@vkontakte/videoplayer-core 2.0.128-dev.699ea99e.0 → 2.0.128-dev.6c63bff4.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/es2018.esm.js CHANGED
@@ -1,19 +1,19 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.128-dev.699ea99e.0
3
- * Tue, 04 Mar 2025 11:03:36 GMT
2
+ * @vkontakte/videoplayer-core v2.0.128-dev.6c63bff4.0
3
+ * Tue, 04 Mar 2025 10:51:50 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-128/doc/
5
5
  */
6
- var JT=Object.create;var td=Object.defineProperty;var ZT=Object.getOwnPropertyDescriptor;var eI=Object.getOwnPropertyNames;var tI=Object.getPrototypeOf,rI=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var iI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of eI(e))!rI.call(a,i)&&i!==t&&td(a,i,{get:()=>e[i],enumerable:!(r=ZT(e,i))||r.enumerable});return a};var D=(a,e,t)=>(t=a!=null?JT(tI(a)):{},iI(e||!a||!a.__esModule?td(t,"default",{value:a,enumerable:!0}):t,a));var J=m((ao,id)=>{"use strict";var gi=function(a){return a&&a.Math===Math&&a};id.exports=gi(typeof globalThis=="object"&&globalThis)||gi(typeof window=="object"&&window)||gi(typeof self=="object"&&self)||gi(typeof global=="object"&&global)||gi(typeof ao=="object"&&ao)||function(){return this}()||Function("return this")()});var oe=m((V0,ad)=>{"use strict";ad.exports=function(a){try{return!!a()}catch(e){return!0}}});var vi=m((B0,sd)=>{"use strict";var aI=oe();sd.exports=!aI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var so=m((O0,ld)=>{"use strict";var sI=vi(),ud=Function.prototype,nd=ud.apply,od=ud.call;ld.exports=typeof Reflect=="object"&&Reflect.apply||(sI?od.bind(nd):function(){return od.apply(nd,arguments)})});var re=m((_0,pd)=>{"use strict";var cd=vi(),dd=Function.prototype,no=dd.call,nI=cd&&dd.bind.bind(no,no);pd.exports=cd?nI:function(a){return function(){return no.apply(a,arguments)}}});var Jt=m((N0,fd)=>{"use strict";var hd=re(),oI=hd({}.toString),uI=hd("".slice);fd.exports=function(a){return uI(oI(a),8,-1)}});var oo=m((F0,md)=>{"use strict";var lI=Jt(),cI=re();md.exports=function(a){if(lI(a)==="Function")return cI(a)}});var K=m((q0,bd)=>{"use strict";var uo=typeof document=="object"&&document.all;bd.exports=typeof uo=="undefined"&&uo!==void 0?function(a){return typeof a=="function"||a===uo}:function(a){return typeof a=="function"}});var Le=m((U0,gd)=>{"use strict";var dI=oe();gd.exports=!dI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Re=m((H0,vd)=>{"use strict";var pI=vi(),fs=Function.prototype.call;vd.exports=pI?fs.bind(fs):function(){return fs.apply(fs,arguments)}});var lo=m(Td=>{"use strict";var Sd={}.propertyIsEnumerable,yd=Object.getOwnPropertyDescriptor,hI=yd&&!Sd.call({1:2},1);Td.f=hI?function(e){var t=yd(this,e);return!!t&&t.enumerable}:Sd});var Si=m((Q0,Id)=>{"use strict";Id.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var xd=m((G0,Ed)=>{"use strict";var fI=re(),mI=oe(),bI=Jt(),co=Object,gI=fI("".split);Ed.exports=mI(function(){return!co("z").propertyIsEnumerable(0)})?function(a){return bI(a)==="String"?gI(a,""):co(a)}:co});var Lr=m((W0,Pd)=>{"use strict";Pd.exports=function(a){return a==null}});var kt=m((Y0,wd)=>{"use strict";var vI=Lr(),SI=TypeError;wd.exports=function(a){if(vI(a))throw new SI("Can't call method on "+a);return a}});var Zt=m((z0,Ad)=>{"use strict";var yI=xd(),TI=kt();Ad.exports=function(a){return yI(TI(a))}});var $e=m((K0,kd)=>{"use strict";var II=K();kd.exports=function(a){return typeof a=="object"?a!==null:II(a)}});var Rr=m((X0,Ld)=>{"use strict";Ld.exports={}});var ut=m((J0,$d)=>{"use strict";var po=Rr(),ho=J(),EI=K(),Rd=function(a){return EI(a)?a:void 0};$d.exports=function(a,e){return arguments.length<2?Rd(po[a])||Rd(ho[a]):po[a]&&po[a][e]||ho[a]&&ho[a][e]}});var yi=m((Z0,Md)=>{"use strict";var xI=re();Md.exports=xI({}.isPrototypeOf)});var er=m((eV,Vd)=>{"use strict";var PI=J(),Dd=PI.navigator,Cd=Dd&&Dd.userAgent;Vd.exports=Cd?String(Cd):""});var mo=m((tV,qd)=>{"use strict";var Fd=J(),fo=er(),Bd=Fd.process,Od=Fd.Deno,_d=Bd&&Bd.versions||Od&&Od.version,Nd=_d&&_d.v8,je,ms;Nd&&(je=Nd.split("."),ms=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!ms&&fo&&(je=fo.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=fo.match(/Chrome\/(\d+)/),je&&(ms=+je[1])));qd.exports=ms});var bo=m((rV,Hd)=>{"use strict";var Ud=mo(),wI=oe(),AI=J(),kI=AI.String;Hd.exports=!!Object.getOwnPropertySymbols&&!wI(function(){var a=Symbol("symbol detection");return!kI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Ud&&Ud<41})});var go=m((iV,jd)=>{"use strict";var LI=bo();jd.exports=LI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var vo=m((aV,Qd)=>{"use strict";var RI=ut(),$I=K(),MI=yi(),DI=go(),CI=Object;Qd.exports=DI?function(a){return typeof a=="symbol"}:function(a){var e=RI("Symbol");return $I(e)&&MI(e.prototype,CI(a))}});var Ti=m((sV,Gd)=>{"use strict";var VI=String;Gd.exports=function(a){try{return VI(a)}catch(e){return"Object"}}});var Ze=m((nV,Wd)=>{"use strict";var BI=K(),OI=Ti(),_I=TypeError;Wd.exports=function(a){if(BI(a))return a;throw new _I(OI(a)+" is not a function")}});var Ii=m((oV,Yd)=>{"use strict";var NI=Ze(),FI=Lr();Yd.exports=function(a,e){var t=a[e];return FI(t)?void 0:NI(t)}});var Kd=m((uV,zd)=>{"use strict";var So=Re(),yo=K(),To=$e(),qI=TypeError;zd.exports=function(a,e){var t,r;if(e==="string"&&yo(t=a.toString)&&!To(r=So(t,a))||yo(t=a.valueOf)&&!To(r=So(t,a))||e!=="string"&&yo(t=a.toString)&&!To(r=So(t,a)))return r;throw new qI("Can't convert object to primitive value")}});var Qe=m((lV,Xd)=>{"use strict";Xd.exports=!0});var ep=m((cV,Zd)=>{"use strict";var Jd=J(),UI=Object.defineProperty;Zd.exports=function(a,e){try{UI(Jd,a,{value:e,configurable:!0,writable:!0})}catch(t){Jd[a]=e}return e}});var Ei=m((dV,ip)=>{"use strict";var HI=Qe(),jI=J(),QI=ep(),tp="__core-js_shared__",rp=ip.exports=jI[tp]||QI(tp,{});(rp.versions||(rp.versions=[])).push({version:"3.38.0",mode:HI?"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 Io=m((pV,sp)=>{"use strict";var ap=Ei();sp.exports=function(a,e){return ap[a]||(ap[a]=e||{})}});var $r=m((hV,np)=>{"use strict";var GI=kt(),WI=Object;np.exports=function(a){return WI(GI(a))}});var Ge=m((fV,op)=>{"use strict";var YI=re(),zI=$r(),KI=YI({}.hasOwnProperty);op.exports=Object.hasOwn||function(e,t){return KI(zI(e),t)}});var Eo=m((mV,up)=>{"use strict";var XI=re(),JI=0,ZI=Math.random(),eE=XI(1 .toString);up.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+eE(++JI+ZI,36)}});var ue=m((bV,cp)=>{"use strict";var tE=J(),rE=Io(),lp=Ge(),iE=Eo(),aE=bo(),sE=go(),Mr=tE.Symbol,xo=rE("wks"),nE=sE?Mr.for||Mr:Mr&&Mr.withoutSetter||iE;cp.exports=function(a){return lp(xo,a)||(xo[a]=aE&&lp(Mr,a)?Mr[a]:nE("Symbol."+a)),xo[a]}});var fp=m((gV,hp)=>{"use strict";var oE=Re(),dp=$e(),pp=vo(),uE=Ii(),lE=Kd(),cE=ue(),dE=TypeError,pE=cE("toPrimitive");hp.exports=function(a,e){if(!dp(a)||pp(a))return a;var t=uE(a,pE),r;if(t){if(e===void 0&&(e="default"),r=oE(t,a,e),!dp(r)||pp(r))return r;throw new dE("Can't convert object to primitive value")}return e===void 0&&(e="number"),lE(a,e)}});var Po=m((vV,mp)=>{"use strict";var hE=fp(),fE=vo();mp.exports=function(a){var e=hE(a,"string");return fE(e)?e:e+""}});var bs=m((SV,gp)=>{"use strict";var mE=J(),bp=$e(),wo=mE.document,bE=bp(wo)&&bp(wo.createElement);gp.exports=function(a){return bE?wo.createElement(a):{}}});var Ao=m((yV,vp)=>{"use strict";var gE=Le(),vE=oe(),SE=bs();vp.exports=!gE&&!vE(function(){return Object.defineProperty(SE("div"),"a",{get:function(){return 7}}).a!==7})});var Tp=m(yp=>{"use strict";var yE=Le(),TE=Re(),IE=lo(),EE=Si(),xE=Zt(),PE=Po(),wE=Ge(),AE=Ao(),Sp=Object.getOwnPropertyDescriptor;yp.f=yE?Sp:function(e,t){if(e=xE(e),t=PE(t),AE)try{return Sp(e,t)}catch(r){}if(wE(e,t))return EE(!TE(IE.f,e,t),e[t])}});var ko=m((IV,Ip)=>{"use strict";var kE=oe(),LE=K(),RE=/#|\.prototype\./,xi=function(a,e){var t=ME[$E(a)];return t===CE?!0:t===DE?!1:LE(e)?kE(e):!!e},$E=xi.normalize=function(a){return String(a).replace(RE,".").toLowerCase()},ME=xi.data={},DE=xi.NATIVE="N",CE=xi.POLYFILL="P";Ip.exports=xi});var Dr=m((EV,xp)=>{"use strict";var Ep=oo(),VE=Ze(),BE=vi(),OE=Ep(Ep.bind);xp.exports=function(a,e){return VE(a),e===void 0?a:BE?OE(a,e):function(){return a.apply(e,arguments)}}});var Lo=m((xV,Pp)=>{"use strict";var _E=Le(),NE=oe();Pp.exports=_E&&NE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var et=m((PV,wp)=>{"use strict";var FE=$e(),qE=String,UE=TypeError;wp.exports=function(a){if(FE(a))return a;throw new UE(qE(a)+" is not an object")}});var tr=m(kp=>{"use strict";var HE=Le(),jE=Ao(),QE=Lo(),gs=et(),Ap=Po(),GE=TypeError,Ro=Object.defineProperty,WE=Object.getOwnPropertyDescriptor,$o="enumerable",Mo="configurable",Do="writable";kp.f=HE?QE?function(e,t,r){if(gs(e),t=Ap(t),gs(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Do in r&&!r[Do]){var i=WE(e,t);i&&i[Do]&&(e[t]=r.value,r={configurable:Mo in r?r[Mo]:i[Mo],enumerable:$o in r?r[$o]:i[$o],writable:!1})}return Ro(e,t,r)}:Ro:function(e,t,r){if(gs(e),t=Ap(t),gs(r),jE)try{return Ro(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new GE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Cr=m((AV,Lp)=>{"use strict";var YE=Le(),zE=tr(),KE=Si();Lp.exports=YE?function(a,e,t){return zE.f(a,e,KE(1,t))}:function(a,e,t){return a[e]=t,a}});var te=m((kV,$p)=>{"use strict";var Pi=J(),XE=so(),JE=oo(),ZE=K(),ex=Tp().f,tx=ko(),Vr=Rr(),rx=Dr(),Br=Cr(),Rp=Ge();Ei();var ix=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 XE(a,this,arguments)};return e.prototype=a.prototype,e};$p.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Pi:i?Pi[t]:Pi[t]&&Pi[t].prototype,o=r?Vr:Vr[t]||Br(Vr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,v;for(p in e)l=tx(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Rp(n,p),f=o[p],c&&(a.dontCallGetSet?(v=ex(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=rx(h,Pi):a.wrap&&c?g=ix(h):s&&ZE(h)?g=JE(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Br(g,"sham",!0),Br(o,p,g),s&&(d=t+"Prototype",Rp(Vr,d)||Br(Vr,d,{}),Br(Vr[d],p,h),a.real&&u&&(l||!u[p])&&Br(u,p,h)))}});var Dp=m((LV,Mp)=>{"use strict";var ax=Math.ceil,sx=Math.floor;Mp.exports=Math.trunc||function(e){var t=+e;return(t>0?sx:ax)(t)}});var wi=m((RV,Cp)=>{"use strict";var nx=Dp();Cp.exports=function(a){var e=+a;return e!==e||e===0?0:nx(e)}});var Bp=m(($V,Vp)=>{"use strict";var ox=wi(),ux=Math.max,lx=Math.min;Vp.exports=function(a,e){var t=ox(a);return t<0?ux(t+e,0):lx(t,e)}});var Co=m((MV,Op)=>{"use strict";var cx=wi(),dx=Math.min;Op.exports=function(a){var e=cx(a);return e>0?dx(e,9007199254740991):0}});var Or=m((DV,_p)=>{"use strict";var px=Co();_p.exports=function(a){return px(a.length)}});var Vo=m((CV,Fp)=>{"use strict";var hx=Zt(),fx=Bp(),mx=Or(),Np=function(a){return function(e,t,r){var i=hx(e),s=mx(i);if(s===0)return!a&&-1;var n=fx(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}};Fp.exports={includes:Np(!0),indexOf:Np(!1)}});var Ai=m((VV,qp)=>{"use strict";qp.exports=function(){}});var Up=m(()=>{"use strict";var bx=te(),gx=Vo().includes,vx=oe(),Sx=Ai(),yx=vx(function(){return!Array(1).includes()});bx({target:"Array",proto:!0,forced:yx},{includes:function(e){return gx(this,e,arguments.length>1?arguments[1]:void 0)}});Sx("includes")});var Lt=m((_V,Hp)=>{"use strict";var Tx=ut();Hp.exports=Tx});var Qp=m((NV,jp)=>{"use strict";Up();var Ix=Lt();jp.exports=Ix("Array","includes")});var Wp=m((FV,Gp)=>{"use strict";var Ex=Qp();Gp.exports=Ex});var We=m((qV,Yp)=>{"use strict";var xx=Wp();Yp.exports=xx});var ys=m((ZV,rh)=>{"use strict";var Mx=Io(),Dx=Eo(),th=Mx("keys");rh.exports=function(a){return th[a]||(th[a]=Dx(a))}});var ah=m((eB,ih)=>{"use strict";var Cx=oe();ih.exports=!Cx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Ts=m((tB,nh)=>{"use strict";var Vx=Ge(),Bx=K(),Ox=$r(),_x=ys(),Nx=ah(),sh=_x("IE_PROTO"),_o=Object,Fx=_o.prototype;nh.exports=Nx?_o.getPrototypeOf:function(a){var e=Ox(a);if(Vx(e,sh))return e[sh];var t=e.constructor;return Bx(t)&&e instanceof t?t.prototype:e instanceof _o?Fx:null}});var Is=m((rB,oh)=>{"use strict";oh.exports={}});var ch=m((iB,lh)=>{"use strict";var qx=re(),No=Ge(),Ux=Zt(),Hx=Vo().indexOf,jx=Is(),uh=qx([].push);lh.exports=function(a,e){var t=Ux(a),r=0,i=[],s;for(s in t)!No(jx,s)&&No(t,s)&&uh(i,s);for(;e.length>r;)No(t,s=e[r++])&&(~Hx(i,s)||uh(i,s));return i}});var Fo=m((aB,dh)=>{"use strict";dh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var qo=m((sB,ph)=>{"use strict";var Qx=ch(),Gx=Fo();ph.exports=Object.keys||function(e){return Qx(e,Gx)}});var Uo=m((nB,gh)=>{"use strict";var fh=Le(),Wx=oe(),mh=re(),Yx=Ts(),zx=qo(),Kx=Zt(),Xx=lo().f,bh=mh(Xx),Jx=mh([].push),Zx=fh&&Wx(function(){var a=Object.create(null);return a[2]=2,!bh(a,2)}),hh=function(a){return function(e){for(var t=Kx(e),r=zx(t),i=Zx&&Yx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!fh||(i?u in t:bh(t,u)))&&Jx(o,a?[u,t[u]]:t[u]);return o}};gh.exports={entries:hh(!0),values:hh(!1)}});var vh=m(()=>{"use strict";var eP=te(),tP=Uo().entries;eP({target:"Object",stat:!0},{entries:function(e){return tP(e)}})});var yh=m((lB,Sh)=>{"use strict";vh();var rP=Rr();Sh.exports=rP.Object.entries});var Ih=m((cB,Th)=>{"use strict";var iP=yh();Th.exports=iP});var _r=m((dB,Eh)=>{"use strict";var aP=Ih();Eh.exports=aP});var rr=m((pB,xh)=>{"use strict";xh.exports={}});var Ah=m((hB,wh)=>{"use strict";var sP=J(),nP=K(),Ph=sP.WeakMap;wh.exports=nP(Ph)&&/native code/.test(String(Ph))});var Go=m((fB,Rh)=>{"use strict";var oP=Ah(),Lh=J(),uP=$e(),lP=Cr(),Ho=Ge(),jo=Ei(),cP=ys(),dP=Is(),kh="Object already initialized",Qo=Lh.TypeError,pP=Lh.WeakMap,Es,ki,xs,hP=function(a){return xs(a)?ki(a):Es(a,{})},fP=function(a){return function(e){var t;if(!uP(e)||(t=ki(e)).type!==a)throw new Qo("Incompatible receiver, "+a+" required");return t}};oP||jo.state?(Ye=jo.state||(jo.state=new pP),Ye.get=Ye.get,Ye.has=Ye.has,Ye.set=Ye.set,Es=function(a,e){if(Ye.has(a))throw new Qo(kh);return e.facade=a,Ye.set(a,e),e},ki=function(a){return Ye.get(a)||{}},xs=function(a){return Ye.has(a)}):(ir=cP("state"),dP[ir]=!0,Es=function(a,e){if(Ho(a,ir))throw new Qo(kh);return e.facade=a,lP(a,ir,e),e},ki=function(a){return Ho(a,ir)?a[ir]:{}},xs=function(a){return Ho(a,ir)});var Ye,ir;Rh.exports={set:Es,get:ki,has:xs,enforce:hP,getterFor:fP}});var zo=m((mB,Mh)=>{"use strict";var Wo=Le(),mP=Ge(),$h=Function.prototype,bP=Wo&&Object.getOwnPropertyDescriptor,Yo=mP($h,"name"),gP=Yo&&function(){}.name==="something",vP=Yo&&(!Wo||Wo&&bP($h,"name").configurable);Mh.exports={EXISTS:Yo,PROPER:gP,CONFIGURABLE:vP}});var Ch=m(Dh=>{"use strict";var SP=Le(),yP=Lo(),TP=tr(),IP=et(),EP=Zt(),xP=qo();Dh.f=SP&&!yP?Object.defineProperties:function(e,t){IP(e);for(var r=EP(t),i=xP(t),s=i.length,n=0,o;s>n;)TP.f(e,o=i[n++],r[o]);return e}});var Ko=m((gB,Vh)=>{"use strict";var PP=ut();Vh.exports=PP("document","documentElement")});var eu=m((vB,Uh)=>{"use strict";var wP=et(),AP=Ch(),Bh=Fo(),kP=Is(),LP=Ko(),RP=bs(),$P=ys(),Oh=">",_h="<",Jo="prototype",Zo="script",Fh=$P("IE_PROTO"),Xo=function(){},qh=function(a){return _h+Zo+Oh+a+_h+"/"+Zo+Oh},Nh=function(a){a.write(qh("")),a.close();var e=a.parentWindow.Object;return a=null,e},MP=function(){var a=RP("iframe"),e="java"+Zo+":",t;return a.style.display="none",LP.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?Nh(Ps):MP():Nh(Ps);for(var a=Bh.length;a--;)delete ws[Jo][Bh[a]];return ws()};kP[Fh]=!0;Uh.exports=Object.create||function(e,t){var r;return e!==null?(Xo[Jo]=wP(e),r=new Xo,Xo[Jo]=null,r[Fh]=e):r=ws(),t===void 0?r:AP.f(r,t)}});var Nr=m((SB,Hh)=>{"use strict";var DP=Cr();Hh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:DP(a,e,t),a}});var au=m((yB,Gh)=>{"use strict";var CP=oe(),VP=K(),BP=$e(),OP=eu(),jh=Ts(),_P=Nr(),NP=ue(),FP=Qe(),iu=NP("iterator"),Qh=!1,lt,tu,ru;[].keys&&(ru=[].keys(),"next"in ru?(tu=jh(jh(ru)),tu!==Object.prototype&&(lt=tu)):Qh=!0);var qP=!BP(lt)||CP(function(){var a={};return lt[iu].call(a)!==a});qP?lt={}:FP&&(lt=OP(lt));VP(lt[iu])||_P(lt,iu,function(){return this});Gh.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Qh}});var As=m((TB,Yh)=>{"use strict";var UP=ue(),HP=UP("toStringTag"),Wh={};Wh[HP]="z";Yh.exports=String(Wh)==="[object z]"});var Li=m((IB,zh)=>{"use strict";var jP=As(),QP=K(),ks=Jt(),GP=ue(),WP=GP("toStringTag"),YP=Object,zP=ks(function(){return arguments}())==="Arguments",KP=function(a,e){try{return a[e]}catch(t){}};zh.exports=jP?ks:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=KP(e=YP(a),WP))=="string"?t:zP?ks(e):(r=ks(e))==="Object"&&QP(e.callee)?"Arguments":r}});var Xh=m((EB,Kh)=>{"use strict";var XP=As(),JP=Li();Kh.exports=XP?{}.toString:function(){return"[object "+JP(this)+"]"}});var Ri=m((xB,Zh)=>{"use strict";var ZP=As(),ew=tr().f,tw=Cr(),rw=Ge(),iw=Xh(),aw=ue(),Jh=aw("toStringTag");Zh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(rw(i,Jh)||ew(i,Jh,{configurable:!0,value:e}),r&&!ZP&&tw(i,"toString",iw))}});var tf=m((PB,ef)=>{"use strict";var sw=au().IteratorPrototype,nw=eu(),ow=Si(),uw=Ri(),lw=rr(),cw=function(){return this};ef.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=nw(sw,{next:ow(+!r,t)}),uw(a,i,!1,!0),lw[i]=cw,a}});var af=m((wB,rf)=>{"use strict";var dw=re(),pw=Ze();rf.exports=function(a,e,t){try{return dw(pw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var nf=m((AB,sf)=>{"use strict";var hw=$e();sf.exports=function(a){return hw(a)||a===null}});var uf=m((kB,of)=>{"use strict";var fw=nf(),mw=String,bw=TypeError;of.exports=function(a){if(fw(a))return a;throw new bw("Can't set "+mw(a)+" as a prototype")}});var su=m((LB,lf)=>{"use strict";var gw=af(),vw=$e(),Sw=kt(),yw=uf();lf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=gw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return Sw(i),yw(s),vw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var yf=m((RB,Sf)=>{"use strict";var Tw=te(),Iw=Re(),Ls=Qe(),gf=zo(),Ew=K(),xw=tf(),cf=Ts(),df=su(),Pw=Ri(),ww=Cr(),nu=Nr(),Aw=ue(),pf=rr(),vf=au(),kw=gf.PROPER,Lw=gf.CONFIGURABLE,hf=vf.IteratorPrototype,Rs=vf.BUGGY_SAFARI_ITERATORS,$i=Aw("iterator"),ff="keys",Mi="values",mf="entries",bf=function(){return this};Sf.exports=function(a,e,t,r,i,s,n){xw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Rs&&v&&v in c)return c[v];switch(v){case ff:return function(){return new t(this,v)};case Mi:return function(){return new t(this,v)};case mf:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[$i]||c["@@iterator"]||i&&c[i],p=!Rs&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=cf(h.call(new a)),f!==Object.prototype&&f.next&&(!Ls&&cf(f)!==hf&&(df?df(f,hf):Ew(f[$i])||nu(f,$i,bf)),Pw(f,u,!0,!0),Ls&&(pf[u]=bf))),kw&&i===Mi&&d&&d.name!==Mi&&(!Ls&&Lw?ww(c,"name",Mi):(l=!0,p=function(){return Iw(d,this)})),i)if(b={values:o(Mi),keys:s?p:o(ff),entries:o(mf)},n)for(g in b)(Rs||l||!(g in c))&&nu(c,g,b[g]);else Tw({target:e,proto:!0,forced:Rs||l},b);return(!Ls||n)&&c[$i]!==p&&nu(c,$i,p,{name:i}),pf[e]=p,b}});var If=m(($B,Tf)=>{"use strict";Tf.exports=function(a,e){return{value:a,done:e}}});var uu=m((MB,Af)=>{"use strict";var Rw=Zt(),ou=Ai(),Ef=rr(),Pf=Go(),$w=tr().f,Mw=yf(),$s=If(),Dw=Qe(),Cw=Le(),wf="Array Iterator",Vw=Pf.set,Bw=Pf.getterFor(wf);Af.exports=Mw(Array,"Array",function(a,e){Vw(this,{type:wf,target:Rw(a),index:0,kind:e})},function(){var a=Bw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,$s(void 0,!0);switch(a.kind){case"keys":return $s(t,!1);case"values":return $s(e[t],!1)}return $s([t,e[t]],!1)},"values");var xf=Ef.Arguments=Ef.Array;ou("keys");ou("values");ou("entries");if(!Dw&&Cw&&xf.name!=="values")try{$w(xf,"name",{value:"values"})}catch(a){}});var Lf=m((DB,kf)=>{"use strict";var Ow=ue(),_w=rr(),Nw=Ow("iterator"),Fw=Array.prototype;kf.exports=function(a){return a!==void 0&&(_w.Array===a||Fw[Nw]===a)}});var lu=m((CB,$f)=>{"use strict";var qw=Li(),Rf=Ii(),Uw=Lr(),Hw=rr(),jw=ue(),Qw=jw("iterator");$f.exports=function(a){if(!Uw(a))return Rf(a,Qw)||Rf(a,"@@iterator")||Hw[qw(a)]}});var Df=m((VB,Mf)=>{"use strict";var Gw=Re(),Ww=Ze(),Yw=et(),zw=Ti(),Kw=lu(),Xw=TypeError;Mf.exports=function(a,e){var t=arguments.length<2?Kw(a):e;if(Ww(t))return Yw(Gw(t,a));throw new Xw(zw(a)+" is not iterable")}});var Bf=m((BB,Vf)=>{"use strict";var Jw=Re(),Cf=et(),Zw=Ii();Vf.exports=function(a,e,t){var r,i;Cf(a);try{if(r=Zw(a,"return"),!r){if(e==="throw")throw t;return t}r=Jw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Cf(r),t}});var Ds=m((OB,Ff)=>{"use strict";var eA=Dr(),tA=Re(),rA=et(),iA=Ti(),aA=Lf(),sA=Or(),Of=yi(),nA=Df(),oA=lu(),_f=Bf(),uA=TypeError,Ms=function(a,e){this.stopped=a,this.result=e},Nf=Ms.prototype;Ff.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=eA(e,r),l,c,d,p,h,f,b,g=function(S){return l&&_f(l,"normal",S),new Ms(!0,S)},v=function(S){return i?(rA(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=oA(a),!c)throw new uA(iA(a)+" is not iterable");if(aA(c)){for(d=0,p=sA(a);p>d;d++)if(h=v(a[d]),h&&Of(Nf,h))return h;return new Ms(!1)}l=nA(a,c)}for(f=s?a.next:l.next;!(b=tA(f,l)).done;){try{h=v(b.value)}catch(S){_f(l,"throw",S)}if(typeof h=="object"&&h&&Of(Nf,h))return h}return new Ms(!1)}});var Uf=m((_B,qf)=>{"use strict";var lA=Le(),cA=tr(),dA=Si();qf.exports=function(a,e,t){lA?cA.f(a,e,dA(0,t)):a[e]=t}});var Hf=m(()=>{"use strict";var pA=te(),hA=Ds(),fA=Uf();pA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return hA(e,function(r,i){fA(t,r,i)},{AS_ENTRIES:!0}),t}})});var Qf=m((qB,jf)=>{"use strict";uu();Hf();var mA=Rr();jf.exports=mA.Object.fromEntries});var Wf=m((UB,Gf)=>{"use strict";Gf.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var zf=m(()=>{"use strict";uu();var bA=Wf(),gA=J(),vA=Ri(),Yf=rr();for(Cs in bA)vA(gA[Cs],Cs),Yf[Cs]=Yf.Array;var Cs});var Xf=m((QB,Kf)=>{"use strict";var SA=Qf();zf();Kf.exports=SA});var cu=m((GB,Jf)=>{"use strict";var yA=Xf();Jf.exports=yA});var Zf=m(()=>{"use strict"});var du=m((zB,em)=>{"use strict";var Di=J(),TA=er(),IA=Jt(),Vs=function(a){return TA.slice(0,a.length)===a};em.exports=function(){return Vs("Bun/")?"BUN":Vs("Cloudflare-Workers")?"CLOUDFLARE":Vs("Deno/")?"DENO":Vs("Node.js/")?"NODE":Di.Bun&&typeof Bun.version=="string"?"BUN":Di.Deno&&typeof Deno.version=="object"?"DENO":IA(Di.process)==="process"?"NODE":Di.window&&Di.document?"BROWSER":"REST"}()});var Bs=m((KB,tm)=>{"use strict";var EA=du();tm.exports=EA==="NODE"});var im=m((XB,rm)=>{"use strict";var xA=tr();rm.exports=function(a,e,t){return xA.f(a,e,t)}});var nm=m((JB,sm)=>{"use strict";var PA=ut(),wA=im(),AA=ue(),kA=Le(),am=AA("species");sm.exports=function(a){var e=PA(a);kA&&e&&!e[am]&&wA(e,am,{configurable:!0,get:function(){return this}})}});var um=m((ZB,om)=>{"use strict";var LA=yi(),RA=TypeError;om.exports=function(a,e){if(LA(e,a))return a;throw new RA("Incorrect invocation")}});var hu=m((eO,lm)=>{"use strict";var $A=re(),MA=K(),pu=Ei(),DA=$A(Function.toString);MA(pu.inspectSource)||(pu.inspectSource=function(a){return DA(a)});lm.exports=pu.inspectSource});var mu=m((tO,fm)=>{"use strict";var CA=re(),VA=oe(),cm=K(),BA=Li(),OA=ut(),_A=hu(),dm=function(){},pm=OA("Reflect","construct"),fu=/^\s*(?:class|function)\b/,NA=CA(fu.exec),FA=!fu.test(dm),Ci=function(e){if(!cm(e))return!1;try{return pm(dm,[],e),!0}catch(t){return!1}},hm=function(e){if(!cm(e))return!1;switch(BA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return FA||!!NA(fu,_A(e))}catch(t){return!0}};hm.sham=!0;fm.exports=!pm||VA(function(){var a;return Ci(Ci.call)||!Ci(Object)||!Ci(function(){a=!0})||a})?hm:Ci});var bm=m((rO,mm)=>{"use strict";var qA=mu(),UA=Ti(),HA=TypeError;mm.exports=function(a){if(qA(a))return a;throw new HA(UA(a)+" is not a constructor")}});var bu=m((iO,vm)=>{"use strict";var gm=et(),jA=bm(),QA=Lr(),GA=ue(),WA=GA("species");vm.exports=function(a,e){var t=gm(a).constructor,r;return t===void 0||QA(r=gm(t)[WA])?e:jA(r)}});var ym=m((aO,Sm)=>{"use strict";var YA=re();Sm.exports=YA([].slice)});var Im=m((sO,Tm)=>{"use strict";var zA=TypeError;Tm.exports=function(a,e){if(a<e)throw new zA("Not enough arguments");return a}});var gu=m((nO,Em)=>{"use strict";var KA=er();Em.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(KA)});var wu=m((oO,Mm)=>{"use strict";var Me=J(),XA=so(),JA=Dr(),xm=K(),ZA=Ge(),$m=oe(),Pm=Ko(),ek=ym(),wm=bs(),tk=Im(),rk=gu(),ik=Bs(),Eu=Me.setImmediate,xu=Me.clearImmediate,ak=Me.process,vu=Me.Dispatch,sk=Me.Function,Am=Me.MessageChannel,nk=Me.String,Su=0,Vi={},km="onreadystatechange",Bi,ar,yu,Tu;$m(function(){Bi=Me.location});var Pu=function(a){if(ZA(Vi,a)){var e=Vi[a];delete Vi[a],e()}},Iu=function(a){return function(){Pu(a)}},Lm=function(a){Pu(a.data)},Rm=function(a){Me.postMessage(nk(a),Bi.protocol+"//"+Bi.host)};(!Eu||!xu)&&(Eu=function(e){tk(arguments.length,1);var t=xm(e)?e:sk(e),r=ek(arguments,1);return Vi[++Su]=function(){XA(t,void 0,r)},ar(Su),Su},xu=function(e){delete Vi[e]},ik?ar=function(a){ak.nextTick(Iu(a))}:vu&&vu.now?ar=function(a){vu.now(Iu(a))}:Am&&!rk?(yu=new Am,Tu=yu.port2,yu.port1.onmessage=Lm,ar=JA(Tu.postMessage,Tu)):Me.addEventListener&&xm(Me.postMessage)&&!Me.importScripts&&Bi&&Bi.protocol!=="file:"&&!$m(Rm)?(ar=Rm,Me.addEventListener("message",Lm,!1)):km in wm("script")?ar=function(a){Pm.appendChild(wm("script"))[km]=function(){Pm.removeChild(this),Pu(a)}}:ar=function(a){setTimeout(Iu(a),0)});Mm.exports={set:Eu,clear:xu}});var Vm=m((uO,Cm)=>{"use strict";var Dm=J(),ok=Le(),uk=Object.getOwnPropertyDescriptor;Cm.exports=function(a){if(!ok)return Dm[a];var e=uk(Dm,a);return e&&e.value}});var Au=m((lO,Om)=>{"use strict";var Bm=function(){this.head=null,this.tail=null};Bm.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}}};Om.exports=Bm});var Nm=m((cO,_m)=>{"use strict";var lk=er();_m.exports=/ipad|iphone|ipod/i.test(lk)&&typeof Pebble!="undefined"});var qm=m((dO,Fm)=>{"use strict";var ck=er();Fm.exports=/web0s(?!.*chrome)/i.test(ck)});var Ym=m((pO,Wm)=>{"use strict";var qr=J(),dk=Vm(),Um=Dr(),ku=wu().set,pk=Au(),hk=gu(),fk=Nm(),mk=qm(),Lu=Bs(),Hm=qr.MutationObserver||qr.WebKitMutationObserver,jm=qr.document,Qm=qr.process,Os=qr.Promise,Mu=dk("queueMicrotask"),Fr,Ru,$u,_s,Gm;Mu||(Oi=new pk,_i=function(){var a,e;for(Lu&&(a=Qm.domain)&&a.exit();e=Oi.get();)try{e()}catch(t){throw Oi.head&&Fr(),t}a&&a.enter()},!hk&&!Lu&&!mk&&Hm&&jm?(Ru=!0,$u=jm.createTextNode(""),new Hm(_i).observe($u,{characterData:!0}),Fr=function(){$u.data=Ru=!Ru}):!fk&&Os&&Os.resolve?(_s=Os.resolve(void 0),_s.constructor=Os,Gm=Um(_s.then,_s),Fr=function(){Gm(_i)}):Lu?Fr=function(){Qm.nextTick(_i)}:(ku=Um(ku,qr),Fr=function(){ku(_i)}),Mu=function(a){Oi.head||Fr(),Oi.add(a)});var Oi,_i;Wm.exports=Mu});var Km=m((hO,zm)=>{"use strict";zm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ns=m((fO,Xm)=>{"use strict";Xm.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var sr=m((mO,Jm)=>{"use strict";var bk=J();Jm.exports=bk.Promise});var Ur=m((bO,rb)=>{"use strict";var gk=J(),Ni=sr(),vk=K(),Sk=ko(),yk=hu(),Tk=ue(),Zm=du(),Ik=Qe(),Du=mo(),eb=Ni&&Ni.prototype,Ek=Tk("species"),Cu=!1,tb=vk(gk.PromiseRejectionEvent),xk=Sk("Promise",function(){var a=yk(Ni),e=a!==String(Ni);if(!e&&Du===66||Ik&&!(eb.catch&&eb.finally))return!0;if(!Du||Du<51||!/native code/.test(a)){var t=new Ni(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Ek]=r,Cu=t.then(function(){})instanceof r,!Cu)return!0}return!e&&(Zm==="BROWSER"||Zm==="DENO")&&!tb});rb.exports={CONSTRUCTOR:xk,REJECTION_EVENT:tb,SUBCLASSING:Cu}});var Hr=m((gO,ab)=>{"use strict";var ib=Ze(),Pk=TypeError,wk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Pk("Bad Promise constructor");e=r,t=i}),this.resolve=ib(e),this.reject=ib(t)};ab.exports.f=function(a){return new wk(a)}});var Eb=m(()=>{"use strict";var Ak=te(),kk=Qe(),Hs=Bs(),Rt=J(),Wr=Re(),sb=Nr(),nb=su(),Lk=Ri(),Rk=nm(),$k=Ze(),Us=K(),Mk=$e(),Dk=um(),Ck=bu(),db=wu().set,Nu=Ym(),Vk=Km(),Bk=Ns(),Ok=Au(),pb=Go(),js=sr(),Fu=Ur(),hb=Hr(),Qs="Promise",fb=Fu.CONSTRUCTOR,_k=Fu.REJECTION_EVENT,Nk=Fu.SUBCLASSING,Vu=pb.getterFor(Qs),Fk=pb.set,jr=js&&js.prototype,nr=js,Fs=jr,mb=Rt.TypeError,Bu=Rt.document,qu=Rt.process,Ou=hb.f,qk=Ou,Uk=!!(Bu&&Bu.createEvent&&Rt.dispatchEvent),bb="unhandledrejection",Hk="rejectionhandled",ob=0,gb=1,jk=2,Uu=1,vb=2,qs,ub,Qk,lb,Sb=function(a){var e;return Mk(a)&&Us(e=a.then)?e:!1},yb=function(a,e){var t=e.value,r=e.state===gb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===vb&&Wk(e),e.rejection=Uu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new mb("Promise-chain cycle")):(l=Sb(u))?Wr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Tb=function(a,e){a.notified||(a.notified=!0,Nu(function(){for(var t=a.reactions,r;r=t.get();)yb(r,a);a.notified=!1,e&&!a.rejection&&Gk(a)}))},Ib=function(a,e,t){var r,i;Uk?(r=Bu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Rt.dispatchEvent(r)):r={promise:e,reason:t},!_k&&(i=Rt["on"+a])?i(r):a===bb&&Vk("Unhandled promise rejection",t)},Gk=function(a){Wr(db,Rt,function(){var e=a.facade,t=a.value,r=cb(a),i;if(r&&(i=Bk(function(){Hs?qu.emit("unhandledRejection",t,e):Ib(bb,e,t)}),a.rejection=Hs||cb(a)?vb:Uu,i.error))throw i.value})},cb=function(a){return a.rejection!==Uu&&!a.parent},Wk=function(a){Wr(db,Rt,function(){var e=a.facade;Hs?qu.emit("rejectionHandled",e):Ib(Hk,e,a.value)})},Qr=function(a,e,t){return function(r){a(e,r,t)}},Gr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=jk,Tb(a,!0))},_u=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new mb("Promise can't be resolved itself");var r=Sb(e);r?Nu(function(){var i={done:!1};try{Wr(r,e,Qr(_u,i,a),Qr(Gr,i,a))}catch(s){Gr(i,s,a)}}):(a.value=e,a.state=gb,Tb(a,!1))}catch(i){Gr({done:!1},i,a)}}};if(fb&&(nr=function(e){Dk(this,Fs),$k(e),Wr(qs,this);var t=Vu(this);try{e(Qr(_u,t),Qr(Gr,t))}catch(r){Gr(t,r)}},Fs=nr.prototype,qs=function(e){Fk(this,{type:Qs,done:!1,notified:!1,parent:!1,reactions:new Ok,rejection:!1,state:ob,value:void 0})},qs.prototype=sb(Fs,"then",function(e,t){var r=Vu(this),i=Ou(Ck(this,nr));return r.parent=!0,i.ok=Us(e)?e:!0,i.fail=Us(t)&&t,i.domain=Hs?qu.domain:void 0,r.state===ob?r.reactions.add(i):Nu(function(){yb(i,r)}),i.promise}),ub=function(){var a=new qs,e=Vu(a);this.promise=a,this.resolve=Qr(_u,e),this.reject=Qr(Gr,e)},hb.f=Ou=function(a){return a===nr||a===Qk?new ub(a):qk(a)},!kk&&Us(js)&&jr!==Object.prototype)){lb=jr.then,Nk||sb(jr,"then",function(e,t){var r=this;return new nr(function(i,s){Wr(lb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete jr.constructor}catch(a){}nb&&nb(jr,Fs)}Ak({global:!0,constructor:!0,wrap:!0,forced:fb},{Promise:nr});Lk(nr,Qs,!1,!0);Rk(Qs)});var kb=m((yO,Ab)=>{"use strict";var Yk=ue(),Pb=Yk("iterator"),wb=!1;try{xb=0,Hu={next:function(){return{done:!!xb++}},return:function(){wb=!0}},Hu[Pb]=function(){return this},Array.from(Hu,function(){throw 2})}catch(a){}var xb,Hu;Ab.exports=function(a,e){try{if(!e&&!wb)return!1}catch(i){return!1}var t=!1;try{var r={};r[Pb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var ju=m((TO,Lb)=>{"use strict";var zk=sr(),Kk=kb(),Xk=Ur().CONSTRUCTOR;Lb.exports=Xk||!Kk(function(a){zk.all(a).then(void 0,function(){})})});var Rb=m(()=>{"use strict";var Jk=te(),Zk=Re(),eL=Ze(),tL=Hr(),rL=Ns(),iL=Ds(),aL=ju();Jk({target:"Promise",stat:!0,forced:aL},{all:function(e){var t=this,r=tL.f(t),i=r.resolve,s=r.reject,n=rL(function(){var o=eL(t.resolve),u=[],l=0,c=1;iL(e,function(d){var p=l++,h=!1;c++,Zk(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 Mb=m(()=>{"use strict";var sL=te(),nL=Qe(),oL=Ur().CONSTRUCTOR,Gu=sr(),uL=ut(),lL=K(),cL=Nr(),$b=Gu&&Gu.prototype;sL({target:"Promise",proto:!0,forced:oL,real:!0},{catch:function(a){return this.then(void 0,a)}});!nL&&lL(Gu)&&(Qu=uL("Promise").prototype.catch,$b.catch!==Qu&&cL($b,"catch",Qu,{unsafe:!0}));var Qu});var Db=m(()=>{"use strict";var dL=te(),pL=Re(),hL=Ze(),fL=Hr(),mL=Ns(),bL=Ds(),gL=ju();dL({target:"Promise",stat:!0,forced:gL},{race:function(e){var t=this,r=fL.f(t),i=r.reject,s=mL(function(){var n=hL(t.resolve);bL(e,function(o){pL(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Cb=m(()=>{"use strict";var vL=te(),SL=Hr(),yL=Ur().CONSTRUCTOR;vL({target:"Promise",stat:!0,forced:yL},{reject:function(e){var t=SL.f(this),r=t.reject;return r(e),t.promise}})});var Wu=m((RO,Vb)=>{"use strict";var TL=et(),IL=$e(),EL=Hr();Vb.exports=function(a,e){if(TL(a),IL(e)&&e.constructor===a)return e;var t=EL.f(a),r=t.resolve;return r(e),t.promise}});var _b=m(()=>{"use strict";var xL=te(),PL=ut(),Bb=Qe(),wL=sr(),Ob=Ur().CONSTRUCTOR,AL=Wu(),kL=PL("Promise"),LL=Bb&&!Ob;xL({target:"Promise",stat:!0,forced:Bb||Ob},{resolve:function(e){return AL(LL&&this===kL?wL:this,e)}})});var Nb=m(()=>{"use strict";Eb();Rb();Mb();Db();Cb();_b()});var Hb=m(()=>{"use strict";var RL=te(),$L=Qe(),Gs=sr(),ML=oe(),qb=ut(),Ub=K(),DL=bu(),Fb=Wu(),CL=Nr(),zu=Gs&&Gs.prototype,VL=!!Gs&&ML(function(){zu.finally.call({then:function(){}},function(){})});RL({target:"Promise",proto:!0,real:!0,forced:VL},{finally:function(a){var e=DL(this,qb("Promise")),t=Ub(a);return this.then(t?function(r){return Fb(e,a()).then(function(){return r})}:a,t?function(r){return Fb(e,a()).then(function(){throw r})}:a)}});!$L&&Ub(Gs)&&(Yu=qb("Promise").prototype.finally,zu.finally!==Yu&&CL(zu,"finally",Yu,{unsafe:!0}));var Yu});var Qb=m((OO,jb)=>{"use strict";Zf();Nb();Hb();var BL=Lt();jb.exports=BL("Promise","finally")});var Wb=m((_O,Gb)=>{"use strict";var OL=Qb();Gb.exports=OL});var Ws=m((NO,Yb)=>{"use strict";var _L=Wb();Yb.exports=_L});var og=m(()=>{"use strict";var JL=te(),ZL=Uo().values;JL({target:"Object",stat:!0},{values:function(e){return ZL(e)}})});var lg=m((E_,ug)=>{"use strict";og();var eR=Rr();ug.exports=eR.Object.values});var dg=m((x_,cg)=>{"use strict";var tR=lg();cg.exports=tR});var zr=m((P_,pg)=>{"use strict";var rR=dg();pg.exports=rR});var Pg=m(()=>{"use strict";var vR=te(),SR=$r(),yR=Or(),TR=wi(),IR=Ai();vR({target:"Array",proto:!0},{at:function(e){var t=SR(this),r=yR(t),i=TR(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});IR("at")});var Ag=m((Z_,wg)=>{"use strict";Pg();var ER=Lt();wg.exports=ER("Array","at")});var Lg=m((eN,kg)=>{"use strict";var xR=Ag();kg.exports=xR});var Vt=m((tN,Rg)=>{"use strict";var PR=Lg();Rg.exports=PR});var vl=m((_F,dv)=>{"use strict";var u$=Jt();dv.exports=Array.isArray||function(e){return u$(e)==="Array"}});var hv=m((NF,pv)=>{"use strict";var l$=TypeError,c$=9007199254740991;pv.exports=function(a){if(a>c$)throw l$("Maximum allowed index exceeded");return a}});var bv=m((FF,mv)=>{"use strict";var d$=vl(),p$=Or(),h$=hv(),f$=Dr(),fv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?f$(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&d$(d)?(p=p$(d),u=fv(a,e,d,p,u,s-1)-1):(h$(u+1),a[u]=d),u++),l++;return u};mv.exports=fv});var yv=m((qF,Sv)=>{"use strict";var gv=vl(),m$=mu(),b$=$e(),g$=ue(),v$=g$("species"),vv=Array;Sv.exports=function(a){var e;return gv(a)&&(e=a.constructor,m$(e)&&(e===vv||gv(e.prototype))?e=void 0:b$(e)&&(e=e[v$],e===null&&(e=void 0))),e===void 0?vv:e}});var Iv=m((UF,Tv)=>{"use strict";var S$=yv();Tv.exports=function(a,e){return new(S$(a))(e===0?0:e)}});var Ev=m(()=>{"use strict";var y$=te(),T$=bv(),I$=Ze(),E$=$r(),x$=Or(),P$=Iv();y$({target:"Array",proto:!0},{flatMap:function(e){var t=E$(this),r=x$(t),i;return I$(e),i=P$(t,0),i.length=T$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var xv=m(()=>{"use strict";var w$=Ai();w$("flatMap")});var wv=m((WF,Pv)=>{"use strict";Ev();xv();var A$=Lt();Pv.exports=A$("Array","flatMap")});var kv=m((YF,Av)=>{"use strict";var k$=wv();Av.exports=k$});var Sl=m((zF,Lv)=>{"use strict";var L$=kv();Lv.exports=L$});var ta=m((sq,zv)=>{"use strict";var O$=Li(),_$=String;zv.exports=function(a){if(O$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return _$(a)}});var Tl=m((nq,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=m((oq,Jv)=>{"use strict";var N$=re(),F$=kt(),q$=ta(),El=Tl(),Xv=N$("".replace),U$=RegExp("^["+El+"]+"),H$=RegExp("(^|[^"+El+"])["+El+"]+$"),Il=function(a){return function(e){var t=q$(F$(e));return a&1&&(t=Xv(t,U$,"")),a&2&&(t=Xv(t,H$,"$1")),t}};Jv.exports={start:Il(1),end:Il(2),trim:Il(3)}});var iS=m((uq,rS)=>{"use strict";var j$=zo().PROPER,Q$=oe(),eS=Tl(),tS="\u200B\x85\u180E";rS.exports=function(a){return Q$(function(){return!!eS[a]()||tS[a]()!==tS||j$&&eS[a].name!==a})}});var xl=m((lq,aS)=>{"use strict";var G$=Zv().start,W$=iS();aS.exports=W$("trimStart")?function(){return G$(this)}:"".trimStart});var nS=m(()=>{"use strict";var Y$=te(),sS=xl();Y$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==sS},{trimLeft:sS})});var uS=m(()=>{"use strict";nS();var z$=te(),oS=xl();z$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==oS},{trimStart:oS})});var cS=m((fq,lS)=>{"use strict";uS();var K$=Lt();lS.exports=K$("String","trimLeft")});var pS=m((mq,dS)=>{"use strict";var X$=cS();dS.exports=X$});var fS=m((bq,hS)=>{"use strict";var J$=pS();hS.exports=J$});var RS=m(()=>{"use strict"});var $S=m(()=>{"use strict"});var DS=m((z1,MS)=>{"use strict";var TM=$e(),IM=Jt(),EM=ue(),xM=EM("match");MS.exports=function(a){var e;return TM(a)&&((e=a[xM])!==void 0?!!e:IM(a)==="RegExp")}});var VS=m((K1,CS)=>{"use strict";var PM=et();CS.exports=function(){var a=PM(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((X1,OS)=>{"use strict";var wM=Re(),AM=Ge(),kM=yi(),LM=VS(),BS=RegExp.prototype;OS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in BS)&&!AM(a,"flags")&&kM(BS,a)?wM(LM,a):e}});var FS=m((J1,NS)=>{"use strict";var Dl=re(),RM=$r(),$M=Math.floor,$l=Dl("".charAt),MM=Dl("".replace),Ml=Dl("".slice),DM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,CM=/\$([$&'`]|\d{1,2})/g;NS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=CM;return i!==void 0&&(i=RM(i),u=DM),MM(s,u,function(l,c){var d;switch($l(c,0)){case"$":return"$";case"&":return a;case"`":return Ml(e,0,t);case"'":return Ml(e,n);case"<":d=i[Ml(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=$M(p/10);return h===0?l:h<=o?r[h-1]===void 0?$l(c,1):r[h-1]+$l(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var HS=m(()=>{"use strict";var VM=te(),BM=Re(),Vl=re(),qS=kt(),OM=K(),_M=Lr(),NM=DS(),ri=ta(),FM=Ii(),qM=_S(),UM=FS(),HM=ue(),jM=Qe(),QM=HM("replace"),GM=TypeError,Cl=Vl("".indexOf),WM=Vl("".replace),US=Vl("".slice),YM=Math.max;VM({target:"String",proto:!0},{replaceAll:function(e,t){var r=qS(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!_M(e)){if(i=NM(e),i&&(s=ri(qS(qM(e))),!~Cl(s,"g")))throw new GM("`.replaceAll` does not allow non-global regexes");if(n=FM(e,QM),n)return BM(n,e,r,t);if(jM&&i)return WM(ri(r),e,t)}for(o=ri(r),u=ri(e),l=OM(t),l||(t=ri(t)),c=u.length,d=YM(1,c),p=Cl(o,u);p!==-1;)h=l?ri(t(u,p,o)):UM(u,o,p,[],void 0,t),b+=US(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Cl(o,u,p+d);return f<o.length&&(b+=US(o,f)),b}})});var QS=m((tH,jS)=>{"use strict";RS();$S();HS();var zM=Lt();jS.exports=zM("String","replaceAll")});var WS=m((rH,GS)=>{"use strict";var KM=QS();GS.exports=KM});var zS=m((iH,YS)=>{"use strict";var XM=WS();YS.exports=XM});var XS=m((aH,KS)=>{"use strict";var JM=wi(),ZM=ta(),eD=kt(),tD=RangeError;KS.exports=function(e){var t=ZM(eD(this)),r="",i=JM(e);if(i<0||i===1/0)throw new tD("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var ry=m((sH,ty)=>{"use strict";var ey=re(),rD=Co(),JS=ta(),iD=XS(),aD=kt(),sD=ey(iD),nD=ey("".slice),oD=Math.ceil,ZS=function(a){return function(e,t,r){var i=JS(aD(e)),s=rD(t),n=i.length,o=r===void 0?" ":JS(r),u,l;return s<=n||o===""?i:(u=s-n,l=sD(o,oD(u/o.length)),l.length>u&&(l=nD(l,0,u)),a?i+l:l+i)}};ty.exports={start:ZS(!1),end:ZS(!0)}});var ay=m((nH,iy)=>{"use strict";var uD=er();iy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(uD)});var sy=m(()=>{"use strict";var lD=te(),cD=ry().start,dD=ay();lD({target:"String",proto:!0,forced:dD},{padStart:function(e){return cD(this,e,arguments.length>1?arguments[1]:void 0)}})});var oy=m((lH,ny)=>{"use strict";sy();var pD=Lt();ny.exports=pD("String","padStart")});var ly=m((cH,uy)=>{"use strict";var hD=oy();uy.exports=hD});var dy=m((dH,cy)=>{"use strict";var fD=ly();cy.exports=fD});var rd="2.0.128-dev.699ea99e.0";var Se=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Se||{}),At=(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))(At||{});var ps=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ps||{}),ro=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ro||{});var io=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(io||{}),hs=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(hs||{});var HT=D(We(),1);import{assertNever as eh,assertNonNullable as Px,isNonNullable as vs,ValueSubject as Bo,Subject as wx,Subscription as Ax,merge as kx,observableFrom as Lx,fromEvent as Kp,map as Xp,tap as Jp,filterChanged as Rx,isNullable as Oo,ErrorCategory as Zp}from"@vkontakte/videoplayer-shared/es2018";var zp=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 Bo(void 0);this.castState$=new Bo("NOT_AVAILABLE");this.errorEvent$=new wx;this.realCastState$=new Bo("NOT_AVAILABLE");this.subscription=new Ax;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||zp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Zp.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(Kp(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 eh(i.sessionState)}})).add(kx(Kp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Jp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Xp(i=>i.castState)),Lx([r.getCastState()])).pipe(Rx(),Xp($x),Jp(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();Px(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:Zp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},$x=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 eh(a)}};var fc=D(We(),1),xT=D(_r(),1),PT=D(cu(),1);var ag=D(Ws(),1);import{assertNever as zb}from"@vkontakte/videoplayer-shared/es2018";var le=(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:zb(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:zb(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as NL,Subject as zs,merge as Kb}from"@vkontakte/videoplayer-shared/es2018";var $=class{constructor(e){this.transitionStarted$=new zs;this.transitionEnded$=new zs;this.transitionUpdated$=new zs;this.forceChanged$=new zs;this.stateChangeStarted$=Kb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Kb(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||NL(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 FL}from"@vkontakte/videoplayer-shared/es2018";var Xb=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 FL(a)}};import{assertNever as Yr,assertNonNullable as or,debounce as Jb,ErrorCategory as Zb,fromEvent as ur,isNonNullable as eg,map as tg,merge as rg,observableFrom as qL,Subject as UL,Subscription as Ku,timeout as HL,getHighestQuality as jL}from"@vkontakte/videoplayer-shared/es2018";var QL=5,GL=5,WL=500,ig=7e3,Fi=class{constructor(e){this.subscription=new Ku;this.loadMediaTimeoutSubscription=new Ku;this.videoState=new $("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:Yr(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:Yr(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:Yr(e)}break}default:Yr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Xb(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 Ku;this.subscription.add(e),this.subscription.add(rg(this.videoState.stateChangeStarted$.pipe(tg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(tg(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 UL;e.add(i.pipe(Jb(WL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(ur(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)>QL)&&i.next(o),s=o})),e.add(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(ur(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<GL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Yr(n)}}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=rg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,qL(["init"])).pipe(Jb(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var 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];or(c);let d=jL(Object.keys(c));or(d);let p=c[d];or(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];or(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];or(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];or(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];or(c),r=le(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:Zb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yr(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 eg(o)&&(n.metadata.title=o),eg(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(HL(ig).subscribe(()=>s(`timeout(${ig})`)))});(0,ag.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:Zb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var bl=D(We(),1);import{clearVideoElement as ng}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as YL}from"@vkontakte/videoplayer-shared/es2018";var sg=a=>{try{a.pause(),a.playbackRate=0,YL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as zL,Subscription as KL}from"@vkontakte/videoplayer-shared/es2018";var Xu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Ju=window.WeakMap?new WeakMap:new Xu,Zu=window.WeakMap?new WeakMap:new Map,XL=(a,e=20)=>{let t=0;return zL(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ye=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?ng(r):(r=document.createElement("video"),a.appendChild(r)),Ju.set(r,i);let s=new KL;return s.add(XL(r,e)),Zu.set(r,s),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},Te=a=>{let e=Zu.get(a);e==null||e.unsubscribe(),Zu.delete(a);let t=Ju.get(a);Ju.delete(a),t?ng(a):sg(a)};var tl=D(zr(),1);import{assertNonNullable as qi,isNonNullable as rt,isNullable as sR,fromEvent as Kr,merge as hg,observableFrom as fg,filterChanged as mg,map as Ui,Subject as bg,Subscription as nR,ValueSubject as oR,ErrorCategory as uR}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as el,isNullable as iR,Subscription as aR}from"@vkontakte/videoplayer-shared/es2018";var Ks=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=iR(i),l=new aR;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},tt=(a,e,t)=>Ks(e,()=>a.loop,r=>{el(r)&&(a.loop=r)},{onError:t}),Ie=(a,e,t,r)=>Ks(e,()=>({muted:a.muted,volume:a.volume}),i=>{el(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Be=(a,e,t,r)=>Ks(e,()=>a.playbackRate,i=>{el(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),$t=Ks;var lR=a=>["__",a.language,a.label].join("|"),cR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},rl=class a{constructor(e){this.available$=new bg;this.current$=new oR(void 0);this.error$=new bg;this.subscription=new nR;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:uR.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($t(t.internalTextTracks,()=>(0,tl.default)(this.internalTracks),s=>{rt(s)&&this.setInternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add($t(t.externalTextTracks,()=>(0,tl.default)(this.externalTracks),s=>{rt(s)&&this.setExternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add($t(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($t(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qi(this.video);let{textTracks:e}=this.video;this.subscription.add(Kr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(hg(Kr(e,"addtrack"),Kr(e,"removetrack"),fg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),mg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(hg(Kr(e,"change"),fg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ui(r=>r&&this.htmlTextTrackToITextTrack(r).id),mg()).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(Kr(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(Kr(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;rt(t.align)&&(i.align=t.align),rt(t.position)&&(i.position=t.position),rt(t.size)&&(i.size=t.size),rt(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){qi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:lR(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){qi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(sR(e)||!cR(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){qi(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){qi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Oe=rl;var dt=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 gg=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},il=a=>{let e=gg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},vg=a=>{let e=gg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as _e,map as Mt,merge as yg,filterChanged as pR,isNonNullable as Tg,Subject as hR,filter as Ig,mapTo as Eg,combine as fR,once as mR,ErrorCategory as bR,ValueSubject as xg,clientChecker as gR}from"@vkontakte/videoplayer-shared/es2018";var dR=3,Sg=(a,e,t=dR)=>{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=>_e(a,y).pipe(Eg(void 0)),r=yg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>_e(a,y))).pipe(Mt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),pR()),i=yg(_e(a,"progress"),_e(a,"timeupdate")).pipe(Mt(()=>Sg(a.buffered,a.currentTime))),s=gR.isSafari?fR({play:e("play").pipe(mR()),playing:e("playing")}).pipe(Eg(void 0)):e("playing"),n=_e(a,"volumechange").pipe(Mt(()=>({muted:a.muted,volume:a.volume}))),o=_e(a,"ratechange").pipe(Mt(()=>a.playbackRate)),u=_e(a,"error").pipe(Ig(()=>!!(a.error||a.played.length)),Mt(()=>{var x;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:bR.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(x=a.error)!=null?x:void 0}})),l=_e(a,"timeupdate").pipe(Mt(()=>a.currentTime)),c=new hR,d=.3,p;l.subscribe(y=>{a.loop&&Tg(p)&&Tg(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(Ig(()=>!a.error&&p!==a.duration)),f=_e(a,"enterpictureinpicture"),b=_e(a,"leavepictureinpicture"),g=new xg(vg(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new xg(il(a));return _e(a,"fullscreenchange").pipe(Mt(()=>il(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$:_e(a,"durationchange").pipe(Mt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as Dt}from"@vkontakte/videoplayer-shared/es2018";var Ct=a=>{switch(a){case"mobile":return Dt.Q_144P;case"lowest":return Dt.Q_240P;case"low":return Dt.Q_360P;case"sd":case"medium":return Dt.Q_480P;case"hd":case"high":return Dt.Q_720P;case"fullhd":case"full":return Dt.Q_1080P;case"quadhd":case"quad":return Dt.Q_1440P;case"ultrahd":case"ultra":return Dt.Q_2160P}};var Bt=D(Vt(),1),Fg=D(We(),1),Zs=D(_r(),1);import{isNonNullable as De,isNullable as Bg,now as qg,isHigher as Og,isHigherOrEqual as ol,isInvariantQuality as _g,isLowerOrEqual as ul,videoSizeToQuality as kR,assertNotEmptyArray as Ug,assertNonNullable as LR}from"@vkontakte/videoplayer-shared/es2018";var al=!1,pt={},$g=a=>{al=a},Mg=()=>{pt={}},Dg=a=>{a(pt)},Hi=(a,e)=>{var t;al&&(pt.meta=(t=pt.meta)!=null?t:{},pt.meta[a]=e)},me=class{constructor(e){this.name=e}next(e){var r,i;if(!al)return;pt.series=(r=pt.series)!=null?r:{};let t=(i=pt.series[this.name])!=null?i:[];t.push([Date.now(),e]),pt.series[this.name]=t}};import{isHigher as wR,isHigherOrEqual as oN,isLower as Cg,isLowerOrEqual as uN,isNonNullable as Xs,isNullable as AR,videoHeightToQuality as Js}from"@vkontakte/videoplayer-shared/es2018";function sl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function nl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&sl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function ji({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return AR(a)||Xs(a.min)&&Xs(a.max)&&Cg(a.max,a.min)||Xs(a.min)&&e&&wR(a.min,e)||Xs(a.max)&&t&&Cg(a.max,t)}function Vg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return ji({limits:{max:a!=null&&a.max?Js(a.max):void 0,min:a!=null&&a.min?Js(a.min):void 0},highestAvailableQuality:e?Js(e):void 0,lowestAvailableQuality:t?Js(t):void 0})}var RR=new me("best_bitrate"),Hg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ll=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Qi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=qg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},jg='Assertion "ABR Tracks is empty array" failed',en=(a,e,t,r)=>{var u;let i=[...e].sort(ll(1)),s=[...t].sort(ll(1)),n=s.filter(l=>De(l.bitrate)&&De(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Bt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Bt.default)(s,-1);return o&&(0,Fg.default)(n,o)?o:n.length?(0,Bt.default)(n,-1):(0,Bt.default)(s,0)},Ng=a=>"quality"in a,Qg=(a,e,t,r)=>{var n;let i=De((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&De(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&qg()-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=Ng(o)?"video":"audio",l=Ng(o)?o.quality:o.bitrate;return e({message:`
6
+ var aI=Object.create;var ld=Object.defineProperty;var sI=Object.getOwnPropertyDescriptor;var nI=Object.getOwnPropertyNames;var oI=Object.getPrototypeOf,uI=Object.prototype.hasOwnProperty;var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var lI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nI(e))!uI.call(a,i)&&i!==t&&ld(a,i,{get:()=>e[i],enumerable:!(r=sI(e,i))||r.enumerable});return a};var C=(a,e,t)=>(t=a!=null?aI(oI(a)):{},lI(e||!a||!a.__esModule?ld(t,"default",{value:a,enumerable:!0}):t,a));var Z=f((ao,dd)=>{"use strict";var bi=function(a){return a&&a.Math===Math&&a};dd.exports=bi(typeof globalThis=="object"&&globalThis)||bi(typeof window=="object"&&window)||bi(typeof self=="object"&&self)||bi(typeof global=="object"&&global)||bi(typeof ao=="object"&&ao)||function(){return this}()||Function("return this")()});var oe=f((N0,pd)=>{"use strict";pd.exports=function(a){try{return!!a()}catch(e){return!0}}});var gi=f((F0,hd)=>{"use strict";var cI=oe();hd.exports=!cI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var so=f((q0,gd)=>{"use strict";var dI=gi(),bd=Function.prototype,md=bd.apply,fd=bd.call;gd.exports=typeof Reflect=="object"&&Reflect.apply||(dI?fd.bind(md):function(){return fd.apply(md,arguments)})});var re=f((U0,yd)=>{"use strict";var vd=gi(),Sd=Function.prototype,no=Sd.call,pI=vd&&Sd.bind.bind(no,no);yd.exports=vd?pI:function(a){return function(){return no.apply(a,arguments)}}});var Jt=f((H0,Id)=>{"use strict";var Td=re(),hI=Td({}.toString),mI=Td("".slice);Id.exports=function(a){return mI(hI(a),8,-1)}});var oo=f((j0,Ed)=>{"use strict";var fI=Jt(),bI=re();Ed.exports=function(a){if(fI(a)==="Function")return bI(a)}});var X=f((Q0,xd)=>{"use strict";var uo=typeof document=="object"&&document.all;xd.exports=typeof uo=="undefined"&&uo!==void 0?function(a){return typeof a=="function"||a===uo}:function(a){return typeof a=="function"}});var Le=f((G0,Pd)=>{"use strict";var gI=oe();Pd.exports=!gI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var $e=f((W0,wd)=>{"use strict";var vI=gi(),ps=Function.prototype.call;wd.exports=vI?ps.bind(ps):function(){return ps.apply(ps,arguments)}});var lo=f(Ld=>{"use strict";var Ad={}.propertyIsEnumerable,kd=Object.getOwnPropertyDescriptor,SI=kd&&!Ad.call({1:2},1);Ld.f=SI?function(e){var t=kd(this,e);return!!t&&t.enumerable}:Ad});var vi=f((z0,$d)=>{"use strict";$d.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Md=f((K0,Rd)=>{"use strict";var yI=re(),TI=oe(),II=Jt(),co=Object,EI=yI("".split);Rd.exports=TI(function(){return!co("z").propertyIsEnumerable(0)})?function(a){return II(a)==="String"?EI(a,""):co(a)}:co});var Ar=f((X0,Dd)=>{"use strict";Dd.exports=function(a){return a==null}});var kt=f((J0,Cd)=>{"use strict";var xI=Ar(),PI=TypeError;Cd.exports=function(a){if(xI(a))throw new PI("Can't call method on "+a);return a}});var Zt=f((Z0,Vd)=>{"use strict";var wI=Md(),AI=kt();Vd.exports=function(a){return wI(AI(a))}});var Re=f((eV,Bd)=>{"use strict";var kI=X();Bd.exports=function(a){return typeof a=="object"?a!==null:kI(a)}});var kr=f((tV,Od)=>{"use strict";Od.exports={}});var ut=f((rV,Nd)=>{"use strict";var po=kr(),ho=Z(),LI=X(),_d=function(a){return LI(a)?a:void 0};Nd.exports=function(a,e){return arguments.length<2?_d(po[a])||_d(ho[a]):po[a]&&po[a][e]||ho[a]&&ho[a][e]}});var Si=f((iV,Fd)=>{"use strict";var $I=re();Fd.exports=$I({}.isPrototypeOf)});var er=f((aV,Hd)=>{"use strict";var RI=Z(),qd=RI.navigator,Ud=qd&&qd.userAgent;Hd.exports=Ud?String(Ud):""});var fo=f((sV,zd)=>{"use strict";var Yd=Z(),mo=er(),jd=Yd.process,Qd=Yd.Deno,Gd=jd&&jd.versions||Qd&&Qd.version,Wd=Gd&&Gd.v8,je,hs;Wd&&(je=Wd.split("."),hs=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!hs&&mo&&(je=mo.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=mo.match(/Chrome\/(\d+)/),je&&(hs=+je[1])));zd.exports=hs});var bo=f((nV,Xd)=>{"use strict";var Kd=fo(),MI=oe(),DI=Z(),CI=DI.String;Xd.exports=!!Object.getOwnPropertySymbols&&!MI(function(){var a=Symbol("symbol detection");return!CI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Kd&&Kd<41})});var go=f((oV,Jd)=>{"use strict";var VI=bo();Jd.exports=VI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var vo=f((uV,Zd)=>{"use strict";var BI=ut(),OI=X(),_I=Si(),NI=go(),FI=Object;Zd.exports=NI?function(a){return typeof a=="symbol"}:function(a){var e=BI("Symbol");return OI(e)&&_I(e.prototype,FI(a))}});var yi=f((lV,ep)=>{"use strict";var qI=String;ep.exports=function(a){try{return qI(a)}catch(e){return"Object"}}});var Ze=f((cV,tp)=>{"use strict";var UI=X(),HI=yi(),jI=TypeError;tp.exports=function(a){if(UI(a))return a;throw new jI(HI(a)+" is not a function")}});var Ti=f((dV,rp)=>{"use strict";var QI=Ze(),GI=Ar();rp.exports=function(a,e){var t=a[e];return GI(t)?void 0:QI(t)}});var ap=f((pV,ip)=>{"use strict";var So=$e(),yo=X(),To=Re(),WI=TypeError;ip.exports=function(a,e){var t,r;if(e==="string"&&yo(t=a.toString)&&!To(r=So(t,a))||yo(t=a.valueOf)&&!To(r=So(t,a))||e!=="string"&&yo(t=a.toString)&&!To(r=So(t,a)))return r;throw new WI("Can't convert object to primitive value")}});var Qe=f((hV,sp)=>{"use strict";sp.exports=!0});var up=f((mV,op)=>{"use strict";var np=Z(),YI=Object.defineProperty;op.exports=function(a,e){try{YI(np,a,{value:e,configurable:!0,writable:!0})}catch(t){np[a]=e}return e}});var Ii=f((fV,dp)=>{"use strict";var zI=Qe(),KI=Z(),XI=up(),lp="__core-js_shared__",cp=dp.exports=KI[lp]||XI(lp,{});(cp.versions||(cp.versions=[])).push({version:"3.38.0",mode:zI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Io=f((bV,hp)=>{"use strict";var pp=Ii();hp.exports=function(a,e){return pp[a]||(pp[a]=e||{})}});var Lr=f((gV,mp)=>{"use strict";var JI=kt(),ZI=Object;mp.exports=function(a){return ZI(JI(a))}});var Ge=f((vV,fp)=>{"use strict";var eE=re(),tE=Lr(),rE=eE({}.hasOwnProperty);fp.exports=Object.hasOwn||function(e,t){return rE(tE(e),t)}});var Eo=f((SV,bp)=>{"use strict";var iE=re(),aE=0,sE=Math.random(),nE=iE(1 .toString);bp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+nE(++aE+sE,36)}});var ue=f((yV,vp)=>{"use strict";var oE=Z(),uE=Io(),gp=Ge(),lE=Eo(),cE=bo(),dE=go(),$r=oE.Symbol,xo=uE("wks"),pE=dE?$r.for||$r:$r&&$r.withoutSetter||lE;vp.exports=function(a){return gp(xo,a)||(xo[a]=cE&&gp($r,a)?$r[a]:pE("Symbol."+a)),xo[a]}});var Ip=f((TV,Tp)=>{"use strict";var hE=$e(),Sp=Re(),yp=vo(),mE=Ti(),fE=ap(),bE=ue(),gE=TypeError,vE=bE("toPrimitive");Tp.exports=function(a,e){if(!Sp(a)||yp(a))return a;var t=mE(a,vE),r;if(t){if(e===void 0&&(e="default"),r=hE(t,a,e),!Sp(r)||yp(r))return r;throw new gE("Can't convert object to primitive value")}return e===void 0&&(e="number"),fE(a,e)}});var Po=f((IV,Ep)=>{"use strict";var SE=Ip(),yE=vo();Ep.exports=function(a){var e=SE(a,"string");return yE(e)?e:e+""}});var ms=f((EV,Pp)=>{"use strict";var TE=Z(),xp=Re(),wo=TE.document,IE=xp(wo)&&xp(wo.createElement);Pp.exports=function(a){return IE?wo.createElement(a):{}}});var Ao=f((xV,wp)=>{"use strict";var EE=Le(),xE=oe(),PE=ms();wp.exports=!EE&&!xE(function(){return Object.defineProperty(PE("div"),"a",{get:function(){return 7}}).a!==7})});var Lp=f(kp=>{"use strict";var wE=Le(),AE=$e(),kE=lo(),LE=vi(),$E=Zt(),RE=Po(),ME=Ge(),DE=Ao(),Ap=Object.getOwnPropertyDescriptor;kp.f=wE?Ap:function(e,t){if(e=$E(e),t=RE(t),DE)try{return Ap(e,t)}catch(r){}if(ME(e,t))return LE(!AE(kE.f,e,t),e[t])}});var ko=f((wV,$p)=>{"use strict";var CE=oe(),VE=X(),BE=/#|\.prototype\./,Ei=function(a,e){var t=_E[OE(a)];return t===FE?!0:t===NE?!1:VE(e)?CE(e):!!e},OE=Ei.normalize=function(a){return String(a).replace(BE,".").toLowerCase()},_E=Ei.data={},NE=Ei.NATIVE="N",FE=Ei.POLYFILL="P";$p.exports=Ei});var Rr=f((AV,Mp)=>{"use strict";var Rp=oo(),qE=Ze(),UE=gi(),HE=Rp(Rp.bind);Mp.exports=function(a,e){return qE(a),e===void 0?a:UE?HE(a,e):function(){return a.apply(e,arguments)}}});var Lo=f((kV,Dp)=>{"use strict";var jE=Le(),QE=oe();Dp.exports=jE&&QE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var et=f((LV,Cp)=>{"use strict";var GE=Re(),WE=String,YE=TypeError;Cp.exports=function(a){if(GE(a))return a;throw new YE(WE(a)+" is not an object")}});var tr=f(Bp=>{"use strict";var zE=Le(),KE=Ao(),XE=Lo(),fs=et(),Vp=Po(),JE=TypeError,$o=Object.defineProperty,ZE=Object.getOwnPropertyDescriptor,Ro="enumerable",Mo="configurable",Do="writable";Bp.f=zE?XE?function(e,t,r){if(fs(e),t=Vp(t),fs(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Do in r&&!r[Do]){var i=ZE(e,t);i&&i[Do]&&(e[t]=r.value,r={configurable:Mo in r?r[Mo]:i[Mo],enumerable:Ro in r?r[Ro]:i[Ro],writable:!1})}return $o(e,t,r)}:$o:function(e,t,r){if(fs(e),t=Vp(t),fs(r),KE)try{return $o(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 Mr=f((RV,Op)=>{"use strict";var ex=Le(),tx=tr(),rx=vi();Op.exports=ex?function(a,e,t){return tx.f(a,e,rx(1,t))}:function(a,e,t){return a[e]=t,a}});var te=f((MV,Np)=>{"use strict";var xi=Z(),ix=so(),ax=oo(),sx=X(),nx=Lp().f,ox=ko(),Dr=kr(),ux=Rr(),Cr=Mr(),_p=Ge();Ii();var lx=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 ix(a,this,arguments)};return e.prototype=a.prototype,e};Np.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?xi:i?xi[t]:xi[t]&&xi[t].prototype,o=r?Dr:Dr[t]||Cr(Dr,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=ox(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&_p(n,p),m=o[p],c&&(a.dontCallGetSet?(v=nx(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=ux(h,xi):a.wrap&&c?g=lx(h):s&&sx(h)?g=ax(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Cr(g,"sham",!0),Cr(o,p,g),s&&(d=t+"Prototype",_p(Dr,d)||Cr(Dr,d,{}),Cr(Dr[d],p,h),a.real&&u&&(l||!u[p])&&Cr(u,p,h)))}});var qp=f((DV,Fp)=>{"use strict";var cx=Math.ceil,dx=Math.floor;Fp.exports=Math.trunc||function(e){var t=+e;return(t>0?dx:cx)(t)}});var Pi=f((CV,Up)=>{"use strict";var px=qp();Up.exports=function(a){var e=+a;return e!==e||e===0?0:px(e)}});var jp=f((VV,Hp)=>{"use strict";var hx=Pi(),mx=Math.max,fx=Math.min;Hp.exports=function(a,e){var t=hx(a);return t<0?mx(t+e,0):fx(t,e)}});var Co=f((BV,Qp)=>{"use strict";var bx=Pi(),gx=Math.min;Qp.exports=function(a){var e=bx(a);return e>0?gx(e,9007199254740991):0}});var Vr=f((OV,Gp)=>{"use strict";var vx=Co();Gp.exports=function(a){return vx(a.length)}});var Vo=f((_V,Yp)=>{"use strict";var Sx=Zt(),yx=jp(),Tx=Vr(),Wp=function(a){return function(e,t,r){var i=Sx(e),s=Tx(i);if(s===0)return!a&&-1;var n=yx(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}};Yp.exports={includes:Wp(!0),indexOf:Wp(!1)}});var wi=f((NV,zp)=>{"use strict";zp.exports=function(){}});var Kp=f(()=>{"use strict";var Ix=te(),Ex=Vo().includes,xx=oe(),Px=wi(),wx=xx(function(){return!Array(1).includes()});Ix({target:"Array",proto:!0,forced:wx},{includes:function(e){return Ex(this,e,arguments.length>1?arguments[1]:void 0)}});Px("includes")});var Lt=f((UV,Xp)=>{"use strict";var Ax=ut();Xp.exports=Ax});var Zp=f((HV,Jp)=>{"use strict";Kp();var kx=Lt();Jp.exports=kx("Array","includes")});var th=f((jV,eh)=>{"use strict";var Lx=Zp();eh.exports=Lx});var We=f((QV,rh)=>{"use strict";var $x=th();rh.exports=$x});var vs=f((iB,ch)=>{"use strict";var _x=Io(),Nx=Eo(),lh=_x("keys");ch.exports=function(a){return lh[a]||(lh[a]=Nx(a))}});var ph=f((aB,dh)=>{"use strict";var Fx=oe();dh.exports=!Fx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Ss=f((sB,mh)=>{"use strict";var qx=Ge(),Ux=X(),Hx=Lr(),jx=vs(),Qx=ph(),hh=jx("IE_PROTO"),_o=Object,Gx=_o.prototype;mh.exports=Qx?_o.getPrototypeOf:function(a){var e=Hx(a);if(qx(e,hh))return e[hh];var t=e.constructor;return Ux(t)&&e instanceof t?t.prototype:e instanceof _o?Gx:null}});var ys=f((nB,fh)=>{"use strict";fh.exports={}});var vh=f((oB,gh)=>{"use strict";var Wx=re(),No=Ge(),Yx=Zt(),zx=Vo().indexOf,Kx=ys(),bh=Wx([].push);gh.exports=function(a,e){var t=Yx(a),r=0,i=[],s;for(s in t)!No(Kx,s)&&No(t,s)&&bh(i,s);for(;e.length>r;)No(t,s=e[r++])&&(~zx(i,s)||bh(i,s));return i}});var Fo=f((uB,Sh)=>{"use strict";Sh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var qo=f((lB,yh)=>{"use strict";var Xx=vh(),Jx=Fo();yh.exports=Object.keys||function(e){return Xx(e,Jx)}});var Uo=f((cB,Ph)=>{"use strict";var Ih=Le(),Zx=oe(),Eh=re(),eP=Ss(),tP=qo(),rP=Zt(),iP=lo().f,xh=Eh(iP),aP=Eh([].push),sP=Ih&&Zx(function(){var a=Object.create(null);return a[2]=2,!xh(a,2)}),Th=function(a){return function(e){for(var t=rP(e),r=tP(t),i=sP&&eP(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Ih||(i?u in t:xh(t,u)))&&aP(o,a?[u,t[u]]:t[u]);return o}};Ph.exports={entries:Th(!0),values:Th(!1)}});var wh=f(()=>{"use strict";var nP=te(),oP=Uo().entries;nP({target:"Object",stat:!0},{entries:function(e){return oP(e)}})});var kh=f((hB,Ah)=>{"use strict";wh();var uP=kr();Ah.exports=uP.Object.entries});var $h=f((mB,Lh)=>{"use strict";var lP=kh();Lh.exports=lP});var Br=f((fB,Rh)=>{"use strict";var cP=$h();Rh.exports=cP});var rr=f((bB,Mh)=>{"use strict";Mh.exports={}});var Vh=f((gB,Ch)=>{"use strict";var dP=Z(),pP=X(),Dh=dP.WeakMap;Ch.exports=pP(Dh)&&/native code/.test(String(Dh))});var Go=f((vB,_h)=>{"use strict";var hP=Vh(),Oh=Z(),mP=Re(),fP=Mr(),Ho=Ge(),jo=Ii(),bP=vs(),gP=ys(),Bh="Object already initialized",Qo=Oh.TypeError,vP=Oh.WeakMap,Ts,Ai,Is,SP=function(a){return Is(a)?Ai(a):Ts(a,{})},yP=function(a){return function(e){var t;if(!mP(e)||(t=Ai(e)).type!==a)throw new Qo("Incompatible receiver, "+a+" required");return t}};hP||jo.state?(Ye=jo.state||(jo.state=new vP),Ye.get=Ye.get,Ye.has=Ye.has,Ye.set=Ye.set,Ts=function(a,e){if(Ye.has(a))throw new Qo(Bh);return e.facade=a,Ye.set(a,e),e},Ai=function(a){return Ye.get(a)||{}},Is=function(a){return Ye.has(a)}):(ir=bP("state"),gP[ir]=!0,Ts=function(a,e){if(Ho(a,ir))throw new Qo(Bh);return e.facade=a,fP(a,ir,e),e},Ai=function(a){return Ho(a,ir)?a[ir]:{}},Is=function(a){return Ho(a,ir)});var Ye,ir;_h.exports={set:Ts,get:Ai,has:Is,enforce:SP,getterFor:yP}});var zo=f((SB,Fh)=>{"use strict";var Wo=Le(),TP=Ge(),Nh=Function.prototype,IP=Wo&&Object.getOwnPropertyDescriptor,Yo=TP(Nh,"name"),EP=Yo&&function(){}.name==="something",xP=Yo&&(!Wo||Wo&&IP(Nh,"name").configurable);Fh.exports={EXISTS:Yo,PROPER:EP,CONFIGURABLE:xP}});var Uh=f(qh=>{"use strict";var PP=Le(),wP=Lo(),AP=tr(),kP=et(),LP=Zt(),$P=qo();qh.f=PP&&!wP?Object.defineProperties:function(e,t){kP(e);for(var r=LP(t),i=$P(t),s=i.length,n=0,o;s>n;)AP.f(e,o=i[n++],r[o]);return e}});var Ko=f((TB,Hh)=>{"use strict";var RP=ut();Hh.exports=RP("document","documentElement")});var eu=f((IB,Kh)=>{"use strict";var MP=et(),DP=Uh(),jh=Fo(),CP=ys(),VP=Ko(),BP=ms(),OP=vs(),Qh=">",Gh="<",Jo="prototype",Zo="script",Yh=OP("IE_PROTO"),Xo=function(){},zh=function(a){return Gh+Zo+Qh+a+Gh+"/"+Zo+Qh},Wh=function(a){a.write(zh("")),a.close();var e=a.parentWindow.Object;return a=null,e},_P=function(){var a=BP("iframe"),e="java"+Zo+":",t;return a.style.display="none",VP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(zh("document.F=Object")),t.close(),t.F},Es,xs=function(){try{Es=new ActiveXObject("htmlfile")}catch(e){}xs=typeof document!="undefined"?document.domain&&Es?Wh(Es):_P():Wh(Es);for(var a=jh.length;a--;)delete xs[Jo][jh[a]];return xs()};CP[Yh]=!0;Kh.exports=Object.create||function(e,t){var r;return e!==null?(Xo[Jo]=MP(e),r=new Xo,Xo[Jo]=null,r[Yh]=e):r=xs(),t===void 0?r:DP.f(r,t)}});var Or=f((EB,Xh)=>{"use strict";var NP=Mr();Xh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:NP(a,e,t),a}});var au=f((xB,em)=>{"use strict";var FP=oe(),qP=X(),UP=Re(),HP=eu(),Jh=Ss(),jP=Or(),QP=ue(),GP=Qe(),iu=QP("iterator"),Zh=!1,lt,tu,ru;[].keys&&(ru=[].keys(),"next"in ru?(tu=Jh(Jh(ru)),tu!==Object.prototype&&(lt=tu)):Zh=!0);var WP=!UP(lt)||FP(function(){var a={};return lt[iu].call(a)!==a});WP?lt={}:GP&&(lt=HP(lt));qP(lt[iu])||jP(lt,iu,function(){return this});em.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Zh}});var Ps=f((PB,rm)=>{"use strict";var YP=ue(),zP=YP("toStringTag"),tm={};tm[zP]="z";rm.exports=String(tm)==="[object z]"});var ki=f((wB,im)=>{"use strict";var KP=Ps(),XP=X(),ws=Jt(),JP=ue(),ZP=JP("toStringTag"),ew=Object,tw=ws(function(){return arguments}())==="Arguments",rw=function(a,e){try{return a[e]}catch(t){}};im.exports=KP?ws:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=rw(e=ew(a),ZP))=="string"?t:tw?ws(e):(r=ws(e))==="Object"&&XP(e.callee)?"Arguments":r}});var sm=f((AB,am)=>{"use strict";var iw=Ps(),aw=ki();am.exports=iw?{}.toString:function(){return"[object "+aw(this)+"]"}});var Li=f((kB,om)=>{"use strict";var sw=Ps(),nw=tr().f,ow=Mr(),uw=Ge(),lw=sm(),cw=ue(),nm=cw("toStringTag");om.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(uw(i,nm)||nw(i,nm,{configurable:!0,value:e}),r&&!sw&&ow(i,"toString",lw))}});var lm=f((LB,um)=>{"use strict";var dw=au().IteratorPrototype,pw=eu(),hw=vi(),mw=Li(),fw=rr(),bw=function(){return this};um.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=pw(dw,{next:hw(+!r,t)}),mw(a,i,!1,!0),fw[i]=bw,a}});var dm=f(($B,cm)=>{"use strict";var gw=re(),vw=Ze();cm.exports=function(a,e,t){try{return gw(vw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var hm=f((RB,pm)=>{"use strict";var Sw=Re();pm.exports=function(a){return Sw(a)||a===null}});var fm=f((MB,mm)=>{"use strict";var yw=hm(),Tw=String,Iw=TypeError;mm.exports=function(a){if(yw(a))return a;throw new Iw("Can't set "+Tw(a)+" as a prototype")}});var su=f((DB,bm)=>{"use strict";var Ew=dm(),xw=Re(),Pw=kt(),ww=fm();bm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Ew(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return Pw(i),ww(s),xw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Am=f((CB,wm)=>{"use strict";var Aw=te(),kw=$e(),As=Qe(),xm=zo(),Lw=X(),$w=lm(),gm=Ss(),vm=su(),Rw=Li(),Mw=Mr(),nu=Or(),Dw=ue(),Sm=rr(),Pm=au(),Cw=xm.PROPER,Vw=xm.CONFIGURABLE,ym=Pm.IteratorPrototype,ks=Pm.BUGGY_SAFARI_ITERATORS,$i=Dw("iterator"),Tm="keys",Ri="values",Im="entries",Em=function(){return this};wm.exports=function(a,e,t,r,i,s,n){$w(t,e,r);var o=function(v){if(v===i&&p)return p;if(!ks&&v&&v in c)return c[v];switch(v){case Tm:return function(){return new t(this,v)};case Ri:return function(){return new t(this,v)};case Im:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[$i]||c["@@iterator"]||i&&c[i],p=!ks&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=gm(h.call(new a)),m!==Object.prototype&&m.next&&(!As&&gm(m)!==ym&&(vm?vm(m,ym):Lw(m[$i])||nu(m,$i,Em)),Rw(m,u,!0,!0),As&&(Sm[u]=Em))),Cw&&i===Ri&&d&&d.name!==Ri&&(!As&&Vw?Mw(c,"name",Ri):(l=!0,p=function(){return kw(d,this)})),i)if(b={values:o(Ri),keys:s?p:o(Tm),entries:o(Im)},n)for(g in b)(ks||l||!(g in c))&&nu(c,g,b[g]);else Aw({target:e,proto:!0,forced:ks||l},b);return(!As||n)&&c[$i]!==p&&nu(c,$i,p,{name:i}),Sm[e]=p,b}});var Lm=f((VB,km)=>{"use strict";km.exports=function(a,e){return{value:a,done:e}}});var uu=f((BB,Cm)=>{"use strict";var Bw=Zt(),ou=wi(),$m=rr(),Mm=Go(),Ow=tr().f,_w=Am(),Ls=Lm(),Nw=Qe(),Fw=Le(),Dm="Array Iterator",qw=Mm.set,Uw=Mm.getterFor(Dm);Cm.exports=_w(Array,"Array",function(a,e){qw(this,{type:Dm,target:Bw(a),index:0,kind:e})},function(){var a=Uw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,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 Rm=$m.Arguments=$m.Array;ou("keys");ou("values");ou("entries");if(!Nw&&Fw&&Rm.name!=="values")try{Ow(Rm,"name",{value:"values"})}catch(a){}});var Bm=f((OB,Vm)=>{"use strict";var Hw=ue(),jw=rr(),Qw=Hw("iterator"),Gw=Array.prototype;Vm.exports=function(a){return a!==void 0&&(jw.Array===a||Gw[Qw]===a)}});var lu=f((_B,_m)=>{"use strict";var Ww=ki(),Om=Ti(),Yw=Ar(),zw=rr(),Kw=ue(),Xw=Kw("iterator");_m.exports=function(a){if(!Yw(a))return Om(a,Xw)||Om(a,"@@iterator")||zw[Ww(a)]}});var Fm=f((NB,Nm)=>{"use strict";var Jw=$e(),Zw=Ze(),eA=et(),tA=yi(),rA=lu(),iA=TypeError;Nm.exports=function(a,e){var t=arguments.length<2?rA(a):e;if(Zw(t))return eA(Jw(t,a));throw new iA(tA(a)+" is not iterable")}});var Hm=f((FB,Um)=>{"use strict";var aA=$e(),qm=et(),sA=Ti();Um.exports=function(a,e,t){var r,i;qm(a);try{if(r=sA(a,"return"),!r){if(e==="throw")throw t;return t}r=aA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return qm(r),t}});var Rs=f((qB,Wm)=>{"use strict";var nA=Rr(),oA=$e(),uA=et(),lA=yi(),cA=Bm(),dA=Vr(),jm=Si(),pA=Fm(),hA=lu(),Qm=Hm(),mA=TypeError,$s=function(a,e){this.stopped=a,this.result=e},Gm=$s.prototype;Wm.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=nA(e,r),l,c,d,p,h,m,b,g=function(y){return l&&Qm(l,"normal",y),new $s(!0,y)},v=function(y){return i?(uA(y),o?u(y[0],y[1],g):u(y[0],y[1])):o?u(y,g):u(y)};if(s)l=a.iterator;else if(n)l=a;else{if(c=hA(a),!c)throw new mA(lA(a)+" is not iterable");if(cA(c)){for(d=0,p=dA(a);p>d;d++)if(h=v(a[d]),h&&jm(Gm,h))return h;return new $s(!1)}l=pA(a,c)}for(m=s?a.next:l.next;!(b=oA(m,l)).done;){try{h=v(b.value)}catch(y){Qm(l,"throw",y)}if(typeof h=="object"&&h&&jm(Gm,h))return h}return new $s(!1)}});var zm=f((UB,Ym)=>{"use strict";var fA=Le(),bA=tr(),gA=vi();Ym.exports=function(a,e,t){fA?bA.f(a,e,gA(0,t)):a[e]=t}});var Km=f(()=>{"use strict";var vA=te(),SA=Rs(),yA=zm();vA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return SA(e,function(r,i){yA(t,r,i)},{AS_ENTRIES:!0}),t}})});var Jm=f((QB,Xm)=>{"use strict";uu();Km();var TA=kr();Xm.exports=TA.Object.fromEntries});var ef=f((GB,Zm)=>{"use strict";Zm.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 rf=f(()=>{"use strict";uu();var IA=ef(),EA=Z(),xA=Li(),tf=rr();for(Ms in IA)xA(EA[Ms],Ms),tf[Ms]=tf.Array;var Ms});var sf=f((zB,af)=>{"use strict";var PA=Jm();rf();af.exports=PA});var cu=f((KB,nf)=>{"use strict";var wA=sf();nf.exports=wA});var of=f(()=>{"use strict"});var du=f((ZB,uf)=>{"use strict";var Mi=Z(),AA=er(),kA=Jt(),Ds=function(a){return AA.slice(0,a.length)===a};uf.exports=function(){return Ds("Bun/")?"BUN":Ds("Cloudflare-Workers")?"CLOUDFLARE":Ds("Deno/")?"DENO":Ds("Node.js/")?"NODE":Mi.Bun&&typeof Bun.version=="string"?"BUN":Mi.Deno&&typeof Deno.version=="object"?"DENO":kA(Mi.process)==="process"?"NODE":Mi.window&&Mi.document?"BROWSER":"REST"}()});var Cs=f((eO,lf)=>{"use strict";var LA=du();lf.exports=LA==="NODE"});var df=f((tO,cf)=>{"use strict";var $A=tr();cf.exports=function(a,e,t){return $A.f(a,e,t)}});var mf=f((rO,hf)=>{"use strict";var RA=ut(),MA=df(),DA=ue(),CA=Le(),pf=DA("species");hf.exports=function(a){var e=RA(a);CA&&e&&!e[pf]&&MA(e,pf,{configurable:!0,get:function(){return this}})}});var bf=f((iO,ff)=>{"use strict";var VA=Si(),BA=TypeError;ff.exports=function(a,e){if(VA(e,a))return a;throw new BA("Incorrect invocation")}});var hu=f((aO,gf)=>{"use strict";var OA=re(),_A=X(),pu=Ii(),NA=OA(Function.toString);_A(pu.inspectSource)||(pu.inspectSource=function(a){return NA(a)});gf.exports=pu.inspectSource});var fu=f((sO,If)=>{"use strict";var FA=re(),qA=oe(),vf=X(),UA=ki(),HA=ut(),jA=hu(),Sf=function(){},yf=HA("Reflect","construct"),mu=/^\s*(?:class|function)\b/,QA=FA(mu.exec),GA=!mu.test(Sf),Di=function(e){if(!vf(e))return!1;try{return yf(Sf,[],e),!0}catch(t){return!1}},Tf=function(e){if(!vf(e))return!1;switch(UA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return GA||!!QA(mu,jA(e))}catch(t){return!0}};Tf.sham=!0;If.exports=!yf||qA(function(){var a;return Di(Di.call)||!Di(Object)||!Di(function(){a=!0})||a})?Tf:Di});var xf=f((nO,Ef)=>{"use strict";var WA=fu(),YA=yi(),zA=TypeError;Ef.exports=function(a){if(WA(a))return a;throw new zA(YA(a)+" is not a constructor")}});var bu=f((oO,wf)=>{"use strict";var Pf=et(),KA=xf(),XA=Ar(),JA=ue(),ZA=JA("species");wf.exports=function(a,e){var t=Pf(a).constructor,r;return t===void 0||XA(r=Pf(t)[ZA])?e:KA(r)}});var kf=f((uO,Af)=>{"use strict";var ek=re();Af.exports=ek([].slice)});var $f=f((lO,Lf)=>{"use strict";var tk=TypeError;Lf.exports=function(a,e){if(a<e)throw new tk("Not enough arguments");return a}});var gu=f((cO,Rf)=>{"use strict";var rk=er();Rf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(rk)});var wu=f((dO,Ff)=>{"use strict";var Me=Z(),ik=so(),ak=Rr(),Mf=X(),sk=Ge(),Nf=oe(),Df=Ko(),nk=kf(),Cf=ms(),ok=$f(),uk=gu(),lk=Cs(),Eu=Me.setImmediate,xu=Me.clearImmediate,ck=Me.process,vu=Me.Dispatch,dk=Me.Function,Vf=Me.MessageChannel,pk=Me.String,Su=0,Ci={},Bf="onreadystatechange",Vi,ar,yu,Tu;Nf(function(){Vi=Me.location});var Pu=function(a){if(sk(Ci,a)){var e=Ci[a];delete Ci[a],e()}},Iu=function(a){return function(){Pu(a)}},Of=function(a){Pu(a.data)},_f=function(a){Me.postMessage(pk(a),Vi.protocol+"//"+Vi.host)};(!Eu||!xu)&&(Eu=function(e){ok(arguments.length,1);var t=Mf(e)?e:dk(e),r=nk(arguments,1);return Ci[++Su]=function(){ik(t,void 0,r)},ar(Su),Su},xu=function(e){delete Ci[e]},lk?ar=function(a){ck.nextTick(Iu(a))}:vu&&vu.now?ar=function(a){vu.now(Iu(a))}:Vf&&!uk?(yu=new Vf,Tu=yu.port2,yu.port1.onmessage=Of,ar=ak(Tu.postMessage,Tu)):Me.addEventListener&&Mf(Me.postMessage)&&!Me.importScripts&&Vi&&Vi.protocol!=="file:"&&!Nf(_f)?(ar=_f,Me.addEventListener("message",Of,!1)):Bf in Cf("script")?ar=function(a){Df.appendChild(Cf("script"))[Bf]=function(){Df.removeChild(this),Pu(a)}}:ar=function(a){setTimeout(Iu(a),0)});Ff.exports={set:Eu,clear:xu}});var Hf=f((pO,Uf)=>{"use strict";var qf=Z(),hk=Le(),mk=Object.getOwnPropertyDescriptor;Uf.exports=function(a){if(!hk)return qf[a];var e=mk(qf,a);return e&&e.value}});var Au=f((hO,Qf)=>{"use strict";var jf=function(){this.head=null,this.tail=null};jf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Qf.exports=jf});var Wf=f((mO,Gf)=>{"use strict";var fk=er();Gf.exports=/ipad|iphone|ipod/i.test(fk)&&typeof Pebble!="undefined"});var zf=f((fO,Yf)=>{"use strict";var bk=er();Yf.exports=/web0s(?!.*chrome)/i.test(bk)});var rb=f((bO,tb)=>{"use strict";var Nr=Z(),gk=Hf(),Kf=Rr(),ku=wu().set,vk=Au(),Sk=gu(),yk=Wf(),Tk=zf(),Lu=Cs(),Xf=Nr.MutationObserver||Nr.WebKitMutationObserver,Jf=Nr.document,Zf=Nr.process,Vs=Nr.Promise,Mu=gk("queueMicrotask"),_r,$u,Ru,Bs,eb;Mu||(Bi=new vk,Oi=function(){var a,e;for(Lu&&(a=Zf.domain)&&a.exit();e=Bi.get();)try{e()}catch(t){throw Bi.head&&_r(),t}a&&a.enter()},!Sk&&!Lu&&!Tk&&Xf&&Jf?($u=!0,Ru=Jf.createTextNode(""),new Xf(Oi).observe(Ru,{characterData:!0}),_r=function(){Ru.data=$u=!$u}):!yk&&Vs&&Vs.resolve?(Bs=Vs.resolve(void 0),Bs.constructor=Vs,eb=Kf(Bs.then,Bs),_r=function(){eb(Oi)}):Lu?_r=function(){Zf.nextTick(Oi)}:(ku=Kf(ku,Nr),_r=function(){ku(Oi)}),Mu=function(a){Bi.head||_r(),Bi.add(a)});var Bi,Oi;tb.exports=Mu});var ab=f((gO,ib)=>{"use strict";ib.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Os=f((vO,sb)=>{"use strict";sb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var sr=f((SO,nb)=>{"use strict";var Ik=Z();nb.exports=Ik.Promise});var Fr=f((yO,cb)=>{"use strict";var Ek=Z(),_i=sr(),xk=X(),Pk=ko(),wk=hu(),Ak=ue(),ob=du(),kk=Qe(),Du=fo(),ub=_i&&_i.prototype,Lk=Ak("species"),Cu=!1,lb=xk(Ek.PromiseRejectionEvent),$k=Pk("Promise",function(){var a=wk(_i),e=a!==String(_i);if(!e&&Du===66||kk&&!(ub.catch&&ub.finally))return!0;if(!Du||Du<51||!/native code/.test(a)){var t=new _i(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Lk]=r,Cu=t.then(function(){})instanceof r,!Cu)return!0}return!e&&(ob==="BROWSER"||ob==="DENO")&&!lb});cb.exports={CONSTRUCTOR:$k,REJECTION_EVENT:lb,SUBCLASSING:Cu}});var qr=f((TO,pb)=>{"use strict";var db=Ze(),Rk=TypeError,Mk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Rk("Bad Promise constructor");e=r,t=i}),this.resolve=db(e),this.reject=db(t)};pb.exports.f=function(a){return new Mk(a)}});var Rb=f(()=>{"use strict";var Dk=te(),Ck=Qe(),qs=Cs(),$t=Z(),Qr=$e(),hb=Or(),mb=su(),Vk=Li(),Bk=mf(),Ok=Ze(),Fs=X(),_k=Re(),Nk=bf(),Fk=bu(),Sb=wu().set,Nu=rb(),qk=ab(),Uk=Os(),Hk=Au(),yb=Go(),Us=sr(),Fu=Fr(),Tb=qr(),Hs="Promise",Ib=Fu.CONSTRUCTOR,jk=Fu.REJECTION_EVENT,Qk=Fu.SUBCLASSING,Vu=yb.getterFor(Hs),Gk=yb.set,Ur=Us&&Us.prototype,nr=Us,_s=Ur,Eb=$t.TypeError,Bu=$t.document,qu=$t.process,Ou=Tb.f,Wk=Ou,Yk=!!(Bu&&Bu.createEvent&&$t.dispatchEvent),xb="unhandledrejection",zk="rejectionhandled",fb=0,Pb=1,Kk=2,Uu=1,wb=2,Ns,bb,Xk,gb,Ab=function(a){var e;return _k(a)&&Fs(e=a.then)?e:!1},kb=function(a,e){var t=e.value,r=e.state===Pb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===wb&&Zk(e),e.rejection=Uu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Eb("Promise-chain cycle")):(l=Ab(u))?Qr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Lb=function(a,e){a.notified||(a.notified=!0,Nu(function(){for(var t=a.reactions,r;r=t.get();)kb(r,a);a.notified=!1,e&&!a.rejection&&Jk(a)}))},$b=function(a,e,t){var r,i;Yk?(r=Bu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),$t.dispatchEvent(r)):r={promise:e,reason:t},!jk&&(i=$t["on"+a])?i(r):a===xb&&qk("Unhandled promise rejection",t)},Jk=function(a){Qr(Sb,$t,function(){var e=a.facade,t=a.value,r=vb(a),i;if(r&&(i=Uk(function(){qs?qu.emit("unhandledRejection",t,e):$b(xb,e,t)}),a.rejection=qs||vb(a)?wb:Uu,i.error))throw i.value})},vb=function(a){return a.rejection!==Uu&&!a.parent},Zk=function(a){Qr(Sb,$t,function(){var e=a.facade;qs?qu.emit("rejectionHandled",e):$b(zk,e,a.value)})},Hr=function(a,e,t){return function(r){a(e,r,t)}},jr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Kk,Lb(a,!0))},_u=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Eb("Promise can't be resolved itself");var r=Ab(e);r?Nu(function(){var i={done:!1};try{Qr(r,e,Hr(_u,i,a),Hr(jr,i,a))}catch(s){jr(i,s,a)}}):(a.value=e,a.state=Pb,Lb(a,!1))}catch(i){jr({done:!1},i,a)}}};if(Ib&&(nr=function(e){Nk(this,_s),Ok(e),Qr(Ns,this);var t=Vu(this);try{e(Hr(_u,t),Hr(jr,t))}catch(r){jr(t,r)}},_s=nr.prototype,Ns=function(e){Gk(this,{type:Hs,done:!1,notified:!1,parent:!1,reactions:new Hk,rejection:!1,state:fb,value:void 0})},Ns.prototype=hb(_s,"then",function(e,t){var r=Vu(this),i=Ou(Fk(this,nr));return r.parent=!0,i.ok=Fs(e)?e:!0,i.fail=Fs(t)&&t,i.domain=qs?qu.domain:void 0,r.state===fb?r.reactions.add(i):Nu(function(){kb(i,r)}),i.promise}),bb=function(){var a=new Ns,e=Vu(a);this.promise=a,this.resolve=Hr(_u,e),this.reject=Hr(jr,e)},Tb.f=Ou=function(a){return a===nr||a===Xk?new bb(a):Wk(a)},!Ck&&Fs(Us)&&Ur!==Object.prototype)){gb=Ur.then,Qk||hb(Ur,"then",function(e,t){var r=this;return new nr(function(i,s){Qr(gb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Ur.constructor}catch(a){}mb&&mb(Ur,_s)}Dk({global:!0,constructor:!0,wrap:!0,forced:Ib},{Promise:nr});Vk(nr,Hs,!1,!0);Bk(Hs)});var Bb=f((xO,Vb)=>{"use strict";var eL=ue(),Db=eL("iterator"),Cb=!1;try{Mb=0,Hu={next:function(){return{done:!!Mb++}},return:function(){Cb=!0}},Hu[Db]=function(){return this},Array.from(Hu,function(){throw 2})}catch(a){}var Mb,Hu;Vb.exports=function(a,e){try{if(!e&&!Cb)return!1}catch(i){return!1}var t=!1;try{var r={};r[Db]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var ju=f((PO,Ob)=>{"use strict";var tL=sr(),rL=Bb(),iL=Fr().CONSTRUCTOR;Ob.exports=iL||!rL(function(a){tL.all(a).then(void 0,function(){})})});var _b=f(()=>{"use strict";var aL=te(),sL=$e(),nL=Ze(),oL=qr(),uL=Os(),lL=Rs(),cL=ju();aL({target:"Promise",stat:!0,forced:cL},{all:function(e){var t=this,r=oL.f(t),i=r.resolve,s=r.reject,n=uL(function(){var o=nL(t.resolve),u=[],l=0,c=1;lL(e,function(d){var p=l++,h=!1;c++,sL(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 Fb=f(()=>{"use strict";var dL=te(),pL=Qe(),hL=Fr().CONSTRUCTOR,Gu=sr(),mL=ut(),fL=X(),bL=Or(),Nb=Gu&&Gu.prototype;dL({target:"Promise",proto:!0,forced:hL,real:!0},{catch:function(a){return this.then(void 0,a)}});!pL&&fL(Gu)&&(Qu=mL("Promise").prototype.catch,Nb.catch!==Qu&&bL(Nb,"catch",Qu,{unsafe:!0}));var Qu});var qb=f(()=>{"use strict";var gL=te(),vL=$e(),SL=Ze(),yL=qr(),TL=Os(),IL=Rs(),EL=ju();gL({target:"Promise",stat:!0,forced:EL},{race:function(e){var t=this,r=yL.f(t),i=r.reject,s=TL(function(){var n=SL(t.resolve);IL(e,function(o){vL(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Ub=f(()=>{"use strict";var xL=te(),PL=qr(),wL=Fr().CONSTRUCTOR;xL({target:"Promise",stat:!0,forced:wL},{reject:function(e){var t=PL.f(this),r=t.reject;return r(e),t.promise}})});var Wu=f((CO,Hb)=>{"use strict";var AL=et(),kL=Re(),LL=qr();Hb.exports=function(a,e){if(AL(a),kL(e)&&e.constructor===a)return e;var t=LL.f(a),r=t.resolve;return r(e),t.promise}});var Gb=f(()=>{"use strict";var $L=te(),RL=ut(),jb=Qe(),ML=sr(),Qb=Fr().CONSTRUCTOR,DL=Wu(),CL=RL("Promise"),VL=jb&&!Qb;$L({target:"Promise",stat:!0,forced:jb||Qb},{resolve:function(e){return DL(VL&&this===CL?ML:this,e)}})});var Wb=f(()=>{"use strict";Rb();_b();Fb();qb();Ub();Gb()});var Xb=f(()=>{"use strict";var BL=te(),OL=Qe(),js=sr(),_L=oe(),zb=ut(),Kb=X(),NL=bu(),Yb=Wu(),FL=Or(),zu=js&&js.prototype,qL=!!js&&_L(function(){zu.finally.call({then:function(){}},function(){})});BL({target:"Promise",proto:!0,real:!0,forced:qL},{finally:function(a){var e=NL(this,zb("Promise")),t=Kb(a);return this.then(t?function(r){return Yb(e,a()).then(function(){return r})}:a,t?function(r){return Yb(e,a()).then(function(){throw r})}:a)}});!OL&&Kb(js)&&(Yu=zb("Promise").prototype.finally,zu.finally!==Yu&&FL(zu,"finally",Yu,{unsafe:!0}));var Yu});var Zb=f((qO,Jb)=>{"use strict";of();Wb();Xb();var UL=Lt();Jb.exports=UL("Promise","finally")});var tg=f((UO,eg)=>{"use strict";var HL=Zb();eg.exports=HL});var Qs=f((HO,rg)=>{"use strict";var jL=tg();rg.exports=jL});var fg=f(()=>{"use strict";var a$=te(),s$=Uo().values;a$({target:"Object",stat:!0},{values:function(e){return s$(e)}})});var gg=f((A_,bg)=>{"use strict";fg();var n$=kr();bg.exports=n$.Object.values});var Sg=f((k_,vg)=>{"use strict";var o$=gg();vg.exports=o$});var Wr=f((L_,yg)=>{"use strict";var u$=Sg();yg.exports=u$});var Dg=f(()=>{"use strict";var x$=te(),P$=Lr(),w$=Vr(),A$=Pi(),k$=wi();x$({target:"Array",proto:!0},{at:function(e){var t=P$(this),r=w$(t),i=A$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});k$("at")});var Vg=f((iN,Cg)=>{"use strict";Dg();var L$=Lt();Cg.exports=L$("Array","at")});var Og=f((aN,Bg)=>{"use strict";var $$=Vg();Bg.exports=$$});var Vt=f((sN,_g)=>{"use strict";var R$=Og();_g.exports=R$});var vl=f((UF,Sv)=>{"use strict";var mR=Jt();Sv.exports=Array.isArray||function(e){return mR(e)==="Array"}});var Tv=f((HF,yv)=>{"use strict";var fR=TypeError,bR=9007199254740991;yv.exports=function(a){if(a>bR)throw fR("Maximum allowed index exceeded");return a}});var xv=f((jF,Ev)=>{"use strict";var gR=vl(),vR=Vr(),SR=Tv(),yR=Rr(),Iv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?yR(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&gR(d)?(p=vR(d),u=Iv(a,e,d,p,u,s-1)-1):(SR(u+1),a[u]=d),u++),l++;return u};Ev.exports=Iv});var kv=f((QF,Av)=>{"use strict";var Pv=vl(),TR=fu(),IR=Re(),ER=ue(),xR=ER("species"),wv=Array;Av.exports=function(a){var e;return Pv(a)&&(e=a.constructor,TR(e)&&(e===wv||Pv(e.prototype))?e=void 0:IR(e)&&(e=e[xR],e===null&&(e=void 0))),e===void 0?wv:e}});var $v=f((GF,Lv)=>{"use strict";var PR=kv();Lv.exports=function(a,e){return new(PR(a))(e===0?0:e)}});var Rv=f(()=>{"use strict";var wR=te(),AR=xv(),kR=Ze(),LR=Lr(),$R=Vr(),RR=$v();wR({target:"Array",proto:!0},{flatMap:function(e){var t=LR(this),r=$R(t),i;return kR(e),i=RR(t,0),i.length=AR(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Mv=f(()=>{"use strict";var MR=wi();MR("flatMap")});var Cv=f((XF,Dv)=>{"use strict";Rv();Mv();var DR=Lt();Dv.exports=DR("Array","flatMap")});var Bv=f((JF,Vv)=>{"use strict";var CR=Cv();Vv.exports=CR});var Sl=f((ZF,Ov)=>{"use strict";var VR=Bv();Ov.exports=VR});var ea=f((lq,iS)=>{"use strict";var HR=ki(),jR=String;iS.exports=function(a){if(HR(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return jR(a)}});var Tl=f((cq,aS)=>{"use strict";aS.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 oS=f((dq,nS)=>{"use strict";var QR=re(),GR=kt(),WR=ea(),El=Tl(),sS=QR("".replace),YR=RegExp("^["+El+"]+"),zR=RegExp("(^|[^"+El+"])["+El+"]+$"),Il=function(a){return function(e){var t=WR(GR(e));return a&1&&(t=sS(t,YR,"")),a&2&&(t=sS(t,zR,"$1")),t}};nS.exports={start:Il(1),end:Il(2),trim:Il(3)}});var dS=f((pq,cS)=>{"use strict";var KR=zo().PROPER,XR=oe(),uS=Tl(),lS="\u200B\x85\u180E";cS.exports=function(a){return XR(function(){return!!uS[a]()||lS[a]()!==lS||KR&&uS[a].name!==a})}});var xl=f((hq,pS)=>{"use strict";var JR=oS().start,ZR=dS();pS.exports=ZR("trimStart")?function(){return JR(this)}:"".trimStart});var mS=f(()=>{"use strict";var eM=te(),hS=xl();eM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==hS},{trimLeft:hS})});var bS=f(()=>{"use strict";mS();var tM=te(),fS=xl();tM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==fS},{trimStart:fS})});var vS=f((vq,gS)=>{"use strict";bS();var rM=Lt();gS.exports=rM("String","trimLeft")});var yS=f((Sq,SS)=>{"use strict";var iM=vS();SS.exports=iM});var IS=f((yq,TS)=>{"use strict";var aM=yS();TS.exports=aM});var _S=f(()=>{"use strict"});var NS=f(()=>{"use strict"});var qS=f((Z1,FS)=>{"use strict";var AM=Re(),kM=Jt(),LM=ue(),$M=LM("match");FS.exports=function(a){var e;return AM(a)&&((e=a[$M])!==void 0?!!e:kM(a)==="RegExp")}});var HS=f((eH,US)=>{"use strict";var RM=et();US.exports=function(){var a=RM(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 GS=f((tH,QS)=>{"use strict";var MM=$e(),DM=Ge(),CM=Si(),VM=HS(),jS=RegExp.prototype;QS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in jS)&&!DM(a,"flags")&&CM(jS,a)?MM(VM,a):e}});var YS=f((rH,WS)=>{"use strict";var Dl=re(),BM=Lr(),OM=Math.floor,Rl=Dl("".charAt),_M=Dl("".replace),Ml=Dl("".slice),NM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,FM=/\$([$&'`]|\d{1,2})/g;WS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=FM;return i!==void 0&&(i=BM(i),u=NM),_M(s,u,function(l,c){var d;switch(Rl(c,0)){case"$":return"$";case"&":return a;case"`":return Ml(e,0,t);case"'":return Ml(e,n);case"<":d=i[Ml(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=OM(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 XS=f(()=>{"use strict";var qM=te(),UM=$e(),Vl=re(),zS=kt(),HM=X(),jM=Ar(),QM=qS(),ei=ea(),GM=Ti(),WM=GS(),YM=YS(),zM=ue(),KM=Qe(),XM=zM("replace"),JM=TypeError,Cl=Vl("".indexOf),ZM=Vl("".replace),KS=Vl("".slice),eD=Math.max;qM({target:"String",proto:!0},{replaceAll:function(e,t){var r=zS(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!jM(e)){if(i=QM(e),i&&(s=ei(zS(WM(e))),!~Cl(s,"g")))throw new JM("`.replaceAll` does not allow non-global regexes");if(n=GM(e,XM),n)return UM(n,e,r,t);if(KM&&i)return ZM(ei(r),e,t)}for(o=ei(r),u=ei(e),l=HM(t),l||(t=ei(t)),c=u.length,d=eD(1,c),p=Cl(o,u);p!==-1;)h=l?ei(t(u,p,o)):YM(u,o,p,[],void 0,t),b+=KS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Cl(o,u,p+d);return m<o.length&&(b+=KS(o,m)),b}})});var ZS=f((sH,JS)=>{"use strict";_S();NS();XS();var tD=Lt();JS.exports=tD("String","replaceAll")});var ty=f((nH,ey)=>{"use strict";var rD=ZS();ey.exports=rD});var iy=f((oH,ry)=>{"use strict";var iD=ty();ry.exports=iD});var sy=f((uH,ay)=>{"use strict";var aD=Pi(),sD=ea(),nD=kt(),oD=RangeError;ay.exports=function(e){var t=sD(nD(this)),r="",i=aD(e);if(i<0||i===1/0)throw new oD("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var cy=f((lH,ly)=>{"use strict";var uy=re(),uD=Co(),ny=ea(),lD=sy(),cD=kt(),dD=uy(lD),pD=uy("".slice),hD=Math.ceil,oy=function(a){return function(e,t,r){var i=ny(cD(e)),s=uD(t),n=i.length,o=r===void 0?" ":ny(r),u,l;return s<=n||o===""?i:(u=s-n,l=dD(o,hD(u/o.length)),l.length>u&&(l=pD(l,0,u)),a?i+l:l+i)}};ly.exports={start:oy(!1),end:oy(!0)}});var py=f((cH,dy)=>{"use strict";var mD=er();dy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(mD)});var hy=f(()=>{"use strict";var fD=te(),bD=cy().start,gD=py();fD({target:"String",proto:!0,forced:gD},{padStart:function(e){return bD(this,e,arguments.length>1?arguments[1]:void 0)}})});var fy=f((hH,my)=>{"use strict";hy();var vD=Lt();my.exports=vD("String","padStart")});var gy=f((mH,by)=>{"use strict";var SD=fy();by.exports=SD});var Sy=f((fH,vy)=>{"use strict";var yD=gy();vy.exports=yD});var cd="2.0.128-dev.6c63bff4.0";var ke=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ke||{}),At=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(At||{});var cs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(cs||{}),ro=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ro||{});var io=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(io||{}),ds=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(ds||{});var KT=C(We(),1);import{assertNever as uh,assertNonNullable as Rx,isNonNullable as bs,ValueSubject as Bo,Subject as Mx,Subscription as Dx,merge as Cx,observableFrom as Vx,fromEvent as ah,map as sh,tap as nh,filterChanged as Bx,isNullable as Oo,ErrorCategory as oh}from"@vkontakte/videoplayer-shared/es2018";var ih=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 gs=class{constructor(e){this.connection$=new Bo(void 0);this.castState$=new Bo("NOT_AVAILABLE");this.errorEvent$=new Mx;this.realCastState$=new Bo("NOT_AVAILABLE");this.subscription=new Dx;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=bs((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||ih("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:oh.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(){bs(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(ah(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 uh(i.sessionState)}})).add(Cx(ah(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(nh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),sh(i=>i.castState)),Vx([r.getCastState()])).pipe(Bx(),sh(Ox),nh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=bs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Rx(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"?bs(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:oh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Ox=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return uh(a)}};var gc=C(We(),1),MT=C(Br(),1),DT=C(cu(),1);var pg=C(Qs(),1);import{assertNever as ig}from"@vkontakte/videoplayer-shared/es2018";var le=(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:ig(t)}return a},Gs=(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:ig(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as QL,Subject as Ws,merge as ag}from"@vkontakte/videoplayer-shared/es2018";var R=class{constructor(e){this.transitionStarted$=new Ws;this.transitionEnded$=new Ws;this.transitionUpdated$=new Ws;this.forceChanged$=new Ws;this.stateChangeStarted$=ag(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=ag(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||QL(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 GL}from"@vkontakte/videoplayer-shared/es2018";var sg=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 GL(a)}};import{assertNever as Gr,assertNonNullable as or,debounce as ng,ErrorCategory as og,fromEvent as ur,isNonNullable as ug,map as lg,merge as cg,observableFrom as WL,Subject as YL,Subscription as Ku,timeout as zL,getHighestQuality as KL}from"@vkontakte/videoplayer-shared/es2018";var XL=5,JL=5,ZL=500,dg=7e3,Ni=class{constructor(e){this.subscription=new Ku;this.loadMediaTimeoutSubscription=new Ku;this.videoState=new R("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:Gr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Gr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Gr(e)}break}default:Gr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(sg(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 Ku;this.subscription.add(e),this.subscription.add(cg(this.videoState.stateChangeStarted$.pipe(lg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(lg(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 YL;e.add(i.pipe(ng(ZL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(ur(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)>XL)&&i.next(o),s=o})),e.add(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(ur(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<JL&&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:Gr(n)}}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=cg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,WL(["init"])).pipe(ng(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];or(c);let d=KL(Object.keys(c));or(d);let p=c[d];or(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];or(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];or(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];or(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];or(c),r=le(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:og.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Gr(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 ug(o)&&(n.metadata.title=o),ug(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(zL(dg).subscribe(()=>s(`timeout(${dg})`)))});(0,pg.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:og.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var bl=C(We(),1);import{clearVideoElement as mg}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as e$}from"@vkontakte/videoplayer-shared/es2018";var hg=a=>{try{a.pause(),a.playbackRate=0,e$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as t$,Subscription as r$}from"@vkontakte/videoplayer-shared/es2018";var Xu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Ju=window.WeakMap?new WeakMap:new Xu,Zu=window.WeakMap?new WeakMap:new Map,i$=(a,e=20)=>{let t=0;return t$(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Se=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?mg(r):(r=document.createElement("video"),a.appendChild(r)),Ju.set(r,i);let s=new r$;return s.add(i$(r,e)),Zu.set(r,s),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},ye=a=>{let e=Zu.get(a);e==null||e.unsubscribe(),Zu.delete(a);let t=Ju.get(a);Ju.delete(a),t?mg(a):hg(a)};var tl=C(Wr(),1);import{assertNonNullable as Fi,isNonNullable as rt,isNullable as d$,fromEvent as Yr,merge as Tg,observableFrom as Ig,filterChanged as Eg,map as qi,Subject as xg,Subscription as p$,ValueSubject as h$,ErrorCategory as m$}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as el,isNullable as l$,Subscription as c$}from"@vkontakte/videoplayer-shared/es2018";var Ys=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=l$(i),l=new c$;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},tt=(a,e,t)=>Ys(e,()=>a.loop,r=>{el(r)&&(a.loop=r)},{onError:t}),Te=(a,e,t,r)=>Ys(e,()=>({muted:a.muted,volume:a.volume}),i=>{el(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Be=(a,e,t,r)=>Ys(e,()=>a.playbackRate,i=>{el(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Rt=Ys;var f$=a=>["__",a.language,a.label].join("|"),b$=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},rl=class a{constructor(e){this.available$=new xg;this.current$=new h$(void 0);this.error$=new xg;this.subscription=new p$;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:m$.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(Rt(t.internalTextTracks,()=>(0,tl.default)(this.internalTracks),s=>{rt(s)&&this.setInternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(qi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Rt(t.externalTextTracks,()=>(0,tl.default)(this.externalTracks),s=>{rt(s)&&this.setExternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(qi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Rt(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(Rt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Fi(this.video);let{textTracks:e}=this.video;this.subscription.add(Yr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Tg(Yr(e,"addtrack"),Yr(e,"removetrack"),Ig(["init"])).pipe(qi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Eg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Tg(Yr(e,"change"),Ig(["init"])).pipe(qi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),qi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Eg()).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(Yr(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(Yr(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;rt(t.align)&&(i.align=t.align),rt(t.position)&&(i.position=t.position),rt(t.size)&&(i.size=t.size),rt(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Fi(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:f$(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){Fi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(d$(e)||!b$(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){Fi(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){Fi(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)}},Oe=rl;var lr=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 Pg=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},il=a=>{let e=Pg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},wg=a=>{let e=Pg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as _e,map as Mt,merge as kg,filterChanged as v$,isNonNullable as Lg,Subject as S$,filter as $g,mapTo as Rg,combine as y$,once as T$,ErrorCategory as I$,ValueSubject as Mg,clientChecker as E$}from"@vkontakte/videoplayer-shared/es2018";var g$=3,Ag=(a,e,t=g$)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Ie=a=>{let e=S=>_e(a,S).pipe(Rg(void 0)),r=kg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>_e(a,S))).pipe(Mt(S=>S.type==="ended"?a.readyState<2:a.readyState<3),v$()),i=kg(_e(a,"progress"),_e(a,"timeupdate")).pipe(Mt(()=>Ag(a.buffered,a.currentTime))),s=E$.isSafari?y$({play:e("play").pipe(T$()),playing:e("playing")}).pipe(Rg(void 0)):e("playing"),n=_e(a,"volumechange").pipe(Mt(()=>({muted:a.muted,volume:a.volume}))),o=_e(a,"ratechange").pipe(Mt(()=>a.playbackRate)),u=_e(a,"error").pipe($g(()=>!!(a.error||a.played.length)),Mt(()=>{var E;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:I$.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=_e(a,"timeupdate").pipe(Mt(()=>a.currentTime)),c=new S$,d=.3,p;l.subscribe(S=>{a.loop&&Lg(p)&&Lg(S)&&p>=a.duration-d&&S<=d&&c.next(p),p=S});let h=e("pause").pipe($g(()=>!a.error&&p!==a.duration)),m=_e(a,"enterpictureinpicture"),b=_e(a,"leavepictureinpicture"),g=new Mg(wg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Mg(il(a));return _e(a,"fullscreenchange").pipe(Mt(()=>il(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$:_e(a,"durationchange").pipe(Mt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as Dt}from"@vkontakte/videoplayer-shared/es2018";var Ct=a=>{switch(a){case"mobile":return Dt.Q_144P;case"lowest":return Dt.Q_240P;case"low":return Dt.Q_360P;case"sd":case"medium":return Dt.Q_480P;case"hd":case"high":return Dt.Q_720P;case"fullhd":case"full":return Dt.Q_1080P;case"quadhd":case"quad":return Dt.Q_1440P;case"ultrahd":case"ultra":return Dt.Q_2160P}};var Bt=C(Vt(),1),Yg=C(We(),1),Xs=C(Br(),1);import{isNonNullable as De,isNullable as jg,now as zg,isHigher as Qg,isHigherOrEqual as ol,isInvariantQuality as Gg,isLowerOrEqual as ul,videoSizeToQuality as C$,assertNotEmptyArray as Kg,assertNonNullable as V$}from"@vkontakte/videoplayer-shared/es2018";var al=!1,dt={},Ng=a=>{al=a},Fg=()=>{dt={}},qg=a=>{a(dt)},Ui=(a,e)=>{var t;al&&(dt.meta=(t=dt.meta)!=null?t:{},dt.meta[a]=e)},fe=class{constructor(e){this.name=e}next(e){var r,i;if(!al)return;dt.series=(r=dt.series)!=null?r:{};let t=(i=dt.series[this.name])!=null?i:[];t.push([Date.now(),e]),dt.series[this.name]=t}};import{isHigher as M$,isHigherOrEqual as dN,isLower as Ug,isLowerOrEqual as pN,isNonNullable as zs,isNullable as D$,videoHeightToQuality as Ks}from"@vkontakte/videoplayer-shared/es2018";function sl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function nl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&sl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Hi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return D$(a)||zs(a.min)&&zs(a.max)&&Ug(a.max,a.min)||zs(a.min)&&e&&M$(a.min,e)||zs(a.max)&&t&&Ug(a.max,t)}function Hg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Hi({limits:{max:a!=null&&a.max?Ks(a.max):void 0,min:a!=null&&a.min?Ks(a.min):void 0},highestAvailableQuality:e?Ks(e):void 0,lowestAvailableQuality:t?Ks(t):void 0})}var B$=new fe("best_bitrate"),Xg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ll=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),ji=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=zg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Jg='Assertion "ABR Tracks is empty array" failed',Js=(a,e,t,r)=>{var u;let i=[...e].sort(ll(1)),s=[...t].sort(ll(1)),n=s.filter(l=>De(l.bitrate)&&De(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Bt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Bt.default)(s,-1);return o&&(0,Yg.default)(n,o)?o:n.length?(0,Bt.default)(n,-1):(0,Bt.default)(s,0)},Wg=a=>"quality"in a,Zg=(a,e,t,r)=>{var n;let i=De((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&De(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&zg()-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=Wg(o)?"video":"audio",l=Wg(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return r==null||r.recordSwitch(t),t},$R=(a,e)=>Math.log(e)/Math.log(a),MR=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&window.devicePixelRatio){let i=window.devicePixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(i-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=$R(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return nl({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Ot=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f})=>{var F,A,k,Q,ee,w;Ug(a,jg);let{containerSizeFactor:b,containerSizeLimit:g}=MR({container:e,tuning:r,limits:i}),v=r.considerPlaybackRate&&De(o)?o:1,S=a.filter(T=>!_g(T.quality)).sort((T,R)=>Og(T.quality,R.quality)?-1:1),y=(F=(0,Bt.default)(S,-1))==null?void 0:F.quality,x=(A=(0,Bt.default)(S,0))==null?void 0:A.quality,I=ji({limits:i,lowestAvailableQuality:y,highestAvailableQuality:x}),M=v*Hg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),L={},V=S.filter(T=>{let R=!0;if(g)if(T.size)R=T.size.width<=g.width&&T.size.height<=g.height;else{let he=g&&kR(g);R=he?ul(T.quality,he):!0}if(!R)return L[T.quality]="FitsContainer",!1;let q=h||t,B=De(q)&&isFinite(q)&&De(T.bitrate)?q-s>=T.bitrate*M:!0,ke=nl({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:i})&&(i==null?void 0:i.min)===T.quality;if(!B&&!ke)return L[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&De(r.minBufferToSwitchUp)&&u&&!_g(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Og(T.quality,u.quality))return L[T.quality]="Buffer",!1;if(!!d&&ol(T.quality,d)&&!ke)return L[T.quality]="DroppedFramesLimit",!1;if(!!p&&ol(T.quality,p)&&!ke)return L[T.quality]="StallsLimit",!1;let ne=I||(Bg(i==null?void 0:i.max)||ul(T.quality,i.max))&&(Bg(i==null?void 0:i.min)||ol(T.quality,i.min)),pe=De(c)&&!c?ul(T.quality,r.backgroundVideoQualityLimit):!0;return!ne||!pe?(L[T.quality]="FitsQualityLimits",!1):!0})[0];V&&V.bitrate&&RR.next(V.bitrate);let _=(k=V!=null?V:(0,Bt.default)(S,-1))!=null?k:a[0];return _.quality!==((Q=l==null?void 0:l.last)==null?void 0:Q.quality)&&f({message:`
9
+ `}),o}return r==null||r.recordSwitch(t),t},O$=(a,e)=>Math.log(e)/Math.log(a),_$=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&window.devicePixelRatio){let i=window.devicePixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(i-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=O$(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return nl({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Ot=(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 F,A,k,Q,ee,w;Kg(a,Jg);let{containerSizeFactor:b,containerSizeLimit:g}=_$({container:e,tuning:r,limits:i}),v=r.considerPlaybackRate&&De(o)?o:1,y=a.filter(T=>!Gg(T.quality)).sort((T,$)=>Qg(T.quality,$.quality)?-1:1),S=(F=(0,Bt.default)(y,-1))==null?void 0:F.quality,E=(A=(0,Bt.default)(y,0))==null?void 0:A.quality,I=Hi({limits:i,lowestAvailableQuality:S,highestAvailableQuality:E}),D=v*Xg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),L={},V=y.filter(T=>{let $=!0;if(g)if(T.size)$=T.size.width<=g.width&&T.size.height<=g.height;else{let he=g&&C$(g);$=he?ul(T.quality,he):!0}if(!$)return L[T.quality]="FitsContainer",!1;let q=h||t,B=De(q)&&isFinite(q)&&De(T.bitrate)?q-s>=T.bitrate*D:!0,Ae=nl({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:i})&&(i==null?void 0:i.min)===T.quality;if(!B&&!Ae)return L[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&De(r.minBufferToSwitchUp)&&u&&!Gg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Qg(T.quality,u.quality))return L[T.quality]="Buffer",!1;if(!!d&&ol(T.quality,d)&&!Ae)return L[T.quality]="DroppedFramesLimit",!1;if(!!p&&ol(T.quality,p)&&!Ae)return L[T.quality]="StallsLimit",!1;let ne=I||(jg(i==null?void 0:i.max)||ul(T.quality,i.max))&&(jg(i==null?void 0:i.min)||ol(T.quality,i.min)),pe=De(c)&&!c?ul(T.quality,r.backgroundVideoQualityLimit):!0;return!ne||!pe?(L[T.quality]="FitsQualityLimits",!1):!0})[0];V&&V.bitrate&&B$.next(V.bitrate);let _=(k=V!=null?V:(0,Bt.default)(y,-1))!=null?k:a[0];return _.quality!==((Q=l==null?void 0:l.last)==null?void 0:Q.quality)&&m({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(T=>{var R,q;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${(R=T.size)==null?void 0:R.width}:${(q=T.size)==null?void 0:q.height} }`}).join(`
12
+ ${a.map(T=>{var $,q;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${($=T.size)==null?void 0:$.width}:${(q=T.size)==null?void 0:q.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,Zs.default)(r!=null?r:{}).map(([T,R])=>`${T}: ${R}`).join(`
16
+ ${(0,Xs.default)(r!=null?r:{}).map(([T,$])=>`${T}: ${$}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
@@ -25,7 +25,7 @@ var JT=Object.create;var td=Object.defineProperty;var ZT=Object.getOwnPropertyDe
25
25
  playbackRate: ${o},
26
26
  playbackRateFactor: ${v},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${M},
28
+ bitrateFactor: ${D},
29
29
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
30
30
  droppedVideoMaxQualityLimit: ${d},
31
31
  stallsVideoMaxQualityLimit: ${p},
@@ -34,19 +34,19 @@ var JT=Object.create;var td=Object.defineProperty;var ZT=Object.getOwnPropertyDe
34
34
  minQualityLimit: ${i==null?void 0:i.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,Zs.default)(L).map(([T,R])=>`${T}: ${R}`).join(`
37
+ ${(0,Xs.default)(L).map(([T,$])=>`${T}: ${$}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
40
  [best video track] ${V==null?void 0:V.quality}
41
41
  [selected video track] ${_==null?void 0:_.quality}
42
- `}),Qg(r,f,_,l)},Gg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;Ug(t,jg);let c=i.considerPlaybackRate&&De(s)?s:1,d=[...t].sort(ll(-1)),p=a.bitrate;LR(p);let h=c*Hg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,b=en(a,e,t,i.minVideoAudioRatio),g=l||r;return De(g)&&isFinite(g)&&(f=d.find(S=>De(S.bitrate)&&De(b==null?void 0:b.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),f||(f=b),(f==null?void 0:f.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
42
+ `}),Zg(r,m,_,l)},ev=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;Kg(t,Jg);let c=i.considerPlaybackRate&&De(s)?s:1,d=[...t].sort(ll(-1)),p=a.bitrate;V$(p);let h=c*Xg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,b=Js(a,e,t,i.minVideoAudioRatio),g=l||r;return De(g)&&isFinite(g)&&(m=d.find(y=>De(y.bitrate)&&De(b==null?void 0:b.bitrate)?g-p>=y.bitrate*h&&y.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(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
45
+ ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,Zs.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
49
+ ${(0,Xs.default)(i!=null?i:{}).map(([y,S])=>`${y}: ${S}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
@@ -59,15 +59,15 @@ var JT=Object.create;var td=Object.defineProperty;var ZT=Object.getOwnPropertyDe
59
59
  bitrateFactor: ${h},
60
60
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
61
61
 
62
- [selected audio track] ${f==null?void 0:f.id}
63
- `}),f&&Qg(i,u,f,o)};var ie=a=>new URL(a).hostname;import{assertNever as iv,assertNonNullable as av,combine as ZR,debounce as e$,ErrorCategory as sv,filter as nv,filterChanged as t$,isNonNullable as fl,map as nn,merge as ov,observableFrom as r$,once as i$,Subscription as a$,ValueSubject as ml,videoQualityToHeight as uv,videoSizeToQuality as s$}from"@vkontakte/videoplayer-shared/es2018";var Zg=D(Vt(),1);var Yg=D(We(),1),Wg=a=>{if(a instanceof DOMException&&(0,Yg.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},xe=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!Wg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return Wg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as rn,isNullable as VR,assertNonNullable as Yi}from"@vkontakte/videoplayer-shared/es2018";var Kg=D(zr(),1);import{isNonNullable as zg,assertNonNullable as tn,now as DR}from"@vkontakte/videoplayer-shared/es2018";function ae(){return DR()}function cl(a){return ae()-a}function dl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Xg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Xr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;tn(c);let A=cl(c),k;if(A<b){k=b-A,setTimeout(g,k);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,M()},v=A=>(s=A,F),S=A=>(d=A,F),y=()=>(h="json",F),x=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=A=>(p=A,F),M=()=>{c=ae(),n=new i,n.open("get",a);let A=0,k,Q=0,ee=()=>(tn(c),Math.max(c,Math.max(k||0,Q||0)));if(s&&n.addEventListener("progress",w=>{let T=ae();s.updateChunk&&w.loaded>A&&(s.updateChunk(ee(),w.loaded-A),A=w.loaded,k=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(u)return;tn(n);let w=n.status;if(w>=200&&w<300){let{response:T,responseType:R}=n,q=T==null?void 0:T.byteLength;if(typeof q=="number"&&s){let B=q-A;B&&s.updateChunk&&s.updateChunk(ee(),B)}R==="json"&&(!T||!(0,Kg.default)(T).length)?x():(d&&d(),e(T))}else x()}),n.addEventListener("error",()=>{x()}),p){let w=()=>{tn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=ae(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=h,n.send(),F},F={withBitrateReporting:v,withParallel:I,withJSONResponse:y,withRetryCount:A=>(l=A,F),withRetryInterval:(A,k)=>(zg(A)&&(b=A),zg(k)&&(f=k),F),withTimeout:A=>(o=A,F),withFinally:S,send:M,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return F}var Gi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Jg=D(zr(),1);var Wi=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=ae(),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=ae()-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=Xr(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=ae()}_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=ae();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Jg.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as BR}from"@vkontakte/videoplayer-shared/es2018";var an=1e4,pl=3;var OR=6e4,_R=10,NR=1,FR=500,zi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new BR,this.chunkRateEstimator=new Gi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=dl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=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=dl(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];let{max:u,min:l}=this.autoQualityLimits||{};!Vg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Zg.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s))}return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||rn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Xg(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Wi(pl,an,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let x=s&&(!c||c===this.rep);return x||t("Not running!"),x},p=(x,I,M)=>{u&&u.abort(),u=Xr(this.urlResolver.resolve(x,!1),I,M,()=>this._retryCallback()).withTimeout(an).withBitrateReporting(this.bitrateSwitcher).withRetryCount(pl).withFinally(()=>{u=null}).send()},h=(x,I,M)=>{Yi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),I,M,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=x=>{let I=r.playbackRate;r.playbackRate!==x&&(t(`Playback rate switch: ${I}=>${x}`),r.playbackRate=x)},b=x=>{this.lowLatency=x,t(`lowLatency changed to ${x}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let x=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let M=ae()-1e4,L=0;for(let V=0;V<this.bufferStates.length;V++){let _=this.bufferStates[V];x=Math.min(x,_.buf),_.ts<M&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${x} drop=${L} jitter=${this.sourceJitter}`);let j=x-NR;this.sourceJitter>=0?j-=this.sourceJitter/2:this.sourceJitter-=1,j>3?f(1.15):j>1?f(1.1):j>.3?f(1.05):f(1)}},v=x=>{let I,M=()=>I&&I.start?I.start.length:0,L=w=>I.start[w]/1e3,j=w=>I.dur[w]/1e3,V=w=>I.fragIndex+w,_=(w,T)=>({chunkIdx:V(w),startTS:L(w),dur:j(w),discontinuity:T}),F=()=>{let w=0;if(I&&I.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,R=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,q=T;this.sourceJitter>1&&(q+=this.sourceJitter-1);let B=I.dur.length-1;for(;B>=0&&(q-=I.dur[B],!(q<=0));--B);w=Math.min(B,I.dur.length-1-R),w=Math.max(w,0)}return _(w,!0)},A=w=>{let T=M();if(!(T<=0)){if(rn(w)){for(let R=0;R<T;R++)if(L(R)>w)return _(R)}return F()}},k=w=>{let T=M(),R=w?w.chunkIdx+1:0,q=R-I.fragIndex;if(!(T<=0)){if(!w||q<0||q-T>_R)return t(`Resync: offset=${q} bChunks=${T} chunk=`+JSON.stringify(w)),F();if(!(q>=T))return _(R-I.fragIndex,!1)}},Q=(w,T,R)=>{l&&l.abort(),l=Xr(this.urlResolver.resolve(w,!0,this.lowLatency),T,R,()=>this._retryCallback()).withTimeout(an).withRetryCount(pl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,T)=>{Q(x,R=>{if(!d())return;I=R;let q=!!I.lowLatency;q!==this.lowLatency&&b(q);let B=0;for(let ke=0;ke<I.dur.length;++ke)B+=I.dur[ke];B>0&&(Yi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,w(A(T))},()=>this._handleNetworkError())},nextChunk:k}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Yi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:x=>{let{videoElement:I,logger:M}=this.params,L=v(e.jidxUrl),j,V,_,F,A=0,k,Q,ee,w=()=>{k&&(clearTimeout(k),k=void 0);let U=Math.max(FR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=A+U,pe=ae(),he=Math.min(1e4,ne-pe);A=pe;let St=()=>{l||d()&&L.seek(()=>{d()&&(A=ae(),T(),w())})};he>0?k=window.setTimeout(()=>{this.paused?w():St()},he):St()},T=()=>{let U;for(;U=L.nextChunk(F);)F=U,li(U);let ne=L.nextChunk(_);if(ne){if(_&&ne.discontinuity){M("Detected discontinuity; restarting playback"),this.paused?w():(S(),this._initPlayerWith(e));return}ke(ne)}else w()},R=(U,ne)=>{if(!d()||!this.sourceBuffer)return;let pe,he,St,Tr=yt=>{window.setTimeout(()=>{d()&&R(U,ne)},yt)};if(this.sourceBuffer.updating)M("Source buffer is updating; delaying appendBuffer"),Tr(100);else{let yt=ae(),Qt=I.currentTime;!this.paused&&I.buffered.length>1&&Q===Qt&&yt-ee>500&&(M("Stall suspected; trying to fix"),this._fixupStall()),Q!==Qt&&(Q=Qt,ee=yt);let Ir=this._getBufferSizeSec();if(Ir>30)M(`Buffered ${Ir} seconds; delaying appendBuffer`),Tr(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:Ir}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(ci){if(ci.name==="QuotaExceededError")M("QuotaExceededError; delaying appendBuffer"),St=this.sourceBuffer.buffered.length,St!==0&&(pe=this.sourceBuffer.buffered.start(0),he=Qt,he-pe>4&&this.sourceBuffer.remove(pe,he-3)),Tr(1e3);else throw ci}}},q=()=>{V&&j&&(M([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(_)]),R(V,function(){V=null,T()}))},B=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),ke=U=>{d()&&h(B(U),(ne,pe)=>{if(d()){if(pe/=1e3,V=ne,_=U,n=U.startTS,pe){let he=Math.min(10,U.dur/pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*he:he}q()}},()=>this._handleNetworkError())},li=U=>{d()&&(Yi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(U),!1)))},yr=U=>{d()&&(e.cachedHeader=U,R(U,()=>{j=!0,q()}))};s=!0,L.seek(U=>{if(d()){if(A=ae(),!U){w();return}F=U,!VR(x)||U.startTS>x?ke(U):(_=U,T())}},x),e.cachedHeader?yr(e.cachedHeader):p(e.headerUrl,yr,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),rn(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Yi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return rn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ae();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&&cl(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=ae();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Xr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(an).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;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)=>{var c,d;u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(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))},OR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var rv=D(_r(),1);import{debounce as qR,filter as ev,fromEvent as UR,interval as HR,isHigher as jR,isInvariantQuality as QR,isLower as GR,merge as WR,Subject as tv,Subscription as YR}from"@vkontakte/videoplayer-shared/es2018";var hl=class{constructor(){this.onDroopedVideoFramesLimit$=new tv;this.subscription=new YR;this.playing=!1;this.tracks=[];this.forceChecker$=new tv;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!QR(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&&jR(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(UR(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=HR(this.droppedFramesChecker.checkTime).pipe(ev(()=>this.playing),ev(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(qR(this.droppedFramesChecker.checkTime)),r=WR(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,rv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>GR(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},sn=hl;import{map as zR,Observable as KR}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as XR}from"@vkontakte/videoplayer-shared/es2018";var Ki=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var JR=(a,e)=>new KR(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ki()))},{...r,...e});i.observe(a);let s=XR(document,"visibilitychange").pipe(zR(n=>!document.hidden||Ki())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ne=JR;var n$=["paused","playing","ready"],o$=["paused","playing","ready"],Xi=class{constructor(e){this.subscription=new a$;this.videoState=new $("stopped");this.representations$=new ml([]);this.droppedFramesManager=new sn;this.maxSeekBackTime$=new ml(1/0);this.zeroTime$=new ml(void 0);this.liveOffset=new dt;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:sv.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=Ct(u.name))!=null?r:s$(u.video),d=u.bitrate/1e3,p={...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),fl(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,bl.default)(o$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,bl.default)(n$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(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(le(this.params.source.url,u))}return;default:return iv(e)}};this.textTracksManager=new Oe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:sv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};ov(this.videoState.stateChangeStarted$.pipe(nn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=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(ie(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(nn(i=>i.map(({track:s})=>s)),nv(i=>!!i.length),i$()).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(t$(),nn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(ZR({zeroTime:this.zeroTime$.pipe(nv(fl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(tt(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(Be(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ne(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&uv(i),min:s&&uv(s)}),this.params.output.autoVideoTrackLimits$.next({max:i,min:s})})).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 iv(i.to)}},t)).add(ov(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r$(["init"])).pipe(e$(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 zi({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&&fl(t)?t:Ot(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;av(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;av(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(le(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var lv=Xi;var Yy=D(We(),1);var it=(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 zD,assertNonNullable as KD,debounce as XD,ErrorCategory as jy,filter as Qy,filterChanged as Fa,fromEvent as JD,isNonNullable as Gy,map as ic,merge as Cn,observableFrom as ac,once as Wy,Subscription as ZD}from"@vkontakte/videoplayer-shared/es2018";var on=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Jr=class extends on{constructor(){super(),this.listeners||on.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Ji=class{constructor(){Object.defineProperty(this,"signal",{value:new Jr,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&&(Ji.prototype[Symbol.toStringTag]="AbortController",Jr.prototype[Symbol.toStringTag]="AbortSignal");function un(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function gl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!un({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Zi=un({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),cv=Zi?gl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,at=Zi?cv.fetch:window.fetch,VF=Zi?cv.Request:window.Request,ce=Zi?Ji:window.AbortController,BF=Zi?Jr:window.AbortSignal;var Zl=D(Sl(),1);var gn=D(Vt(),1);var ht=()=>window.ManagedMediaSource||window.MediaSource,ln=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Rv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},$v=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Sn,clientChecker as vn}from"@vkontakte/videoplayer-shared/es2018";var Fe=document.createElement("video"),M$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',D$='video/mp4; codecs="hev1.1.6.L93.B0"',Uv='video/webm; codecs="vp09.00.10.08"',Hv='video/webm; codecs="av01.0.00M.08"',C$='audio/mp4; codecs="mp4a.40.2"',V$='audio/webm; codecs="opus"',Mv,Dv,ea={mms:ln(),mse:Rv(),hls:!!((Mv=Fe.canPlayType)!=null&&Mv.call(Fe,"application/x-mpegurl")||(Dv=Fe.canPlayType)!=null&&Dv.call(Fe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Cv,Vv,Pe={mp4:!!((Cv=Fe.canPlayType)!=null&&Cv.call(Fe,"video/mp4")),webm:!!((Vv=Fe.canPlayType)!=null&&Vv.call(Fe,"video/webm")),cmaf:!0},dn,Bv,pn,Ov,hn,_v,fn,Nv,mn,Fv,bn,qv,we={h264:!!((Bv=(dn=ht())==null?void 0:dn.isTypeSupported)!=null&&Bv.call(dn,M$)),h265:!!((Ov=(pn=ht())==null?void 0:pn.isTypeSupported)!=null&&Ov.call(pn,D$)),vp9:!!((_v=(hn=ht())==null?void 0:hn.isTypeSupported)!=null&&_v.call(hn,Uv)),av1:!!((Nv=(fn=ht())==null?void 0:fn.isTypeSupported)!=null&&Nv.call(fn,Hv)),aac:!!((Fv=(mn=ht())==null?void 0:mn.isTypeSupported)!=null&&Fv.call(mn,C$)),opus:!!((qv=(bn=ht())==null?void 0:bn.isTypeSupported)!=null&&qv.call(bn,V$))},Zr=(we.h264||we.h265)&&we.aac,lr,B$=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Hv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Uv}})]);lr={DASH_WEBM_AV1:e,DASH_WEBM:t}};B$().catch(a=>{console.error(a)});var ei=ea.hls&&Pe.mp4,jv=()=>Object.keys(we).filter(a=>we[a]),Qv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ea.mse&&(!r||!!window.MediaStreamTrack)||ea.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Pe.mp4&&Zr;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&&Zr||Pe.webm&&(we.vp9||we.av1)&&(we.opus||we.aac));case"DASH_LIVE":return i&&Pe.mp4&&Zr;case"DASH_LIVE_CMAF":return i&&Pe.mp4&&Zr&&Pe.cmaf;case"DASH_ONDEMAND":return i&&Pe.mp4&&Zr;case"HLS":case"HLS_ONDEMAND":return ei||e&&i&&Pe.mp4&&Zr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ei;case"MPEG":return Pe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ea.webrtc&&ea.ws&&we.h264&&(Pe.mp4||Pe.webm);default:return Sn(s)}})},cn=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return lr?lr[t].smooth?[t,e]:lr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return lr?lr[t].powerEfficient?[t,e]:lr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Sn(a)}return[e,t]},Gv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...cn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(vn.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...cn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...cn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...cn(a),...i,"HLS","HLS_ONDEMAND"];default:Sn(e)}return ei?[...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=vn.isMac&&vn.isSafari;if(vn.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Sn(a)}else ei&&!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"]},yl=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,gn.default)(t.value.split("."),0)}for(let t of a){let r=(0,gn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,gn.default)(e.value.split("."),0)};var mS=D(fS(),1);import{ErrorCategory as ra}from"@vkontakte/videoplayer-shared/es2018";var bS=a=>{if(!a)return{id:"EmptyResponse",category:ra.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ra.NETWORK,message:`UV Error ${a}`};let e=(0,mS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ra.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ra.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ra.PARSER,message:"Response is valid XML, but parser failed"}};var _t=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as Kl,assertNonNullable as mr,clientChecker as LD,combine as br,ErrorCategory as st,filter as Oa,filterChanged as Xl,flattenObject as _a,fromEvent as gr,getTraceSubscriptionMethod as RD,interval as Jl,isNonNullable as By,isNullable as Oy,map as ni,merge as vr,now as $D,Subject as kn,Subscription as _y,tap as MD,throttle as DD,ValueSubject as Z}from"@vkontakte/videoplayer-shared/es2018";var Tn=D(We(),1),ai=D(Vt(),1),In=D(Sl(),1);var Z$=(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)},eM=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),Pl=vS?Z$:window.requestIdleCallback,ia=vS?eM:window.cancelIdleCallback;var Ay=D(Ws(),1);import{assertNever as tM,ErrorCategory as SS,clientChecker as wl,Subject as yS}from"@vkontakte/videoplayer-shared/es2018";var rM=18,TS=!1;try{TS=wl.isSafari&&!!wl.macVersion&&wl.macVersion<=rM}catch(a){console.error(a)}var Al=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)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){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()})}async abort(e){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:tM(t)}}},IS=Al;var kl=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 Ft,assertNonNullable as Ae,clientChecker as vD,ErrorCategory as bt,fromEvent as Ql,getExponentialDelay as Gl,isNonNullable as ii,isNullable as de,now as yn,once as SD,Subject as yD,Subscription as TD,ValueSubject as pr}from"@vkontakte/videoplayer-shared/es2018";var O=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)}get id(){return this.type}get size(){return this.size32}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 ti=class extends O{};var aa=class extends O{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 sa=class extends O{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 na=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var z=class extends O{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var oa=class extends z{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ua=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var la=class extends O{constructor(e,t){super(e,t),this.data=this.content}};var cr=class extends z{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ca=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends z{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ha=class extends z{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var fa=class extends z{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ma=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends z{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ga=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends z{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ya=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends z{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ia=class extends z{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ea=class extends z{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var xa=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends z{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var wa=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var aM={ftyp:sa,moov:na,mvhd:oa,moof:ua,mdat:la,sidx:cr,trak:ca,mdia:ma,mfhd:Sa,tkhd:ba,traf:ya,tfhd:Ta,tfdt:Ia,trun:Ea,minf:ga,sv3d:da,st3d:pa,prhd:ha,proj:va,equi:fa,uuid:aa,stbl:xa,stsd:Pa,avc1:wa,unknown:ti},ft=class a{constructor(e={}){this.options={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=aM[e];return r?new r(t,new a):new ti(t,new a)}};var Nt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var nM=new TextDecoder("ascii"),oM=a=>nM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",uM=a=>{let e=new cr(a,new ft),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})},lM=(a,e)=>{let r=new ft().parse(a),i=new Nt(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},cM=a=>{let t=new ft().parse(a),r=new Nt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},dM=a=>{var i;let t=new ft().parse(a);return(i=new Nt(t).find("sidx"))==null?void 0:i.timescale},pM=(a,e)=>{let r=new ft().parse(a),s=new Nt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},hM=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 ft().parse(a),i=new Nt(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},ES={validateData:oM,parseInit:hM,getIndexRange:()=>{},parseSegments:uM,parseFeedableSegmentChunk:lM,getChunkEndTime:pM,getServerLatencyTimestamps:cM,getTimescaleFromIndex:dM};var ka=D(We(),1);import{assertNonNullable as Rl,isNonNullable as AS,isNullable as mM}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as fM}from"@vkontakte/videoplayer-shared/es2018";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=Aa(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=Aa(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Aa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*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 Aa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:fM(e)}},dr=(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"&&dr(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 dr(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 kS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],bM=[231,22612,22743,167,171,163,160,175],gM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return dr(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=ze(f,h);l=Aa(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=ze(f,h):p===17545?i=ze(f,h):p===21420&&l===475249515?u=ze(f,h):p===374648427?dr(f,({tag:g,type:v,value:S})=>g===30321?(c=ze(S,v)===1,!1):!0):s&&n&&(0,ka.default)(kS,p)&&(o=!0),!o}),Rl(e,"Failed to parse webm Segment start"),Rl(t,"Failed to parse webm Segment end"),Rl(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},vM=a=>{if(mM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},SM=(a,e)=>{let t=!1,r=!1,i=o=>AS(o.time)&&AS(o.position),s=[],n;return dr(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,ka.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}}})},yM=a=>{let e=0,t=!1;try{dr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ka.default)(bM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ka.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},LS={validateData:wS,parseInit:gM,getIndexRange:vM,parseSegments:SM,parseFeedableSegmentChunk:yM};var La=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return LS;case"mp4":return ES}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Ul=D(zS(),1),Ty=D(_r(),1),Iy=D(dy(),1),Ey=D(Vt(),1),Hl=D(zr(),1);var py=D(We(),1),Bl=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 gD,isNullable as Sy}from"@vkontakte/videoplayer-shared/es2018";var hy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var fy=a=>{var e;try{let t=mD(),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 mD(){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&&Zg(i,u,m,o)};var ie=a=>new URL(a).hostname;import{assertNever as dv,assertNonNullable as pv,combine as sR,debounce as nR,ErrorCategory as hv,filter as mv,filterChanged as oR,isNonNullable as ml,map as an,merge as fv,observableFrom as uR,once as lR,Subscription as cR,ValueSubject as fl,videoQualityToHeight as bv,videoSizeToQuality as dR}from"@vkontakte/videoplayer-shared/es2018";var ov=C(Vt(),1);var rv=C(We(),1),tv=a=>{if(a instanceof DOMException&&(0,rv.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Ee=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!tv(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return tv(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as en,isNullable as q$,assertNonNullable as Wi}from"@vkontakte/videoplayer-shared/es2018";var av=C(Wr(),1);import{isNonNullable as iv,assertNonNullable as Zs,now as N$}from"@vkontakte/videoplayer-shared/es2018";function ae(){return N$()}function cl(a){return ae()-a}function dl(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 sv(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function zr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;Zs(c);let A=cl(c),k;if(A<b){k=b-A,setTimeout(g,k);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,D()},v=A=>(s=A,F),y=A=>(d=A,F),S=()=>(h="json",F),E=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=A=>(p=A,F),D=()=>{c=ae(),n=new i,n.open("get",a);let A=0,k,Q=0,ee=()=>(Zs(c),Math.max(c,Math.max(k||0,Q||0)));if(s&&n.addEventListener("progress",w=>{let T=ae();s.updateChunk&&w.loaded>A&&(s.updateChunk(ee(),w.loaded-A),A=w.loaded,k=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;Zs(n);let w=n.status;if(w>=200&&w<300){let{response:T,responseType:$}=n,q=T==null?void 0:T.byteLength;if(typeof q=="number"&&s){let B=q-A;B&&s.updateChunk&&s.updateChunk(ee(),B)}$==="json"&&(!T||!(0,av.default)(T).length)?E():(d&&d(),e(T))}else E()}),n.addEventListener("error",()=>{E()}),p){let w=()=>{Zs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=ae(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=h,n.send(),F},F={withBitrateReporting:v,withParallel:I,withJSONResponse:S,withRetryCount:A=>(l=A,F),withRetryInterval:(A,k)=>(iv(A)&&(b=A),iv(k)&&(m=k),F),withTimeout:A=>(o=A,F),withFinally:y,send:D,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return F}var Qi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var nv=C(Wr(),1);var Gi=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=ae(),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=ae()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=zr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ae()}_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=ae();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,nv.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 U$}from"@vkontakte/videoplayer-shared/es2018";var tn=1e4,pl=3;var H$=6e4,j$=10,Q$=1,G$=500,Yi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new U$,this.chunkRateEstimator=new Qi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=dl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=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=dl(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];let{max:u,min:l}=this.autoQualityLimits||{};!Hg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,ov.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!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=()=>{sv(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 Gi(pl,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 E=s&&(!c||c===this.rep);return E||t("Not running!"),E},p=(E,I,D)=>{u&&u.abort(),u=zr(this.urlResolver.resolve(E,!1),I,D,()=>this._retryCallback()).withTimeout(tn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(pl).withFinally(()=>{u=null}).send()},h=(E,I,D)=>{Wi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,D,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let I=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),r.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let D=ae()-1e4,L=0;for(let V=0;V<this.bufferStates.length;V++){let _=this.bufferStates[V];E=Math.min(E,_.buf),_.ts<D&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${E} drop=${L} jitter=${this.sourceJitter}`);let j=E-Q$;this.sourceJitter>=0?j-=this.sourceJitter/2:this.sourceJitter-=1,j>3?m(1.15):j>1?m(1.1):j>.3?m(1.05):m(1)}},v=E=>{let I,D=()=>I&&I.start?I.start.length:0,L=w=>I.start[w]/1e3,j=w=>I.dur[w]/1e3,V=w=>I.fragIndex+w,_=(w,T)=>({chunkIdx:V(w),startTS:L(w),dur:j(w),discontinuity:T}),F=()=>{let w=0;if(I&&I.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,$=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,q=T;this.sourceJitter>1&&(q+=this.sourceJitter-1);let B=I.dur.length-1;for(;B>=0&&(q-=I.dur[B],!(q<=0));--B);w=Math.min(B,I.dur.length-1-$),w=Math.max(w,0)}return _(w,!0)},A=w=>{let T=D();if(!(T<=0)){if(en(w)){for(let $=0;$<T;$++)if(L($)>w)return _($)}return F()}},k=w=>{let T=D(),$=w?w.chunkIdx+1:0,q=$-I.fragIndex;if(!(T<=0)){if(!w||q<0||q-T>j$)return t(`Resync: offset=${q} bChunks=${T} chunk=`+JSON.stringify(w)),F();if(!(q>=T))return _($-I.fragIndex,!1)}},Q=(w,T,$)=>{l&&l.abort(),l=zr(this.urlResolver.resolve(w,!0,this.lowLatency),T,$,()=>this._retryCallback()).withTimeout(tn).withRetryCount(pl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,T)=>{Q(E,$=>{if(!d())return;I=$;let q=!!I.lowLatency;q!==this.lowLatency&&b(q);let B=0;for(let Ae=0;Ae<I.dur.length;++Ae)B+=I.dur[Ae];B>0&&(Wi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,w(A(T))},()=>this._handleNetworkError())},nextChunk:k}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Wi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:I,logger:D}=this.params,L=v(e.jidxUrl),j,V,_,F,A=0,k,Q,ee,w=()=>{k&&(clearTimeout(k),k=void 0);let U=Math.max(G$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=A+U,pe=ae(),he=Math.min(1e4,ne-pe);A=pe;let St=()=>{l||d()&&L.seek(()=>{d()&&(A=ae(),T(),w())})};he>0?k=window.setTimeout(()=>{this.paused?w():St()},he):St()},T=()=>{let U;for(;U=L.nextChunk(F);)F=U,ui(U);let ne=L.nextChunk(_);if(ne){if(_&&ne.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?w():(y(),this._initPlayerWith(e));return}Ae(ne)}else w()},$=(U,ne)=>{if(!d()||!this.sourceBuffer)return;let pe,he,St,Sr=yt=>{window.setTimeout(()=>{d()&&$(U,ne)},yt)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),Sr(100);else{let yt=ae(),Qt=I.currentTime;!this.paused&&I.buffered.length>1&&Q===Qt&&yt-ee>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),Q!==Qt&&(Q=Qt,ee=yt);let yr=this._getBufferSizeSec();if(yr>30)D(`Buffered ${yr} seconds; delaying appendBuffer`),Sr(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:yr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(li){if(li.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),St=this.sourceBuffer.buffered.length,St!==0&&(pe=this.sourceBuffer.buffered.start(0),he=Qt,he-pe>4&&this.sourceBuffer.remove(pe,he-3)),Sr(1e3);else throw li}}},q=()=>{V&&j&&(D([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(_)]),$(V,function(){V=null,T()}))},B=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),Ae=U=>{d()&&h(B(U),(ne,pe)=>{if(d()){if(pe/=1e3,V=ne,_=U,n=U.startTS,pe){let he=Math.min(10,U.dur/pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*he:he}q()}},()=>this._handleNetworkError())},ui=U=>{d()&&(Wi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(U),!1)))},vr=U=>{d()&&(e.cachedHeader=U,$(U,()=>{j=!0,q()}))};s=!0,L.seek(U=>{if(d()){if(A=ae(),!U){w();return}F=U,!q$(E)||U.startTS>E?Ae(U):(_=U,T())}},E),e.cachedHeader?vr(e.cachedHeader):p(e.headerUrl,vr,()=>this._handleNetworkError())},stop:y,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,Wi(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=ae();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&&cl(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=ae();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=zr(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;Ee(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(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))},H$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var cv=C(Br(),1);import{debounce as W$,filter as uv,fromEvent as Y$,interval as z$,isHigher as K$,isInvariantQuality as X$,isLower as J$,merge as Z$,Subject as lv,Subscription as eR}from"@vkontakte/videoplayer-shared/es2018";var hl=class{constructor(){this.onDroopedVideoFramesLimit$=new lv;this.subscription=new eR;this.playing=!1;this.tracks=[];this.forceChecker$=new lv;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&&!X$(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&&K$(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(Y$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=z$(this.droppedFramesChecker.checkTime).pipe(uv(()=>this.playing),uv(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(W$(this.droppedFramesChecker.checkTime)),r=Z$(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,cv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>J$(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=hl;import{map as tR,Observable as rR}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as iR}from"@vkontakte/videoplayer-shared/es2018";var zi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var aR=(a,e)=>new rR(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||zi()))},{...r,...e});i.observe(a);let s=iR(document,"visibilitychange").pipe(tR(n=>!document.hidden||zi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ne=aR;var pR=["paused","playing","ready"],hR=["paused","playing","ready"],Ki=class{constructor(e){this.subscription=new cR;this.videoState=new R("stopped");this.representations$=new fl([]);this.droppedFramesManager=new rn;this.maxSeekBackTime$=new fl(1/0);this.zeroTime$=new fl(void 0);this.liveOffset=new lr;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:hv.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=Ct(u.name))!=null?r:dR(u.video),d=u.bitrate/1e3,p={...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),ml(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,bl.default)(hR,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,bl.default)(pR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(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(le(this.params.source.url,u))}return;default:return dv(e)}};this.textTracksManager=new Oe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:hv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};fv(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=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Ie(this.video);this.subscription.add(this.representations$.pipe(an(i=>i.map(({track:s})=>s)),mv(i=>!!i.length),lR()).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(oR(),an(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(sR({zeroTime:this.zeroTime$.pipe(mv(ml)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(Te(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Be(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ne(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&bv(i),min:s&&bv(s)}),this.params.output.autoVideoTrackLimits$.next({max:i,min:s})})).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 dv(i.to)}},t)).add(fv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,uR(["init"])).pipe(nR(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ye(this.video)}createLiveDashPlayer(){let e=new Yi({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&&ml(t)?t:Ot(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;pv(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;pv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),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(le(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var gv=Ki;var rT=C(We(),1);var it=(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 eC,assertNonNullable as tC,debounce as rC,ErrorCategory as Jy,filter as Zy,filterChanged as _a,fromEvent as iC,isNonNullable as eT,map as ac,merge as Cn,observableFrom as sc,once as tT,Subscription as aC}from"@vkontakte/videoplayer-shared/es2018";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}},Kr=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)}},Xi=class{constructor(){Object.defineProperty(this,"signal",{value:new Kr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Xi.prototype[Symbol.toStringTag]="AbortController",Kr.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 gl(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 Ji=nn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),vv=Ji?gl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,at=Ji?vv.fetch:window.fetch,NF=Ji?vv.Request:window.Request,ce=Ji?Xi:window.AbortController,FF=Ji?Kr:window.AbortSignal;var ec=C(Sl(),1);var fn=C(Vt(),1);var pt=()=>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))},Nv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as gn,clientChecker as bn}from"@vkontakte/videoplayer-shared/es2018";var Fe=document.createElement("video"),_R='video/mp4; codecs="avc1.42000a,mp4a.40.2"',NR='video/mp4; codecs="hev1.1.6.L93.B0"',Kv='video/webm; codecs="vp09.00.10.08"',Xv='video/webm; codecs="av01.0.00M.08"',FR='audio/mp4; codecs="mp4a.40.2"',qR='audio/webm; codecs="opus"',Fv,qv,Zi={mms:on(),mse:_v(),hls:!!((Fv=Fe.canPlayType)!=null&&Fv.call(Fe,"application/x-mpegurl")||(qv=Fe.canPlayType)!=null&&qv.call(Fe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Uv,Hv,xe={mp4:!!((Uv=Fe.canPlayType)!=null&&Uv.call(Fe,"video/mp4")),webm:!!((Hv=Fe.canPlayType)!=null&&Hv.call(Fe,"video/webm")),cmaf:!0},ln,jv,cn,Qv,dn,Gv,pn,Wv,hn,Yv,mn,zv,Pe={h264:!!((jv=(ln=pt())==null?void 0:ln.isTypeSupported)!=null&&jv.call(ln,_R)),h265:!!((Qv=(cn=pt())==null?void 0:cn.isTypeSupported)!=null&&Qv.call(cn,NR)),vp9:!!((Gv=(dn=pt())==null?void 0:dn.isTypeSupported)!=null&&Gv.call(dn,Kv)),av1:!!((Wv=(pn=pt())==null?void 0:pn.isTypeSupported)!=null&&Wv.call(pn,Xv)),aac:!!((Yv=(hn=pt())==null?void 0:hn.isTypeSupported)!=null&&Yv.call(hn,FR)),opus:!!((zv=(mn=pt())==null?void 0:mn.isTypeSupported)!=null&&zv.call(mn,qR))},Xr=(Pe.h264||Pe.h265)&&Pe.aac,cr,UR=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Xv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Kv}})]);cr={DASH_WEBM_AV1:e,DASH_WEBM:t}};UR().catch(a=>{console.error(a)});var Jr=Zi.hls&&xe.mp4,Jv=()=>Object.keys(Pe).filter(a=>Pe[a]),Zv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Zi.mse&&(!r||!!window.MediaStreamTrack)||Zi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&xe.mp4&&Xr;case"DASH_WEBM":return i&&xe.webm&&Pe.vp9&&Pe.opus;case"DASH_WEBM_AV1":return i&&xe.webm&&Pe.av1&&Pe.opus;case"DASH_STREAMS":return i&&(xe.mp4&&Xr||xe.webm&&(Pe.vp9||Pe.av1)&&(Pe.opus||Pe.aac));case"DASH_LIVE":return i&&xe.mp4&&Xr;case"DASH_LIVE_CMAF":return i&&xe.mp4&&Xr&&xe.cmaf;case"DASH_ONDEMAND":return i&&xe.mp4&&Xr;case"HLS":case"HLS_ONDEMAND":return Jr||e&&i&&xe.mp4&&Xr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Jr;case"MPEG":return xe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Zi.webrtc&&Zi.ws&&Pe.h264&&(xe.mp4||xe.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 cr?cr[t].smooth?[t,e]:cr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return cr?cr[t].powerEfficient?[t,e]:cr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:gn(a)}return[e,t]},eS=({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 Jr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},tS=({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 Jr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},yl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],rS=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 ES=C(IS(),1);import{ErrorCategory as ta}from"@vkontakte/videoplayer-shared/es2018";var xS=a=>{if(!a)return{id:"EmptyResponse",category:ta.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ta.NETWORK,message:`UV Error ${a}`};let e=(0,ES.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ta.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:ta.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ta.PARSER,message:"Response is valid XML, but parser failed"}};var _t=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as Xl,assertNonNullable as ai,clientChecker as BD,combine as si,ErrorCategory as st,filter as wn,filterChanged as An,flattenObject as Ba,fromEvent as bt,getTraceSubscriptionMethod as OD,interval as Jl,isNonNullable as jy,isNullable as Qy,map as Oa,merge as br,now as Zl,Subject as kn,Subscription as Gy,tap as _D,throttle as ND,ValueSubject as K}from"@vkontakte/videoplayer-shared/es2018";var Sn=C(We(),1),ri=C(Vt(),1),yn=C(Sl(),1);var sM=(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)},nM=a=>window.clearTimeout(a),PS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),wS=!PS(window.requestIdleCallback)||!PS(window.cancelIdleCallback),Pl=wS?sM:window.requestIdleCallback,ra=wS?nM:window.cancelIdleCallback;var Vy=C(Qs(),1);import{assertNever as oM,ErrorCategory as AS,clientChecker as wl,Subject as kS}from"@vkontakte/videoplayer-shared/es2018";var uM=18,LS=!1;try{LS=wl.isSafari&&!!wl.macVersion&&wl.macVersion<=uM}catch(a){console.error(a)}var Al=class{constructor(e){this.bufferFull$=new kS;this.error$=new kS;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:AS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){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()})}async abort(e){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};LS&&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:AS.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:oM(t)}}},$S=Al;var kl=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 Ft,assertNonNullable as we,clientChecker as xD,ErrorCategory as ft,fromEvent as Ql,getExponentialDelay as Gl,isNonNullable as ti,isNullable as de,now as vn,once as PD,Subject as wD,Subscription as AD,ValueSubject as hr}from"@vkontakte/videoplayer-shared/es2018";var O=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)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Zr=class extends O{};var ia=class extends O{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 aa=class extends O{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 sa=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var z=class extends O{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var na=class extends z{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var oa=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=class extends O{constructor(e,t){super(e,t),this.data=this.content}};var dr=class extends z{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var la=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ca=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends z{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var pa=class extends z{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ha=class extends z{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ma=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends z{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ba=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends z{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Sa=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends z{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ta=class extends z{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ia=class extends z{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Ea=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xa=class extends z{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Pa=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var cM={ftyp:aa,moov:sa,mvhd:na,moof:oa,mdat:ua,sidx:dr,trak:la,mdia:ma,mfhd:va,tkhd:fa,traf:Sa,tfhd:ya,tfdt:Ta,trun:Ia,minf:ba,sv3d:ca,st3d:da,prhd:pa,proj:ga,equi:ha,uuid:ia,stbl:Ea,stsd:xa,avc1:Pa,unknown:Zr},ht=class a{constructor(e={}){this.options={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=cM[e];return r?new r(t,new a):new Zr(t,new a)}};var Nt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var pM=new TextDecoder("ascii"),hM=a=>pM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",mM=a=>{let e=new dr(a,new ht),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})},fM=(a,e)=>{let r=new ht().parse(a),i=new Nt(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},bM=a=>{let t=new ht().parse(a),r=new Nt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},gM=a=>{var i;let t=new ht().parse(a);return(i=new Nt(t).find("sidx"))==null?void 0:i.timescale},vM=(a,e)=>{let r=new ht().parse(a),s=new Nt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},SM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new ht().parse(a),i=new Nt(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},RS={validateData:hM,parseInit:SM,getIndexRange:()=>{},parseSegments:mM,parseFeedableSegmentChunk:fM,getChunkEndTime:vM,getServerLatencyTimestamps:bM,getTimescaleFromIndex:gM};var Aa=C(We(),1);import{assertNonNullable as $l,isNonNullable as VS,isNullable as TM}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as yM}from"@vkontakte/videoplayer-shared/es2018";var MS={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"}},DS=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 MS,s=i?MS[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*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)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*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:yM(e)}},pr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=DS(r);if(!e(i))return;i.type==="master"&&pr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},CS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=DS(a);return pr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=ze(o,n):s===17026?t=ze(o,n):s===17029&&(r=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var BS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],IM=[231,22612,22743,167,171,163,160,175],EM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return pr(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=ze(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=ze(m,h):p===17545?i=ze(m,h):p===21420&&l===475249515?u=ze(m,h):p===374648427?pr(m,({tag:g,type:v,value:y})=>g===30321?(c=ze(y,v)===1,!1):!0):s&&n&&(0,Aa.default)(BS,p)&&(o=!0),!o}),$l(e,"Failed to parse webm Segment start"),$l(t,"Failed to parse webm Segment end"),$l(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}}}},xM=a=>{if(TM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},PM=(a,e)=>{let t=!1,r=!1,i=o=>VS(o.time)&&VS(o.position),s=[],n;return pr(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)(BS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},wM=a=>{let e=0,t=!1;try{pr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Aa.default)(IM,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},OS={validateData:CS,parseInit:EM,getIndexRange:xM,parseSegments:PM,parseFeedableSegmentChunk:wM};var ka=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return OS;case"mp4":return RS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Ul=C(iy(),1),Ly=C(Br(),1),$y=C(Sy(),1),Ry=C(Vt(),1),Hl=C(Wr(),1);var yy=C(We(),1),Bl=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,yy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as ED,isNullable as Ay}from"@vkontakte/videoplayer-shared/es2018";var Ty=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Iy=a=>{var e;try{let t=TD(),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 TD(){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 _l=D(Vt(),1);import{videoSizeToQuality as bD}from"@vkontakte/videoplayer-shared/es2018";var my=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Ct(s):void 0)!=null?u:bD({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}),Nl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,_l.default)(r.split("."),0),isDefault:i}),Fl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,_l.default)(i.split("."),0)}),ql=a=>"url"in a,be=a=>a.type==="template",Ra=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var yy=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},mt=(a,e)=>{let t=a;t=(0,Ul.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Ty.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ul.default)(t,n,(o,u)=>Sy(s)?o:Sy(u)?s:(0,Iy.default)(s,parseInt(u,10),"0"))}return t},xy=(a,e)=>{var I,M,L,j,V,_,F,A,k,Q,ee,w,T,R,q,B,ke,li,yr,U,ne,pe,he,St,Tr,yt,Qt,Ir,ci,Tc,Ic,Ec,xc,Pc,wc,Ac,kc,Lc,Rc,$c,Mc,Dc,Cc,Vc,Bc,Oc,_c,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(qe=>{var Y,Gt;return(Gt=(Y=qe.textContent)==null?void 0:Y.trim())!=null?Gt:""}),o=(I=(0,Ey.default)(n,0))!=null?I:"",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((qe,Y)=>({...qe,[Y.id]:Y.children}),{}),v=b.reduce((qe,Y)=>({...qe,[Y.id]:Y.getAttribute("duration")}),{});p?d=yy(p):(0,Hl.default)(v).filter(qe=>qe).length&&!u?d=(0,Hl.default)(v).reduce((qe,Y)=>{var Gt;return qe+((Gt=yy(Y))!=null?Gt:0)},0):f&&(d=parseInt(f,10));let S=0,y=(L=(M=s.getAttribute("profiles"))==null?void 0:M.split(","))!=null?L:[];for(let qe of b.map(Y=>Y.id))for(let Y of g[qe]){let Gt=(j=Y.getAttribute("id"))!=null?j:"id"+(S++).toString(10),di=(V=Y.getAttribute("mimeType"))!=null?V:"",Xn=(_=Y.getAttribute("codecs"))!=null?_:"",Jn=(F=Y.getAttribute("contentType"))!=null?F:di==null?void 0:di.split("/")[0],QT=(k=(A=Y.getAttribute("profiles"))==null?void 0:A.split(","))!=null?k:[],Zc=(ee=fy((Q=Y.getAttribute("lang"))!=null?Q:""))!=null?ee:{},Za=(R=(T=(w=Y.querySelector("Label"))==null?void 0:w.textContent)==null?void 0:T.trim())!=null?R:void 0,GT=Y.querySelectorAll("Representation"),WT=Y.querySelector("SegmentTemplate"),YT=(B=(q=Y.querySelector("Role"))==null?void 0:q.getAttribute("value"))!=null?B:void 0,Er=Jn,X={id:Gt,language:Zc.language,isDefault:YT==="main",label:Za,codecs:Xn,hdr:Er==="video"&&Bl(Xn),mime:di,representations:[]};for(let W of GT){let Tt=(ke=W.getAttribute("lang"))!=null?ke:void 0,pi=(yr=(li=Za!=null?Za:Y.getAttribute("label"))!=null?li:W.getAttribute("label"))!=null?yr:void 0,es=(pe=(ne=(U=W.querySelector("BaseURL"))==null?void 0:U.textContent)==null?void 0:ne.trim())!=null?pe:"",Wt=new URL(es||o,e).toString(),It=(he=W.getAttribute("mimeType"))!=null?he:di,ts=(Tr=(St=W.getAttribute("codecs"))!=null?St:Xn)!=null?Tr:"",rs;if(Jn==="text"){let Et=W.getAttribute("id")||"",is=((yt=Zc.privateuse)==null?void 0:yt.includes("x-auto"))||Et.includes("_auto"),Yt=W.querySelector("SegmentTemplate");if(Yt){let hi={representationId:(Qt=W.getAttribute("id"))!=null?Qt:void 0,bandwidth:(Ir=W.getAttribute("bandwidth"))!=null?Ir:void 0},as=parseInt((ci=W.getAttribute("bandwidth"))!=null?ci:"",10)/1e3,ss=(Ic=parseInt((Tc=Yt.getAttribute("startNumber"))!=null?Tc:"",10))!=null?Ic:1,xr=parseInt((Ec=Yt.getAttribute("timescale"))!=null?Ec:"",10),Zn=(xc=Yt.querySelectorAll("SegmentTimeline S"))!=null?xc:[],Pr=Yt.getAttribute("media");if(!Pr)continue;let ns=[],os=0,us="",wr=0,fi=ss,fe=0;for(let Ue of Zn){let zt=parseInt((Pc=Ue.getAttribute("d"))!=null?Pc:"",10),Ve=parseInt((wc=Ue.getAttribute("r"))!=null?wc:"",10)||0,xt=parseInt((Ac=Ue.getAttribute("t"))!=null?Ac:"",10);fe=Number.isFinite(xt)?xt:fe;let Kt=zt/xr*1e3,Pt=fe/xr*1e3;for(let Xe=0;Xe<Ve+1;Xe++){let wt=mt(Pr,{...hi,segmentNumber:fi.toString(10),segmentTime:(fe+Xe*zt).toString(10)}),Ar=(Pt!=null?Pt:0)+Xe*Kt,bi=Ar+Kt;fi++,ns.push({time:{from:Ar,to:bi},url:wt})}fe+=(Ve+1)*zt,os+=(Ve+1)*Kt}wr=fe/xr*1e3,us=mt(Pr,{...hi,segmentNumber:fi.toString(10),segmentTime:fe.toString(10)});let mi={time:{from:wr,to:1/0},url:us},ot={type:"template",baseUrl:Wt,segmentTemplateUrl:Pr,initUrl:"",totalSegmentsDurationMs:os,segments:ns,nextSegmentBeyondManifest:mi,timescale:xr};rs={id:Et,kind:"text",segmentReference:ot,profiles:[],duration:d,bitrate:as,mime:"",codecs:"",width:0,height:0,isAuto:is}}else rs={id:Et,isAuto:is,kind:"text",url:Wt}}else{let Et=(Lc=(kc=W.getAttribute("contentType"))!=null?kc:It==null?void 0:It.split("/")[0])!=null?Lc:Jn,is=($c=(Rc=Y.getAttribute("profiles"))==null?void 0:Rc.split(","))!=null?$c:[],Yt=parseInt((Mc=W.getAttribute("width"))!=null?Mc:"",10),hi=parseInt((Dc=W.getAttribute("height"))!=null?Dc:"",10),as=parseInt((Cc=W.getAttribute("bandwidth"))!=null?Cc:"",10)/1e3,ss=(Vc=W.getAttribute("frameRate"))!=null?Vc:"",xr=(Bc=W.getAttribute("quality"))!=null?Bc:void 0,Zn=ss?hy(ss):void 0,Pr=(Oc=W.getAttribute("id"))!=null?Oc:"id"+(S++).toString(10),ns=Et==="video"?`${hi}p`:Et==="audio"?`${as}Kbps`:ts,os=`${Pr}@${ns}`,us=[...y,...QT,...is],wr,fi=W.querySelector("SegmentBase"),fe=(_c=W.querySelector("SegmentTemplate"))!=null?_c:WT;if(fi){let ot=(Fc=(Nc=W.querySelector("SegmentBase Initialization"))==null?void 0:Nc.getAttribute("range"))!=null?Fc:"",[Ue,zt]=ot.split("-").map(wt=>parseInt(wt,10)),Ve={from:Ue,to:zt},xt=(qc=W.querySelector("SegmentBase"))==null?void 0:qc.getAttribute("indexRange"),[Kt,Pt]=xt?xt.split("-").map(wt=>parseInt(wt,10)):[],Xe=xt?{from:Kt,to:Pt}:void 0;wr={type:"byteRange",url:Wt,initRange:Ve,indexRange:Xe}}else if(fe){let ot={representationId:(Uc=W.getAttribute("id"))!=null?Uc:void 0,bandwidth:(Hc=W.getAttribute("bandwidth"))!=null?Hc:void 0},Ue=parseInt((jc=fe.getAttribute("timescale"))!=null?jc:"",10),zt=(Qc=fe.getAttribute("initialization"))!=null?Qc:"",Ve=fe.getAttribute("media"),xt=(Wc=parseInt((Gc=fe.getAttribute("startNumber"))!=null?Gc:"",10))!=null?Wc:1,Kt=mt(zt,ot);if(!Ve)throw new ReferenceError("No media attribute in SegmentTemplate");let Pt=(Yc=fe.querySelectorAll("SegmentTimeline S"))!=null?Yc:[],Xe=[],wt=0,Ar="",bi=0;if(Pt.length){let ls=xt,He=0;for(let kr of Pt){let Je=parseInt((zc=kr.getAttribute("d"))!=null?zc:"",10),Xt=parseInt((Kc=kr.getAttribute("r"))!=null?Kc:"",10)||0,cs=parseInt((Xc=kr.getAttribute("t"))!=null?Xc:"",10);He=Number.isFinite(cs)?cs:He;let eo=Je/Ue*1e3,to=He/Ue*1e3;for(let ds=0;ds<Xt+1;ds++){let KT=mt(Ve,{...ot,segmentNumber:ls.toString(10),segmentTime:(He+ds*Je).toString(10)}),ed=(to!=null?to:0)+ds*eo,XT=ed+eo;ls++,Xe.push({time:{from:ed,to:XT},url:KT})}He+=(Xt+1)*Je,wt+=(Xt+1)*eo}bi=He/Ue*1e3,Ar=mt(Ve,{...ot,segmentNumber:ls.toString(10),segmentTime:He.toString(10)})}else if(gD(d)){let He=parseInt((Jc=fe.getAttribute("duration"))!=null?Jc:"",10)/Ue*1e3,kr=Math.ceil(d/He),Je=0;for(let Xt=1;Xt<kr;Xt++){let cs=mt(Ve,{...ot,segmentNumber:Xt.toString(10),segmentTime:Je.toString(10)});Xe.push({time:{from:Je,to:Je+He},url:cs}),Je+=He}bi=Je,Ar=mt(Ve,{...ot,segmentNumber:kr.toString(10),segmentTime:Je.toString(10)})}let zT={time:{from:bi,to:1/0},url:Ar};wr={type:"template",baseUrl:Wt,segmentTemplateUrl:Ve,initUrl:Kt,totalSegmentsDurationMs:wt,segments:Xe,nextSegmentBeyondManifest:zT,timescale:Ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Et||!It)continue;let mi={video:"video",audio:"audio",text:"text"}[Et];if(!mi)continue;Er||(Er=mi),rs={id:os,kind:mi,segmentReference:wr,profiles:us,duration:d,bitrate:as,mime:It,codecs:ts,width:Yt,height:hi,fps:Zn,quality:xr}}X.language||(X.language=Tt),X.label||(X.label=pi),X.mime||(X.mime=It),X.codecs||(X.codecs=ts),X.hdr||(X.hdr=Er==="video"&&Bl(ts)),X.representations.push(rs)}if(Er){let W=i[Er].find(Tt=>Tt.id===X.id);if(W&&X.representations.every(Tt=>be(Tt.segmentReference)))for(let Tt of W.representations){let pi=X.representations.find(It=>It.id===Tt.id),es=pi==null?void 0:pi.segmentReference,Wt=Tt.segmentReference;Wt.segments.push(...es.segments),Wt.nextSegmentBeyondManifest=es.nextSegmentBeyondManifest}else i[Er].push(X)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var wy=D(We(),1);import{isNonNullable as Py}from"@vkontakte/videoplayer-shared/es2018";var ge=(a,e)=>Py(a)&&Py(e)&&a.readyState==="open"&&(0,wy.default)([...a.activeSourceBuffers],e);var $a=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new pr(0);this.currentLowLatencySegmentLength$=new pr(0);this.currentSegmentLength$=new pr(0);this.onLastSegment$=new pr(!1);this.fullyBuffered$=new pr(!1);this.playingRepresentation$=new pr(void 0);this.playingRepresentationInit$=new pr(void 0);this.error$=new yD;this.gaps=[];this.subscription=new TD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ce;this.switchAbortController=new ce;this.destroyAbortController=new ce;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=Ft(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ae(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(Ql(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Ql(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:bt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ge(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,kl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=it(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Ae(r,"No init buffer for starting representation"),Ae(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Ft(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ae(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Ae(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ii(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ft(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ae(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Ae(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ge(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();ii(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ft(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,In.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!be(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);Ae(i);let s=this.segments.get(r);Ae(s,"No segments for starting representation");let n=this.initData.get(r);if(Ae(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ce,Ft(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);Ae(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(de(o)||de(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),Ae(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ge(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();ii(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(){!de(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ce,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(de(e)||de(this.downloadingRepresentationId)||de(this.playingRepresentationId)||de(this.sourceBuffer)||!ge(this.mediaSource,this.sourceBuffer)||ii(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ae(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);ii(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=it(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)&&kl(this.sourceBuffer.buffered)>=this.bufferLimit){let l=it(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,Tn.default)(o,i))l="high";else{let c=(0,ai.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&it(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ai.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;ii(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,In.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,In.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!be(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ai.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;Ae(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(!be(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=mt(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&&ia&&ia(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ia&&ia(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&ge(this.mediaSource,this.sourceBuffer)&&!(_t(this.sourceBuffer.buffered,p)&&_t(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}async loadSegments(e,t,r="auto"){be(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){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&&(await Ft(o,async function*(){let c=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=yn(),!c)return;let d=new DataView(c),p=La(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?await Promise.all(l):await 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())be(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){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&&(await Ft(n,async function*(){let u=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ql(window,"online").pipe(SD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=yn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ra(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(be(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ai.default)(e,0).byte.from,to:(0,ai.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=yn(),await 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:bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!be(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=yn();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Tn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=La(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){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)continue;if(s.aborted){await n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,f=d<=i;if(!h)continue;let b=La(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var r;if(!(de(this.sourceBuffer)||!ge(this.mediaSource,this.sourceBuffer))){!this.isLive&&vD.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(_t(this.sourceBuffer.buffered,e.segment.time.from,100)&&_t(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:bt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ql(e.segment)&&(e.segment.size=e.fedBytes);for(let 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=Pl(()=>(0,Ay.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Ft(this.destroyAbortController.signal,async function*(){let o=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,La(e.mime),i)).then(async o=>{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&&be(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:bt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||de(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({...u.time}),i=n(i);let l=ql(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,Tn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ge(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||!ge(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||!ge(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||de(e)?0:it(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Pl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:bt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(de(this.sourceBuffer)||!ge(this.mediaSource,this.sourceBuffer)||de(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")}}handleAsyncError(e,t){this.error$.next({id:t,category:bt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ma=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var ky=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 Ry,fromEvent as $y,merge as ID,now as Ca,Subscription as ED,Subject as My,ValueSubject as Wl,flattenObject as si,ErrorCategory as Va}from"@vkontakte/videoplayer-shared/es2018";var Ly=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var xn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Wl(void 0);this.lastConnectionReused$=new Wl(void 0);this.lastRequestFirstBytes$=new Wl(void 0);this.recoverableError$=new My;this.error$=new My;this.abortAllController=new ce;this.subscription=new ED;this.fetchManifest=Da(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ma(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Ly(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(En);return i?(t.log("success",si({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",si({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Da(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var F,A;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let k=new URL(l,location.href);k.searchParams.append("bytes",`${r.from}-${r.to}`),l=k.toString();break}default:Ry(t)}this.requestQuic&&(l=Ma(l));let p=this.abortAllController.signal,h;if(n){let k=new ce;if(h=ID($y(this.abortAllController.signal,"abort"),$y(n,"abort")).subscribe(()=>{try{k.abort()}catch(Q){En(Q)}}),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(Q){En(Q)}p=k.signal}let f=Ca();d.log("startRequest",si({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:p}),g=Ca();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((F=this.throughputEstimator)==null||F.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let k=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:k}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let k=Ca(),Q={requestStartedAt:f,requestEndedAt:k,duration:k-f};return d.log("endRequest",si(Q)),d.end(),b.arrayBuffer()}let[v,S]=b.body.tee(),y=v.getReader();o&&((A=this.throughputEstimator)==null||A.trackStream(S,u));let x=0,I=new Uint8Array(0),M=!1,L=k=>{h==null||h.unsubscribe(),M=!0,En(k)},j=Da(p,async function*({done:k,value:Q}){if(x===0&&this.lastRequestFirstBytes$.next(Ca()-f),p.aborted){h==null||h.unsubscribe();return}if(!k&&Q){let ee=new Uint8Array(I.length+Q.length);ee.set(I),ee.set(Q,I.length),I=ee,x+=Q.byteLength,i==null||i(new DataView(I.buffer),x),yield y==null?void 0:y.read().then(j,L)}}.bind(this));yield y==null?void 0:y.read().then(j,L),h==null||h.unsubscribe();let V=Ca(),_={failed:M,requestStartedAt:f,requestEndedAt:V,duration:V-f};return M?(d.error("endRequest",si(_)),d.end(),null):(d.log("endRequest",si(_)),d.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=Da(this.abortAllController.signal,async function*(e,t,r){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Da(this.abortAllController.signal,async function*(e,t){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=>({...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}=ky(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Ry(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let r=await at(e,t);if(r.ok)return r;let i=await r.text(),s=parseInt(i);switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Va.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Va.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Va.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Va.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Va.FATAL})}}},En=a=>{if(!Ra(a))throw a};var hr=(a,e,t)=>t*e+(1-t)*a,Yl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Dy=(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 xD,ValueSubject as Cy}from"@vkontakte/videoplayer-shared/es2018";var qt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Cy(e.initial),this.debounced$=new Cy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new me(`raw_${t}`),this.smoothedSeries$=new me(`smoothed_${t}`),this.reportedSeries$=new me(`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+=(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)&&(xD(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Pn=class extends qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=hr(this.slow,e,this.params.emaAlphaSlow),this.fast=hr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var wn=class extends qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Yl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=hr(this.emaSmoothed,e,this.params.emaAlpha);let r=Dy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var An=class extends qt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?hr(this.smoothed,t,this.params.emaAlpha):t}};var fr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Pn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new wn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new An({initial:e,label:"liveEdgeDelay",...t})}};var zl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as PD,ValueSubject as wD}from"@vkontakte/videoplayer-shared/es2018";var Ba=class a{constructor(e,t){this.currentRepresentation$=new wD(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(!PD(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,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&&be(t.segmentReference))}};var CD=["timeupdate","progress","play","seeked","stalled","waiting"],VD=["timeupdate","progress","loadeddata","playing","seeked"];var Ln=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new _y;this.representationSubscription=new _y;this.state$=new $("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new kn;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(void 0);this.bufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new kn;this.fetcherError$=new kn;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new kn;this.gapWatchdogActive=!1;this.destroyController=new ce;this.initManifest=Kl(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(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:st.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Kl(this.destroyController.signal,async 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:st.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=xy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=bS(e))!=null?n:{id:"ManifestParsing",category:st.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=ht())==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=Yv(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);LD.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",_a(s)),s}.bind(this));this.initRepresentations=Kl(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",_a({initialVideo:e,initialAudio:t,sourceHls:r})),mr(this.manifest),mr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(gr(p,"error").pipe(Oa(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:st.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?$v():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ln())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new $a("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],By(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new $a("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(Jl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=Ys(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,f+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(vr(...VD.map(p=>gr(this.element,p))).pipe(ni(p=>this.element?it(this.element.buffered,this.element.currentTime*1e3):0),Xl(),MD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(vr(gr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(br({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ni(({isActiveLive:h,isLowLatency:f})=>h&&f),Xl()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||zl(this.element,1)})),this.representationSubscription.add(br({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Oa(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(br({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$,currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(Oa(({isActiveLive:h,isLowLatency:f,currentLowLatencySegmentLength:b})=>h&&f&&!!b)).subscribe(({currentLowLatencySegmentLength:h})=>{let f=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(f,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(br({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Oa(({isLive:h})=>h),ni(h=>({...h})),Xl((h,f)=>f.bufferLength<h.bufferLength),ni(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=Ys(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(br({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-g;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(y)>v&&(x=1+Math.sign(y)*S),zl(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(y=>{var x,I;return(I=(x=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:x.to)!=null?I:v}))-v}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(br({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(DD(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(mr(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=Ys(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,I=isFinite(h)?h:f,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=v<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLive$.next(L);let j="none";if(M?j="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(V=>V.proceedLowLatencyLive()),j="active_low_latency"):g!==0&&I<S?j="live_forward_buffering":I<S+x&&(j="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),j==="live_forward_buffering"||j==="live_with_target_offset"){let V=p-(S+y),_=this.normolizeLiveOffset(Math.trunc(g+V/b)),F=Math.abs(_-g),A;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?A=g:_>0&&F>this.tuning.dashCmafLive.offsetCalculationError?A=_:A=0,this.manifestUrlString=le(this.manifestUrlString,A,2)}j!=="none"&&j!=="active_low_latency"&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:st.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=vr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ni(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=vr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ni(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(vr(this.forceEnded$,br({allBuffersFull:l,someBufferEnded:c}).pipe(Oa(({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:st.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(vr(...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 f=[];return h.duration&&f.push(h.duration),be(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&By(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:st.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new xn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=fr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;mr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLive$.next(t===0),this.liveLastSeekOffset=t,this.manifestUrlString=le(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){mr(this.element),this.state$.setState("running"),this.subscription.add(vr(...CD.map(e=>gr(this.element,e)),gr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:st.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(gr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(gr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&_t(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,g,v,S,y,x,I,M;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=$D(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,c=(x=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?x:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset).catch(L=>{this.error$.next({id:"stallIntervalCallback",category:st.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:L})}),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let L=this.element.currentTime*1e3;(I=this.videoBufferManager)==null||I.maintain(L),(M=this.audioBufferManager)==null||M.maintain(L),i.position=L}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:st.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)}async seek(e,t){var i,s,n,o,u;mr(this.element),mr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),_t(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(Oy(this.element)||Oy(this.videoBufferManager))&&(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=RD(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await 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=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),r={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=i&&u.to+n>i&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,r={...r,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",_a(r)))}}};var Rn=class{constructor(e,t){this.fov=e,this.orientation=t}};var $n=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(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={...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*(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 Ny=`attribute vec2 a_vertex;
70
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var _l=C(Vt(),1);import{videoSizeToQuality as ID}from"@vkontakte/videoplayer-shared/es2018";var Ey=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Ct(s):void 0)!=null?u:ID({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},xy=({id:a,bitrate:e})=>({id:a,bitrate:e}),Py=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),wy=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Nl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,_l.default)(r.split("."),0),isDefault:i}),Fl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,_l.default)(i.split("."),0)}),ql=a=>"url"in a,be=a=>a.type==="template",La=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ky=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},mt=(a,e)=>{let t=a;t=(0,Ul.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Ly.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ul.default)(t,n,(o,u)=>Ay(s)?o:Ay(u)?s:(0,$y.default)(s,parseInt(u,10),"0"))}return t},My=(a,e)=>{var V,_,F,A,k,Q,ee,w,T,$,q,B,Ae,ui,vr,U,ne,pe,he,St,Sr,yt,Qt,yr,li,Pc,wc,Ac,kc,Lc,$c,Rc,Mc,Dc,Cc,Vc,Bc,Oc,_c,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,rd,id,ad,sd,nd;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(qe=>{var Y,Gt;return(Gt=(Y=qe.textContent)==null?void 0:Y.trim())!=null?Gt:""}),o=(V=(0,Ry.default)(n,0))!=null?V:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],p=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,y=s.getAttribute("mediaPresentationDuration"),S=[...s.getElementsByTagName("Period")],E=S.reduce((qe,Y)=>({...qe,[Y.id]:Y.children}),{}),I=S.reduce((qe,Y)=>({...qe,[Y.id]:Y.getAttribute("duration")}),{});y?v=ky(y):(0,Hl.default)(I).filter(qe=>qe).length&&!u?v=(0,Hl.default)(I).reduce((qe,Y)=>{var Gt;return qe+((Gt=ky(Y))!=null?Gt:0)},0):b&&(v=parseInt(b,10));let D=0,L=(F=(_=s.getAttribute("profiles"))==null?void 0:_.split(","))!=null?F:[];for(let qe of S.map(Y=>Y.id))for(let Y of E[qe]){let Gt=(A=Y.getAttribute("id"))!=null?A:"id"+(D++).toString(10),ci=(k=Y.getAttribute("mimeType"))!=null?k:"",Xn=(Q=Y.getAttribute("codecs"))!=null?Q:"",Jn=(ee=Y.getAttribute("contentType"))!=null?ee:ci==null?void 0:ci.split("/")[0],XT=(T=(w=Y.getAttribute("profiles"))==null?void 0:w.split(","))!=null?T:[],od=(q=Iy(($=Y.getAttribute("lang"))!=null?$:""))!=null?q:{},Xa=(ui=(Ae=(B=Y.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:Ae.trim())!=null?ui:void 0,JT=Y.querySelectorAll("Representation"),ZT=Y.querySelector("SegmentTemplate"),eI=(U=(vr=Y.querySelector("Role"))==null?void 0:vr.getAttribute("value"))!=null?U:void 0,Tr=Jn,J={id:Gt,language:od.language,isDefault:eI==="main",label:Xa,codecs:Xn,hdr:Tr==="video"&&Bl(Xn),mime:ci,representations:[]};for(let W of JT){let Tt=(ne=W.getAttribute("lang"))!=null?ne:void 0,di=(he=(pe=Xa!=null?Xa:Y.getAttribute("label"))!=null?pe:W.getAttribute("label"))!=null?he:void 0,Ja=(yt=(Sr=(St=W.querySelector("BaseURL"))==null?void 0:St.textContent)==null?void 0:Sr.trim())!=null?yt:"",Wt=new URL(Ja||o,e).toString(),It=(Qt=W.getAttribute("mimeType"))!=null?Qt:ci,Za=(li=(yr=W.getAttribute("codecs"))!=null?yr:Xn)!=null?li:"",es;if(Jn==="text"){let Et=W.getAttribute("id")||"",ts=((Pc=od.privateuse)==null?void 0:Pc.includes("x-auto"))||Et.includes("_auto"),Yt=W.querySelector("SegmentTemplate");if(Yt){let pi={representationId:(wc=W.getAttribute("id"))!=null?wc:void 0,bandwidth:(Ac=W.getAttribute("bandwidth"))!=null?Ac:void 0},rs=parseInt((kc=W.getAttribute("bandwidth"))!=null?kc:"",10)/1e3,is=($c=parseInt((Lc=Yt.getAttribute("startNumber"))!=null?Lc:"",10))!=null?$c:1,Ir=parseInt((Rc=Yt.getAttribute("timescale"))!=null?Rc:"",10),Zn=(Mc=Yt.querySelectorAll("SegmentTimeline S"))!=null?Mc:[],Er=Yt.getAttribute("media");if(!Er)continue;let as=[],ss=0,ns="",xr=0,hi=is,me=0;for(let Ue of Zn){let zt=parseInt((Dc=Ue.getAttribute("d"))!=null?Dc:"",10),Ve=parseInt((Cc=Ue.getAttribute("r"))!=null?Cc:"",10)||0,xt=parseInt((Vc=Ue.getAttribute("t"))!=null?Vc:"",10);me=Number.isFinite(xt)?xt:me;let Kt=zt/Ir*1e3,Pt=me/Ir*1e3;for(let Xe=0;Xe<Ve+1;Xe++){let wt=mt(Er,{...pi,segmentNumber:hi.toString(10),segmentTime:(me+Xe*zt).toString(10)}),Pr=(Pt!=null?Pt:0)+Xe*Kt,fi=Pr+Kt;hi++,as.push({time:{from:Pr,to:fi},url:wt})}me+=(Ve+1)*zt,ss+=(Ve+1)*Kt}xr=me/Ir*1e3,ns=mt(Er,{...pi,segmentNumber:hi.toString(10),segmentTime:me.toString(10)});let mi={time:{from:xr,to:1/0},url:ns},ot={type:"template",baseUrl:Wt,segmentTemplateUrl:Er,initUrl:"",totalSegmentsDurationMs:ss,segments:as,nextSegmentBeyondManifest:mi,timescale:Ir};es={id:Et,kind:"text",segmentReference:ot,profiles:[],duration:v,bitrate:rs,mime:"",codecs:"",width:0,height:0,isAuto:ts}}else es={id:Et,isAuto:ts,kind:"text",url:Wt}}else{let Et=(Oc=(Bc=W.getAttribute("contentType"))!=null?Bc:It==null?void 0:It.split("/")[0])!=null?Oc:Jn,ts=(Nc=(_c=Y.getAttribute("profiles"))==null?void 0:_c.split(","))!=null?Nc:[],Yt=parseInt((Fc=W.getAttribute("width"))!=null?Fc:"",10),pi=parseInt((qc=W.getAttribute("height"))!=null?qc:"",10),rs=parseInt((Uc=W.getAttribute("bandwidth"))!=null?Uc:"",10)/1e3,is=(Hc=W.getAttribute("frameRate"))!=null?Hc:"",Ir=(jc=W.getAttribute("quality"))!=null?jc:void 0,Zn=is?Ty(is):void 0,Er=(Qc=W.getAttribute("id"))!=null?Qc:"id"+(D++).toString(10),as=Et==="video"?`${pi}p`:Et==="audio"?`${rs}Kbps`:Za,ss=`${Er}@${as}`,ns=[...L,...XT,...ts],xr,hi=W.querySelector("SegmentBase"),me=(Gc=W.querySelector("SegmentTemplate"))!=null?Gc:ZT;if(hi){let ot=(Yc=(Wc=W.querySelector("SegmentBase Initialization"))==null?void 0:Wc.getAttribute("range"))!=null?Yc:"",[Ue,zt]=ot.split("-").map(wt=>parseInt(wt,10)),Ve={from:Ue,to:zt},xt=(zc=W.querySelector("SegmentBase"))==null?void 0:zc.getAttribute("indexRange"),[Kt,Pt]=xt?xt.split("-").map(wt=>parseInt(wt,10)):[],Xe=xt?{from:Kt,to:Pt}:void 0;xr={type:"byteRange",url:Wt,initRange:Ve,indexRange:Xe}}else if(me){let ot={representationId:(Kc=W.getAttribute("id"))!=null?Kc:void 0,bandwidth:(Xc=W.getAttribute("bandwidth"))!=null?Xc:void 0},Ue=parseInt((Jc=me.getAttribute("timescale"))!=null?Jc:"",10),zt=(Zc=me.getAttribute("initialization"))!=null?Zc:"",Ve=me.getAttribute("media"),xt=(td=parseInt((ed=me.getAttribute("startNumber"))!=null?ed:"",10))!=null?td:1,Kt=mt(zt,ot);if(!Ve)throw new ReferenceError("No media attribute in SegmentTemplate");let Pt=(rd=me.querySelectorAll("SegmentTimeline S"))!=null?rd:[],Xe=[],wt=0,Pr="",fi=0;if(Pt.length){let os=xt,He=0;for(let wr of Pt){let Je=parseInt((id=wr.getAttribute("d"))!=null?id:"",10),Xt=parseInt((ad=wr.getAttribute("r"))!=null?ad:"",10)||0,us=parseInt((sd=wr.getAttribute("t"))!=null?sd:"",10);He=Number.isFinite(us)?us:He;let eo=Je/Ue*1e3,to=He/Ue*1e3;for(let ls=0;ls<Xt+1;ls++){let rI=mt(Ve,{...ot,segmentNumber:os.toString(10),segmentTime:(He+ls*Je).toString(10)}),ud=(to!=null?to:0)+ls*eo,iI=ud+eo;os++,Xe.push({time:{from:ud,to:iI},url:rI})}He+=(Xt+1)*Je,wt+=(Xt+1)*eo}fi=He/Ue*1e3,Pr=mt(Ve,{...ot,segmentNumber:os.toString(10),segmentTime:He.toString(10)})}else if(ED(v)){let He=parseInt((nd=me.getAttribute("duration"))!=null?nd:"",10)/Ue*1e3,wr=Math.ceil(v/He),Je=0;for(let Xt=1;Xt<wr;Xt++){let us=mt(Ve,{...ot,segmentNumber:Xt.toString(10),segmentTime:Je.toString(10)});Xe.push({time:{from:Je,to:Je+He},url:us}),Je+=He}fi=Je,Pr=mt(Ve,{...ot,segmentNumber:wr.toString(10),segmentTime:Je.toString(10)})}let tI={time:{from:fi,to:1/0},url:Pr};xr={type:"template",baseUrl:Wt,segmentTemplateUrl:Ve,initUrl:Kt,totalSegmentsDurationMs:wt,segments:Xe,nextSegmentBeyondManifest:tI,timescale:Ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Et||!It)continue;let mi={video:"video",audio:"audio",text:"text"}[Et];if(!mi)continue;Tr||(Tr=mi),es={id:ss,kind:mi,segmentReference:xr,profiles:ns,duration:v,bitrate:rs,mime:It,codecs:Za,width:Yt,height:pi,fps:Zn,quality:Ir}}J.language||(J.language=Tt),J.label||(J.label=di),J.mime||(J.mime=It),J.codecs||(J.codecs=Za),J.hdr||(J.hdr=Tr==="video"&&Bl(Za)),J.representations.push(es)}if(Tr){let W=i[Tr].find(Tt=>Tt.id===J.id);if(W&&J.representations.every(Tt=>be(Tt.segmentReference)))for(let Tt of W.representations){let di=J.representations.find(It=>It.id===Tt.id),Ja=di==null?void 0:di.segmentReference,Wt=Tt.segmentReference;Wt.segments.push(...Ja.segments),Wt.nextSegmentBeyondManifest=Ja.nextSegmentBeyondManifest}else i[Tr].push(J)}}return{duration:v,streams:i,baseUrls:n,live:g}};var Cy=C(We(),1);import{isNonNullable as Dy}from"@vkontakte/videoplayer-shared/es2018";var ge=(a,e)=>Dy(a)&&Dy(e)&&a.readyState==="open"&&(0,Cy.default)([...a.activeSourceBuffers],e);var $a=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new hr(0);this.currentLowLatencySegmentLength$=new hr(0);this.currentSegmentLength$=new hr(0);this.onLastSegment$=new hr(!1);this.fullyBuffered$=new hr(!1);this.playingRepresentation$=new hr(void 0);this.playingRepresentationInit$=new hr(void 0);this.error$=new wD;this.gaps=[];this.subscription=new AD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ce;this.switchAbortController=new ce;this.destroyAbortController=new ce;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=Ft(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);we(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new $S(this.sourceBuffer),this.subscription.add(Ql(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Ql(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ft.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ge(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,kl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=it(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);we(r,"No init buffer for starting representation"),we(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Ft(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);we(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),we(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ti(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ft(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);we(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),we(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ge(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();ti(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ft(this.destroyAbortController.signal,async function*(e){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||!be(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);we(i);let s=this.segments.get(r);we(s,"No segments for starting representation");let n=this.initData.get(r);if(we(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.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ce,Ft(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);we(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(de(o)||de(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),we(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ge(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();ti(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(){!de(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ce,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(de(e)||de(this.downloadingRepresentationId)||de(this.playingRepresentationId)||de(this.sourceBuffer)||!ge(this.mediaSource,this.sourceBuffer)||ti(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(we(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);ti(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=it(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)&&kl(this.sourceBuffer.buffered)>=this.bufferLimit){let l=it(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});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,ri.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&it(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ri.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;ti(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||!be(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ri.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;we(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(!be(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=mt(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&&ra&&ra(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ra&&ra(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),y=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&y&&this.sourceBuffer&&ge(this.mediaSource,this.sourceBuffer)&&!(_t(this.sourceBuffer.buffered,p)&&_t(this.sourceBuffer.buffered,h)))&&g&&y});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}async loadSegments(e,t,r="auto"){be(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){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&&(await Ft(o,async function*(){let c=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await 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?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),La(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())be(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){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&&(await Ft(n,async function*(){let u=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ql(window,"online").pipe(PD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=vn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),La(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(be(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ri.default)(e,0).byte.from,to:(0,ri.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!be(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:ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Sn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=ka(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){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)continue;if(s.aborted){await n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,m=d<=i;if(!h)continue;let b=ka(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var r;if(!(de(this.sourceBuffer)||!ge(this.mediaSource,this.sourceBuffer))){!this.isLive&&xD.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(_t(this.sourceBuffer.buffered,e.segment.time.from,100)&&_t(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ft.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ql(e.segment)&&(e.segment.size=e.fedBytes);for(let 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=Pl(()=>(0,Vy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Ft(this.destroyAbortController.signal,async function*(){let o=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ka(e.mime),i)).then(async o=>{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&&be(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:ft.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||de(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({...u.time}),i=n(i);let l=ql(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let 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?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ge(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||!ge(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||!ge(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||de(e)?0:it(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Pl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:ft.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(de(this.sourceBuffer)||!ge(this.mediaSource,this.sourceBuffer)||de(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")}}handleAsyncError(e,t){this.error$.next({id:t,category:ft.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ra=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var By=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 Ma,assertNever as _y,fromEvent as Ny,merge as kD,now as Da,Subscription as LD,Subject as Fy,ValueSubject as Wl,flattenObject as ii,ErrorCategory as Ca}from"@vkontakte/videoplayer-shared/es2018";var Oy=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 Wl(void 0);this.lastConnectionReused$=new Wl(void 0);this.lastRequestFirstBytes$=new Wl(void 0);this.recoverableError$=new Fy;this.error$=new Fy;this.abortAllController=new ce;this.subscription=new LD;this.fetchManifest=Ma(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ra(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Oy(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(Tn);return i?(t.log("success",ii({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ii({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ma(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var F,A;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let k=new URL(l,location.href);k.searchParams.append("bytes",`${r.from}-${r.to}`),l=k.toString();break}default:_y(t)}this.requestQuic&&(l=Ra(l));let p=this.abortAllController.signal,h;if(n){let k=new ce;if(h=kD(Ny(this.abortAllController.signal,"abort"),Ny(n,"abort")).subscribe(()=>{try{k.abort()}catch(Q){Tn(Q)}}),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(Q){Tn(Q)}p=k.signal}let m=Da();d.log("startRequest",ii({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:p}),g=Da();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((F=this.throughputEstimator)==null||F.addRawRtt(g-m),!b.ok||!b.body){h==null||h.unsubscribe();let k=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:k}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let k=Da(),Q={requestStartedAt:m,requestEndedAt:k,duration:k-m};return d.log("endRequest",ii(Q)),d.end(),b.arrayBuffer()}let[v,y]=b.body.tee(),S=v.getReader();o&&((A=this.throughputEstimator)==null||A.trackStream(y,u));let E=0,I=new Uint8Array(0),D=!1,L=k=>{h==null||h.unsubscribe(),D=!0,Tn(k)},j=Ma(p,async function*({done:k,value:Q}){if(E===0&&this.lastRequestFirstBytes$.next(Da()-m),p.aborted){h==null||h.unsubscribe();return}if(!k&&Q){let ee=new Uint8Array(I.length+Q.length);ee.set(I),ee.set(Q,I.length),I=ee,E+=Q.byteLength,i==null||i(new DataView(I.buffer),E),yield S==null?void 0:S.read().then(j,L)}}.bind(this));yield S==null?void 0:S.read().then(j,L),h==null||h.unsubscribe();let V=Da(),_={failed:D,requestStartedAt:m,requestEndedAt:V,duration:V-m};return D?(d.error("endRequest",ii(_)),d.end(),null):(d.log("endRequest",ii(_)),d.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ma(this.abortAllController.signal,async function*(e,t,r){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 y=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ma(this.abortAllController.signal,async function*(e,t){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=>({...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}=By(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:_y(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let r=await at(e,t),i=await r.text(),s=parseInt(i);if(r.ok||isNaN(s))return r;switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ca.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ca.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ca.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ca.FATAL});break;default:console.log(JSON.stringify(r)),console.log(s),this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ca.FATAL})}}},Tn=a=>{if(!La(a))throw a};var mr=(a,e,t)=>t*e+(1-t)*a,Yl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,qy=(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 $D,ValueSubject as Uy}from"@vkontakte/videoplayer-shared/es2018";var qt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Uy(e.initial),this.debounced$=new Uy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new fe(`raw_${t}`),this.smoothedSeries$=new fe(`smoothed_${t}`),this.reportedSeries$=new fe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(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)&&($D(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var En=class extends qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=mr(this.slow,e,this.params.emaAlphaSlow),this.fast=mr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var xn=class extends qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Yl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=mr(this.emaSmoothed,e,this.params.emaAlpha);let r=qy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Pn=class extends qt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?mr(this.smoothed,t,this.params.emaAlpha):t}};var fr=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({initial:e,label:"liveEdgeDelay",...t})}};var zl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as RD,ValueSubject as MD}from"@vkontakte/videoplayer-shared/es2018";var Va=class a{constructor(e,t){this.currentRepresentation$=new MD(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!RD(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,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&&be(t.segmentReference))}};var FD=["timeupdate","progress","play","seeked","stalled","waiting"],qD=["timeupdate","progress","loadeddata","playing","seeked"];var Ln=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Gy;this.representationSubscription=new Gy;this.state$=new R("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new kn;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.isActiveLive$=new K(!1);this.isLowLatency$=new K(!1);this.liveDuration$=new K(0);this.liveSeekableDuration$=new K(0);this.liveAvailabilityStartTime$=new K(0);this.liveStreamStatus$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.fetcherRecoverableError$=new kn;this.fetcherError$=new kn;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new kn;this.gapWatchdogActive=!1;this.destroyController=new ce;this.initManifest=Xl(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(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:st.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Xl(this.destroyController.signal,async 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:st.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=My(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=xS(e))!=null?n:{id:"ManifestParsing",category:st.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=pt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,p=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";d||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}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=rS(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);BD.isHDR&&h&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",Ba(s)),s}.bind(this));this.initRepresentations=Xl(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",Ba({initialVideo:e,initialAudio:t,sourceHls:r})),ai(this.manifest),ai(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(bt(p,"error").pipe(wn(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:st.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Nv():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.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new $a("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],jy(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new $a("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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(br(...qD.map(p=>bt(this.element,p))).pipe(Oa(p=>this.element?it(this.element.buffered,this.element.currentTime*1e3):0),An(),_D(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(br(bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(An()).subscribe(h=>this.liveStreamEndTimestamp=Zl())),this.subscription.add(bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Jl(1e3).subscribe(h=>{let m=Gs(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()})})).add(bt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(si({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Oa(({isActiveLive:h,isLowLatency:m})=>h&&m),An()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||zl(this.element,1)})),this.representationSubscription.add(si({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wn(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(si({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(wn(({isLive:h})=>h),An((h,m)=>m.bufferLength<h.bufferLength),Oa(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let g=Gs(this.manifestUrlString,2);return(h/2+m+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(si({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=h-g;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(S)>v&&(E=1+Math.sign(S)*y),zl(this.element,E)})),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(S=>{var E,I;return(I=(E=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?I:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(si({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ND(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,g=Gs(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,I=isFinite(h)?h:m,D=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let j="none";if(D?j="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(V=>V.proceedLowLatencyLive()),j="active_low_latency"):g!==0&&I<y?j="live_forward_buffering":I<y+E&&(j="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),j==="live_forward_buffering"||j==="live_with_target_offset"){let V=p-(y+S),_=this.normolizeLiveOffset(Math.trunc(g+V/b)),F=Math.abs(_-g),A=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?A=g:_>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(A=_),this.manifestUrlString=le(this.manifestUrlString,A,2)}(j==="live_with_target_offset"||j==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:st.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=br(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Oa(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=br(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Oa(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(br(this.forceEnded$,si({allBuffersFull:l,someBufferEnded:c}).pipe(wn(({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:st.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(br(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,ec.default)((0,ec.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),be(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&jy(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:st.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.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=fr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var i,s,n;ai(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Zl()-this.liveStreamEndTimestamp:0,r=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(r===0),this.manifestUrlString=le(this.manifestUrlString,r,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){ai(this.element),this.state$.setState("running"),this.subscription.add(br(...FD.map(e=>bt(this.element,e)),bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:st.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(bt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&_t(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,b,g,v,y,S,E,I,D;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=Zl(),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=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,c=(E=(S=this.audioBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?E: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%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(j=>{this.error$.next({id:"stallIntervalCallback",category:st.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:j})}),i.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(I=this.videoBufferManager)==null||I.maintain(L),(D=this.audioBufferManager)==null||D.maintain(L),i.position=L}this.tracer.log("stallIntervalCallback",Ba(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Jl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:st.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)}async seek(e,t){var i,s,n,o,u;ai(this.element),ai(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),_t(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(Qy(this.element)||Qy(this.videoBufferManager))&&(this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Ba({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=OD(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await 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=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),r={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=i&&u.to+n>i&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,r={...r,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ba(r)))}}};var $n=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/(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={...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*(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 Wy=`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 Fy=`#ifdef GL_ES
81
+ `;var Yy=`#ifdef GL_ES
82
82
  precision highp float;
83
83
  precision highp int;
84
84
  #else
@@ -121,6 +121,6 @@ void main(void) {
121
121
  // sample using new coordinates
122
122
  gl_FragColor = texture2D(u_texture, tc);
123
123
  }
124
- `;var Mn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Rn(this.params.fov,this.params.orientation),this.cameraRotationManager=new $n(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Ny,this.gl.VERTEX_SHADER),r=this.createShader(Fy,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 _D,now as qy,Subscription as ND,filter as FD,combine as Uy,ValueSubject as ec,isNonNullable as qD}from"@vkontakte/videoplayer-shared/es2018";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 ND;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(Uy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(FD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Uy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(_D(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=qy(),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,qD(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=qy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Hy=tc;import{combine as UD,map as HD,observeElementSize as jD,Subscription as QD,ValueSubject as rc,noop as GD}from"@vkontakte/videoplayer-shared/es2018";var Dn=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=GD}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(jD(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(UD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(HD(({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 Sr=class{constructor(e){this.subscription=new ZD;this.videoState=new $("stopped");this.droppedFramesManager=new sn;this.stallsManager=new Hy;this.elementSizeManager=new Dn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qi;this.audioTrackSwitchHistory=new Qi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return zD(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Mn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Oe(e.source.url),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(ie(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 Ln({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:jy.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(l=>!!l.length),Wy()).subscribe(l=>{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:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ic(l=>l.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.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Qy(Gy),Wy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(ic(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(tt(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(Be(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ne(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(KD(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Nl(h));let f=[];for(let b of h.representations){let g=by(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Fl(p));let h=[];for(let f of p.representations){let b=my({...f,streamId:p.id});b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let f=gy(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i)),this.subscription.add(Cn(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,JD(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Yy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===p.id});Gy(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,g)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Fa()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Fl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Fa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Nl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},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 o=t.playbackState.stateChangeStarted$.pipe(ic(({to:l})=>l==="ready"),Fa());this.subscription.add(Cn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ac(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Cn(o,this.player.state$.stateChangeEnded$,ac(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Cn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ac(["init"])).pipe(XD(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var L,j,V,_,F,A,k,Q,ee,w,T,R,q;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:B})=>B===i),o=t.currentVideoTrack$.getValue(),u=((_=(V=e.videoStream.getState())!=null?V:n&&((j=this.videoTracksMap.get(n))==null?void 0:j.stream))!=null?_:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:B})=>B===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=it(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(p,h||1/0),1),b=(F=e.audioStream.getState())!=null?F:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(A=[...this.audioStreamsMap.keys()].find(({id:B})=>B===(b==null?void 0:b.id)))!=null?A:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let B=en(n,c,(k=this.audioStreamsMap.get(g))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(Q=B==null?void 0:B.bitrate)!=null?Q:-1/0)}if(o){let B=en(o,c,(ee=this.audioStreamsMap.get(g))!=null?ee:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(w=B==null?void 0:B.bitrate)!=null?w:-1/0)}}let S=Ot(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=r?S!=null?S:n:n!=null?n:S,x=g&&Gg(y,c,(T=this.audioStreamsMap.get(g))!=null?T:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(R=this.videoTracksMap.get(y))==null?void 0:R.representation,M=x&&((q=this.audioTracksMap.get(x))==null?void 0:q.representation);if(I&&M)return[I,M];if(I&&!M&&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"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:jy.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Te(this.video),this.tracer.end()}};var qa=class extends Sr{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 zy,interval as eC,map as Ky}from"@vkontakte/videoplayer-shared/es2018";var Ua=class extends Sr{constructor(e){super(e),this.liveOffset=new dt,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(Ky(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(zy({interval:eC(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(zy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Ky(({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])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Jy=D(Ws(),1);import{assertNever as Ha,assertNonNullable as Xy,debounce as tC,ErrorCategory as Vn,filter as rC,isNonNullable as iC,isNullable as aC,map as Bn,merge as sC,Observable as nC,observableFrom as oC,Subscription as uC,videoSizeToQuality as lC}from"@vkontakte/videoplayer-shared/es2018";var Ke={};var oi=(a,e)=>new nC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),ja=class{constructor(e){this.subscription=new uC;this.videoState=new $("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"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ha(e)}break;default:Ha(t)}};this.textTracksManager=new Oe(e.source.url),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(ie(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:Vn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Jy.default)(import("hls.js").then(i=>{e||(Ke.Hls=i.default,Ke.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Xy(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Xy(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Vn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=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(tt(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(Be(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ne(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Bn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(oi(this.hls,Ke.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Vn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(oi(this.hls,Ke.Events.MANIFEST_PARSED).pipe(Bn(({levels:l})=>l.reduce((c,d)=>{var S,y;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(y=Ct((S=d.attrs.QUALITY)!=null?S:""))!=null?y:lC({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(oi(this.hls,Ke.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(oi(this.hls,Ke.Events.LEVEL_LOADING).pipe(Bn(({url:l})=>ie(l))),t.hostname$),s(oi(this.hls,Ke.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($t(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=oi(this.hls,Ke.Events.LEVEL_SWITCHED).pipe(Bn(({level:l})=>n(this.hls.levels[l])));o.pipe(rC(iC)).subscribe(t.currentVideoTrack$,r),this.subscription.add($t(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(aC(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=sC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,oC(["init"])).pipe(tC(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)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vn.DOM,thrown:t}))||(this.videoState.setState("paused"),E(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"),E(this.params.desiredState.playbackState,"stopped",!0)}};var Zy="X-Playback-Duration",sc=async a=>{var i;let e=await at(a),t=await 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 yC,combine as TC,debounce as IC,ErrorCategory as Nn,filter as EC,filterChanged as xC,isNonNullable as rT,isNullable as Fn,map as iT,merge as PC,observableFrom as wC,Subscription as AC,ValueSubject as uc,VideoQuality as kC}from"@vkontakte/videoplayer-shared/es2018";var oc=D(cu(),1);import{videoSizeToQuality as cC,getExponentialDelay as dC}from"@vkontakte/videoplayer-shared/es2018";var pC=a=>{let e=null;if(a.QUALITY&&(e=Ct(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=cC({width:t,height:r})}return e!=null?e:null},hC=(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,oc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=pC(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[S,y]=d.RESOLUTION.split("x").map(x=>parseInt(x,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:f,size:g,fps:b})}if(c){let d=(0,oc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},fC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),nc=0,eT=async(a,e=a,t,r)=>{let s=await(await at(a,r)).text();nc+=1;try{let{qualityManifests:n,textTracks:o}=hC(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(nc<=t.manifestRetryMaxCount)return await fC(dC(nc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),eT(a,e,t)}return{qualityManifests:[],textTracks:[]}},On=eT;import{isNonNullable as mC,Subscription as bC,throttle as gC,ValueSubject as tT,Subject as vC,ErrorCategory as SC}from"@vkontakte/videoplayer-shared/es2018";var _n=class{constructor(e,t,r,i,s){this.subscription=new bC;this.abortControllers={destroy:new ce,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new tT(null);this.getCurrentTime$=new tT(null);this.error$=new vC;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(gC(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()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=await this.fetchManifestData();await this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let r=await this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}}async parseTextTracks(e,t){for(let r of e){let i=new URL(r.url,t).toString(),n=await(await at(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(mC(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([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ce;let{textTracks:e}=await this.fetchManifestData(),t=await 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}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:SC.WTF,thrown:t,message:e})}};var Qa=class{constructor(e){this.subscription=new AC;this.videoState=new $("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new uc([]);this.liveOffset=new dt;this.manifestStartTime$=new uc(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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((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"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return yC(t)}};var r;this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:kC.INVARIANT,url:this.params.source.url};let t=(i,s)=>On(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new _n(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Oe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Nn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Nn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new uc((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Nn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=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(Be(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ne(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"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(xC(),iT(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&&rT(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(ie(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(TC({startTime:this.manifestStartTime$.pipe(EC(rT)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(iT(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=PC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,wC(["init"])).pipe(IC(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),Te(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Fn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=le(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),sc(n).then(c=>{var d;if(!Fn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Fn(p)||!isFinite(p))&&at(n).then(h=>h.text()).then(h=>{var b;let f=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(f){let g=new URL(f,n).toString();sc(g).then(v=>{Fn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=le(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 LC,debounce as RC,ErrorCategory as lc,fromEvent as cc,isNonNullable as $C,isNullable as MC,map as aT,merge as sT,observableFrom as nT,Subscription as DC,ValueSubject as CC,VideoQuality as VC,clientChecker as BC}from"@vkontakte/videoplayer-shared/es2018";var Ga=class{constructor(e){this.subscription=new DC;this.videoState=new $("stopped");this.manifests$=new CC([]);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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return LC(t)}};this.textTracksManager=new Oe(e.source.url),this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:VC.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(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),On(le(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:lc.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||!i.from)&&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:lc.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(aT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(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(Be(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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&&$C(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(ie(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(aT(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)),!BC.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(sT(cc(o,"addtrack"),cc(o,"removetrack"),cc(o,"change"),nT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=sT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,nT(["init"])).pipe(RC(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(MC(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"),E(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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var lT=D(_r(),1),dc=D(zr(),1),cT=D(Vt(),1);import{assertNever as OC,assertNonNullable as oT,debounce as _C,ErrorCategory as uT,isHigherOrEqual as NC,isLowerOrEqual as FC,isNonNullable as qC,merge as UC,observableFrom as HC,Subscription as jC,map as QC}from"@vkontakte/videoplayer-shared/es2018";var Wa=class{constructor(e){this.subscription=new jC;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Oe;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.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return OC(e)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),(0,lT.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,dc.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:uT.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(QC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(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(Be(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ne(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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&&qC(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=UC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,HC(["init"])).pipe(_C(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;oT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];oT(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(ie(t))}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:uT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let p=Ot(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,dc.default)(this.trackUrls).map(d=>d.track);if(!i||!s||ji({limits:e,lowestAvailableQuality:(c=(0,cT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?FC(i,e.max):!0,u=e.min?NC(i,e.min):!0;o&&u||r(e)}};import{assertNever as pT,debounce as zC,merge as hT,observableFrom as KC,Subscription as XC,map as fT,ValueSubject as JC,ErrorCategory as hc,VideoQuality as ZC}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as GC}from"@vkontakte/videoplayer-shared/es2018";var dT=["stun:videostun.mycdn.me:80"],WC=1e3,YC=3,pc=()=>null,qn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:dT}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await 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:GC.WTF,message:e.message})}async onPeerConnectionStream(e){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()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await 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),WC)}normalizeOptions(e={}){let t={stunServerList:dT,maxRetryNumber:YC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ya=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new JC(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return pT(e)}};this.subscription=new XC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ye(e.container,e.tuning),this.liveStreamClient=new qn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Te(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})};hT(this.videoState.stateChangeStarted$.pipe(fT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(fT(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(Ne(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 pT(n.to)}},r)).add(hT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,KC(["init"])).pipe(zC(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(ie(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:ZC.INVARIANT}),this.video.srcObject=e,E(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:hc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var za=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 Xa,assertNonNullable as Ut,ErrorCategory as Un,filter as yT,isNonNullable as TT,isNullable as o0,map as u0,merge as l0,once as c0,Subject as se,Subscription as IT,ValueSubject as C,flattenObject as ET}from"@vkontakte/videoplayer-shared/es2018";import{Observable as e0,map as mT,Subscription as t0,Subject as r0}from"@vkontakte/videoplayer-shared/es2018";var bT=a=>new e0(e=>{let t=new t0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(mT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(mT(({type:l})=>l!==void 0)),n=new r0,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 i0,Subscription as a0,combine as s0,filter as vT,once as ST}from"@vkontakte/videoplayer-shared/es2018";function gT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as n0}from"@vkontakte/videoplayer-shared/es2018";var Ka=class Ka{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ce;this.subscriptions=new a0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(vT(s=>!!s.type),ST()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){n0.isSafari&&e!=="MPEG"||this.subscriptions.add(s0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(vT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),ST()).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}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=gT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await 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:Ka.errorId,category:i0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ka.errorId} exception`,thrown:e})}};Ka.errorId="VolumeMultiplierManager";var ui=Ka;var d0={chunkDuration:5e3,maxParallelRequests:5},Ja=class{constructor(e){this.current$=new C({type:void 0});this.providerError$=new se;this.noAvailableProvidersError$=new se;this.volumeMultiplierError$=new se;this.providerOutput={position$:new C(0),duration$:new C(1/0),volume$:new C({muted:!1,volume:1}),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableVideoTracks$:new C([]),currentVideoTrack$:new C(void 0),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0),isAudioAvailable$:new C(!0),autoVideoTrackLimitingAvailable$:new C(!1),autoVideoTrackLimits$:new C(void 0),currentBuffer$:new C(void 0),isBuffering$:new C(!0),error$:new se,fetcherError$:new se,fetcherRecoverableError$:new se,warning$:new se,willSeekEvent$:new se,soundProhibitedEvent$:new se,seekedEvent$:new se,loopedEvent$:new se,endedEvent$:new se,firstBytesEvent$:new se,loadedMetadataEvent$:new se,firstFrameEvent$:new se,canplay$:new se,isLive$:new C(void 0),isLowLatency$:new C(!1),canChangePlaybackSpeed$:new C(!0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),liveLatency$:new C(void 0),severeStallOccurred$:new se,availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),inPiP$:new C(!1),inFullscreen$:new C(!1),element$:new C(void 0),elementVisible$:new C(!0),availableSources$:new C(void 0),is3DVideo$:new C(!1),playbackState$:new C(""),getCurrentTime$:new C(null)};this.subscription=new IT;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=Qv([...Wv(this.params.tuning),...Gv(this.params.tuning)],this.params.tuning).filter(l=>TT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,fc.default)(i,l)),...t.filter(l=>(0,fc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",ET(s)),this.screenFormatsIterator=new za(s);let n=[...yl(!0),...yl(!1)];this.chromecastFormatsIterator=new za(n.filter(l=>TT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ui.isSupported()&&(this.volumeMultiplierManager=new ui(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(o0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Un.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Xa(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Ut(o),new qa({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Ua({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ut(o),ei||!this.params.tuning.useHlsJs?new Ga({...n,source:o}):new ja({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Qa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Wa({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ut(o),new lv({...n,source:o,config:{...d0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Ya({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 Xa(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ut(o),new Fi({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 Xa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Xa(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 Xa(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,url:r(e.url)}}return(0,PT.default)((0,xT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new IT,t=!1,r=0;return e.add(l0(this.providerOutput.error$.pipe(yT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),bT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(u0(i=>({id:`ProviderHangup:${i}`,category:Un.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(yT(({to:s})=>s==="playing"),c0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Un.NETWORK,u=i.category===Un.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...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",ET(n))})),e}};import{fromEvent as Hn,once as p0,combine as h0,Subscription as wT,ValueSubject as mc,map as f0,filter as m0,isNonNullable as jn,now as Ce,safeStorage as bc}from"@vkontakte/videoplayer-shared/es2018";var b0=5e3,AT="one_video_throughput",kT="one_video_rtt",gt=window.navigator.connection,LT=()=>{let a=gt==null?void 0:gt.downlink;if(jn(a)&&a!==10)return a*1e3},RT=()=>{let a=gt==null?void 0:gt.rtt;if(jn(a)&&a!==3e3)return a},$T=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},gc=class a{constructor(e){this.subscription=new wT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(AT)||(e.useBrowserEstimation?LT():void 0)||b0,r=(s=(i=a.load(kT))!=null?i:e.useBrowserEstimation?RT():void 0)!=null?s:0;if(this.throughput$=new mc(t),this.rtt$=new mc(r),this.rttAdjustedThroughput$=new mc($T(t,r,e.rttPenaltyRequestSize)),this.throughput=fr.getSmoothedValue(t,-1,e),this.rtt=fr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=LT();u&&this.throughput.next(u);let l=RT();jn(l)&&this.rtt.next(l)};gt&&"onchange"in gt&&this.subscription.add(Hn(gt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{bc.set(AT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{bc.set(kT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(h0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(f0(({throughput:n,rtt:o})=>$T(n,o,e.rttPenaltyRequestSize)),m0(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=Ce(),i=new wT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Hn(e,"progress").pipe(p0()).subscribe(s=>{t=s.loaded,r=Ce()}));break;case 1:case 0:i.add(Hn(e,"loadstart").subscribe(()=>{t=0,r=Ce()}));break}i.add(Hn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ce(),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=Ce(),n=0,o=Ce(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,Ce()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ce();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=Ce()}else n+=d.byteLength;o=Ce()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ce()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ce()-o,this.concurrentDownloads.size),n=0,o=Ce());await(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(jn(t))return(r=parseInt(t,10))!=null?r:void 0}},MT=gc;import{fillWithDefault as g0,VideoQuality as Qn}from"@vkontakte/videoplayer-shared/es2018";var DT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Qn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Qn.Q_720P,trafficSavingLimit:Qn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Qn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,useLazyInit:!1},CT=a=>{var e;return{...g0(a,DT),configName:[...(e=a.configName)!=null?e:[],...DT.configName]}};import{assertNonNullable as Gn,combine as vt,ErrorCategory as Wn,filter as ve,filterChanged as H,fromEvent as Sc,isNonNullable as x0,isNullable as P0,Logger as w0,map as N,mapTo as _T,merge as Ht,now as Yn,once as nt,Subject as G,Subscription as NT,tap as FT,ValueSubject as P,isHigher as A0,isInvariantQuality as qT,flattenObject as jt,throttle as yc,getTraceSubscriptionMethod as UT,Tracer as k0,InternalsExposure as L0,uuid as R0}from"@vkontakte/videoplayer-shared/es2018";import{merge as v0,map as S0,filter as VT,isNonNullable as y0}from"@vkontakte/videoplayer-shared/es2018";var vc=({seekState:a,position$:e})=>v0(a.stateChangeEnded$.pipe(S0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),VT(y0)),e.pipe(VT(()=>a.getState().state==="none")));import{assertNonNullable as T0}from"@vkontakte/videoplayer-shared/es2018";var BT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return T0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as I0,once as E0}from"@vkontakte/videoplayer-shared/es2018";var OT=(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(I0(i=>i.length>0),E0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var zn=class{constructor(e={configName:[]},t=k0.createRootTracer(!1)){this.id=R0();this.subscription=new NT;this.logger=new w0;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 $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),isLowLatency:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new 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({}),predefinedQualityLimitType$:new P("unknown"),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),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 G,ready$:new G,started$:new G,playing$:new G,paused$:new G,stopped$:new G,willStart$:new G,willResume$:new G,willPause$:new G,willStop$:new G,willDestruct$:new G,watchCoverageRecord$:new G,watchCoverageLive$:new G,managedError$:new G,fatalError$:new G,fetcherRecoverableError$:new G,ended$:new G,looped$:new G,seeked$:new G,willSeek$:new G,autoplaySoundProhibited$:new G,firstBytes$:new G,loadedMetadata$:new G,firstFrame$:new G,canplay$:new G,log$:new G,fetcherError$:new G,severeStallOccured$:new G};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Dg,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=CT(e),this.tracer=t,console.log(`Embed: SDK: PLayer: useLazyInit = ${this.tuning.useLazyInit}`),this.tuning.useLazyInit,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ss({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new MT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new L0("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,HT.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:Wn.WTF,message:d,thrown:u}),u}}}})}createProviderContainer(e){var t,r;this.providerContainer=new Ja({sources:e.sources,meta:(t=e.meta)!=null?t:{},failoverHosts:(r=e.failoverHosts)!=null?r:[],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.initProviderDebugTelemetry(),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init()}initVideo(e){var i,s;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",jt(r)),this.domContainer=BT(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.initTracerSubscription(),this.tuning.useLazyInit||this.createProviderContainer(e),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initBasicDebugTelemetry(),this.initWakeLock(),(s=this.internalsExposure)==null||s.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=()=>{this.providerContainer||this.createProviderContainer(this.config);let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ki()?(this.tracer.log("request play from hidden tab"),Sc(document,"visibilitychange").pipe(nt()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t})),this}seekPercent(e){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,t){let r=this.desiredState.volume,i=this.info.muted$.getValue(),s=t!=null?t:this.tuning.isAudioDisabled||i;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:s}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):r.startTransitionTo({volume:e,muted:s}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e,r=this.info.volume$.getValue();return this.tracer.log("setMuted",{isMuted:e,nextMuted:t,volume:r,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:r,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Gn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),nt()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",jt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}return this.setAutoQualityLimits(i),this}setPlaybackRate(e){var r;Gn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",jt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return OT(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}),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(P0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return x0(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ht(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(sl({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ve(({from:e})=>e==="stopped"),nt()).subscribe(()=>{this.initedAt=Yn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",jt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Wn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(nt()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",jt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(N(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(N(n=>n.destination),H()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(vt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(N(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>qT(u)?1:qT(l)?-1:A0(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(H()).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(H((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(H((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(H()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(H()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(H()).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(N(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(vt({hasLiveOffsetByPaused:Ht(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(n=>n.to),H(),N(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(vt({atLiveEdge:vt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:vc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(N(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),H(),FT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(N(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(vt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(N(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),H(),FT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(N(n=>n.muted),H()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(N(n=>n.volume),H()).subscribe(this.info.volume$)).add(vc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ht(e.providerOutput.endedEvent$.pipe(_T(!0)),e.providerOutput.seekedEvent$.pipe(_T(!1))).pipe(H()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(N(n=>({id:n?`No${n}`:"NoProviders",category:Wn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(nt(),N(n=>n!=null?n:Yn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(nt(),N(()=>Yn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(nt(),N(()=>Yn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new 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(ve(({to:n})=>n==="playing"),nt()).subscribe(()=>r.next(!1)));let i=0,s=Ht(e.providerOutput.isBuffering$,t,r).pipe(N(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),H());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Ht(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ht(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(N(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 NT;this.subscription.add(t),this.subscription.add(e.current$.pipe(H((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),nt()).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=Ot(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Ht(this.desiredState.videoTrack.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(N(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$))}initBasicDebugTelemetry(){Mg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(e=>$g(e)),this.events.fatalError$.subscribe(new me("fatalError")),this.events.managedError$.subscribe(new me("managedError")),this.info.currentBuffer$.subscribe(new me("buffer"))].forEach(e=>this.subscription.add(e)),Hi("codecs",jv())}initProviderDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Gn(this.providerContainer),Gn(e),[this.providerContainer.current$.subscribe(({type:r})=>Hi("provider",r)),e.duration$.subscribe(r=>Hi("duration",r)),e.availableVideoTracks$.pipe(ve(r=>!!r.length),nt()).subscribe(r=>Hi("tracks",r)),e.position$.subscribe(new me("position")),e.currentVideoTrack$.pipe(N(r=>r==null?void 0:r.quality)).subscribe(new me("quality")),e.isBuffering$.subscribe(new me("isBuffering"))].forEach(r=>this.subscription.add(r))}initTracerSubscription(){let e=UT(this.tracer.log.bind(this.tracer)),t=UT(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(H()).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(vt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ve(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),H((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ve(r=>r>0),H()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ve(r=>r>0),H()).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(vt({currentBuffer:this.info.currentBuffer$.pipe(ve(r=>r.end>0),H((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(H())}).pipe(yc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(H()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(H()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(H()).subscribe(e("canChangePlaybackSpeed"))).add(vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ve(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),yc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(H(),ve(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(H(),ve(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(H()).subscribe(e("muted"))).add(this.info.volume$.pipe(H()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(H(),ve(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ve(({throughputEstimation:r,rtt:i})=>!!r&&!!i),yc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(H(),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=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Wn.DOM,message:String(i)})})};this.subscription.add(Ht(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",jt({quality:t,availableTracks:jt(e),track:jt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as q4,Observable as U4,Subject as H4,ValueSubject as j4,VideoQuality as Q4}from"@vkontakte/videoplayer-shared/es2018";import{ValueSubject as $0}from"@vkontakte/videoplayer-shared/es2018";var jT="vk_vp_channel";var Kn=class{constructor(e){this.ownerId=e;this.channel=new BroadcastChannel(jT);this.listeners=new Map;this.other=[];this.start=performance.now();this.isBlocked=new $0(!0);this.handleMessage=e=>{let{data:t}=e,{type:r,from:i,to:s}=t;r==="register"?(!this.isBlocked.getValue()||this.tmt)&&(this.other.push(i),this.debug(`Send wait for ${i}: diff ${performance.now()-this.start}`),this.postMessage({type:"wait",from:this.ownerId,to:i})):r==="wait"&&this.tmt&&s===this.ownerId&&(this.debug(`CLEAR TIMEOUT, MUST WAIT: diff ${performance.now()-this.start}`),window.clearTimeout(this.tmt),this.tmt=0)};this.channel.onmessage=this.handleMessage,this.postMessage({type:"register",from:this.ownerId}),this.tmt=window.setTimeout(()=>{this.tmt=0},1e3)}destroy(){}postMessage(e){this.debug("postMessage",e),this.channel.postMessage(e),this.channel.onmessage}debug(e,...t){console.log(`PlayerGroupManager ${this.ownerId}: ${e}:`,...t)}};var G4=`@vkontakte/videoplayer-core@${rd}`;export{ps as ChromecastState,ro as HttpConnectionType,U4 as Observable,Se as PlaybackState,zn as Player,Kn as PlayerGroupManager,hs as PredefinedQualityLimits,G4 as SDK_VERSION,H4 as Subject,q4 as Subscription,io as Surface,rd as VERSION,j4 as ValueSubject,At as VideoFormat,Q4 as VideoQuality};
124
+ `;var Mn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new $n(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(Wy,this.gl.VERTEX_SHADER),r=this.createShader(Yy,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 jD,now as zy,Subscription as QD,filter as GD,combine as Ky,ValueSubject as tc,isNonNullable as WD}from"@vkontakte/videoplayer-shared/es2018";var rc=class{constructor(){this.isSeeked$=new tc(!1);this.isBuffering$=new tc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new QD;this.severeStallOccurred$=new tc(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(Ky({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(GD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Ky({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(jD(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=zy(),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,WD(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=zy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Xy=rc;import{combine as YD,map as zD,observeElementSize as KD,Subscription as XD,ValueSubject as ic,noop as JD}from"@vkontakte/videoplayer-shared/es2018";var Dn=class{constructor(){this.subscription=new XD;this.pipSize$=new ic(void 0);this.videoSize$=new ic(void 0);this.elementSize$=new ic(void 0);this.pictureInPictureWindowRemoveEventListener=JD}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(KD(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(YD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(zD(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var gr=class{constructor(e){this.subscription=new aC;this.videoState=new R("stopped");this.droppedFramesManager=new rn;this.stallsManager=new Xy;this.elementSizeManager=new Dn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ji;this.audioTrackSwitchHistory=new ji;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(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(i.position,i.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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"),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 eC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Mn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Oe(e.source.url),this.params=e,this.video=Se(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(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 Ln({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Ie(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Jy.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(Zy(l=>!!l.length),tT()).subscribe(l=>{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:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ac(l=>l.to.state!=="none"),_a());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(_a()),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.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Zy(eT),tT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(ac(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(Te(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Be(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ne(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:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(tC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Nl(h));let m=[];for(let b of h.representations){let g=xy(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Fl(p));let h=[];for(let m of p.representations){let b=Ey({...m,streamId:p.id});b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=Py(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i)),this.subscription.add(Cn(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,iC(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,rT.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===p.id});eT(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,g)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(_a()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Fl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(_a()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Nl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},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 o=t.playbackState.stateChangeStarted$.pipe(ac(({to:l})=>l==="ready"),_a());this.subscription.add(Cn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,sc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Cn(o,this.player.state$.stateChangeEnded$,sc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Cn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,sc(["init"])).pipe(rC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var L,j,V,_,F,A,k,Q,ee,w,T,$,q;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:B})=>B===i),o=t.currentVideoTrack$.getValue(),u=((_=(V=e.videoStream.getState())!=null?V:n&&((j=this.videoTracksMap.get(n))==null?void 0:j.stream))!=null?_:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:B})=>B===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=it(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(p,h||1/0),1),b=(F=e.audioStream.getState())!=null?F:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(A=[...this.audioStreamsMap.keys()].find(({id:B})=>B===(b==null?void 0:b.id)))!=null?A:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let B=Js(n,c,(k=this.audioStreamsMap.get(g))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(Q=B==null?void 0:B.bitrate)!=null?Q:-1/0)}if(o){let B=Js(o,c,(ee=this.audioStreamsMap.get(g))!=null?ee:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(w=B==null?void 0:B.bitrate)!=null?w:-1/0)}}let y=Ot(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),S=r?y!=null?y:n:n!=null?n:y,E=g&&ev(S,c,(T=this.audioStreamsMap.get(g))!=null?T:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=($=this.videoTracksMap.get(S))==null?void 0:$.representation,D=E&&((q=this.audioTracksMap.get(E))==null?void 0:q.representation);if(I&&D)return[I,D];if(I&&!D&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Jy.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),ye(this.video),this.tracer.end()}};var Na=class extends gr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Vn,merge as iT,filter as sC,filterChanged as nC,isNullable as nc,map as aT,ValueSubject as oc}from"@vkontakte/videoplayer-shared/es2018";var Fa=class extends gr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:r,desiredState:i,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(r.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new oc(1);s(r.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe(aT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Vn({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(aT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(Vn({position:t.position$,liveStreamStatus:this.player.liveStreamStatus$}).subscribe(({position:o,liveStreamStatus:u})=>t.isLiveEnded$.next(u!=="active"&&o===0))).add(Vn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:iT(r.playbackRateState$,new oc(1))}).pipe(sC(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||nc(l)||(e=o-l)})).add(Vn({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:iT(r.playbackRateState$,new oc(1))}).pipe(nC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||nc(o)||nc(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=wy(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(r).then(()=>{this.params.output.position$.next(e/1e3)})}};var nT=C(Qs(),1);import{assertNever as qa,assertNonNullable as sT,debounce as oC,ErrorCategory as Bn,filter as uC,isNonNullable as lC,isNullable as cC,map as On,merge as dC,Observable as pC,observableFrom as hC,Subscription as mC,videoSizeToQuality as fC}from"@vkontakte/videoplayer-shared/es2018";var Ke={};var ni=(a,e)=>new pC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ua=class{constructor(e){this.subscription=new mC;this.videoState=new R("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:qa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:qa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:qa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:qa(e)}break;default:qa(t)}};this.textTracksManager=new Oe(e.source.url),this.video=Se(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ye(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Bn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,nT.default)(import("hls.js").then(i=>{e||(Ke.Hls=i.default,Ke.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){sT(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){sT(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Bn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Ie(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(tt(this.video,e.isLooped,r)),this.subscription.add(Te(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Be(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ne(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(On(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ni(this.hls,Ke.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Bn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(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(ni(this.hls,Ke.Events.MANIFEST_PARSED).pipe(On(({levels:l})=>l.reduce((c,d)=>{var y,S;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(S=Ct((y=d.attrs.QUALITY)!=null?y:""))!=null?S:fC({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(ni(this.hls,Ke.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(ni(this.hls,Ke.Events.LEVEL_LOADING).pipe(On(({url:l})=>ie(l))),t.hostname$),s(ni(this.hls,Ke.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(Rt(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=ni(this.hls,Ke.Events.LEVEL_SWITCHED).pipe(On(({level:l})=>n(this.hls.levels[l])));o.pipe(uC(lC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Rt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(cC(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=dC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,hC(["init"])).pipe(oC(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)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bn.DOM,thrown:t}))||(this.videoState.setState("paused"),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 oT="X-Playback-Duration",uc=async a=>{var i;let e=await at(a),t=await 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(oT)?parseInt(e.headers.get(oT),10):void 0};import{assertNever as wC,combine as AC,debounce as kC,ErrorCategory as Fn,filter as LC,filterChanged as $C,isNonNullable as cT,isNullable as qn,map as dT,merge as RC,observableFrom as MC,Subscription as DC,ValueSubject as dc,VideoQuality as CC}from"@vkontakte/videoplayer-shared/es2018";var cc=C(cu(),1);import{videoSizeToQuality as bC,getExponentialDelay as gC}from"@vkontakte/videoplayer-shared/es2018";var vC=a=>{let e=null;if(a.QUALITY&&(e=Ct(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=bC({width:t,height:r})}return e!=null?e:null},SC=(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,cc.default)(l[1].split(",").map(y=>y.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=vC(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[y,S]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));y&&S&&(g={width:y,height:S})}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,cc.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}},yC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),lc=0,uT=async(a,e=a,t,r)=>{let s=await(await at(a,r)).text();lc+=1;try{let{qualityManifests:n,textTracks:o}=SC(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(lc<=t.manifestRetryMaxCount)return await yC(gC(lc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),uT(a,e,t)}return{qualityManifests:[],textTracks:[]}},_n=uT;import{isNonNullable as TC,Subscription as IC,throttle as EC,ValueSubject as lT,Subject as xC,ErrorCategory as PC}from"@vkontakte/videoplayer-shared/es2018";var Nn=class{constructor(e,t,r,i,s){this.subscription=new IC;this.abortControllers={destroy:new ce,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new lT(null);this.getCurrentTime$=new lT(null);this.error$=new xC;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(EC(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()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=await this.fetchManifestData();await this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let r=await this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}}async parseTextTracks(e,t){for(let r of e){let i=new URL(r.url,t).toString(),n=await(await at(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(TC(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([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ce;let{textTracks:e}=await this.fetchManifestData(),t=await 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}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:PC.WTF,thrown:t,message:e})}};var Ha=class{constructor(e){this.subscription=new DC;this.videoState=new R("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new dc([]);this.liveOffset=new lr;this.manifestStartTime$=new dc(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 wC(t)}};var r;this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:CC.INVARIANT,url:this.params.source.url};let t=(i,s)=>_n(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 Nn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Oe(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:Fn.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:Fn.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(ie(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new dc((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:Fn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Ie(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ne(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($C(),dT(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&&cT(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(ie(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(AC({startTime:this.manifestStartTime$.pipe(LC(cT)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(dT(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=RC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,MC(["init"])).pipe(kC(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),ye(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(qn(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=le(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),uc(n).then(c=>{var d;if(!qn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(qn(p)||!isFinite(p))&&at(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();uc(g).then(v=>{qn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Fn.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=le(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 VC,debounce as BC,ErrorCategory as pc,fromEvent as hc,isNonNullable as OC,isNullable as _C,map as pT,merge as hT,observableFrom as mT,Subscription as NC,ValueSubject as FC,VideoQuality as qC,clientChecker as UC}from"@vkontakte/videoplayer-shared/es2018";var ja=class{constructor(e){this.subscription=new NC;this.videoState=new R("stopped");this.manifests$=new FC([]);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 VC(t)}};this.textTracksManager=new Oe(e.source.url),this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:qC.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(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),_n(le(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:pc.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||!i.from)&&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:pc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ie(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(pT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var 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&&OC(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(ie(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(pT(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)),!UC.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(hT(hc(o,"addtrack"),hc(o,"removetrack"),hc(o,"change"),mT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=hT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,mT(["init"])).pipe(BC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){var s,n;let e=this.selectManifest();if(_C(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var gT=C(Br(),1),mc=C(Wr(),1),vT=C(Vt(),1);import{assertNever as HC,assertNonNullable as fT,debounce as jC,ErrorCategory as bT,isHigherOrEqual as QC,isLowerOrEqual as GC,isNonNullable as WC,merge as YC,observableFrom as zC,Subscription as KC,map as XC}from"@vkontakte/videoplayer-shared/es2018";var Qa=class{constructor(e){this.subscription=new KC;this.videoState=new R("stopped");this.trackUrls={};this.textTracksManager=new Oe;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.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);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((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 HC(e)}};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),(0,gT.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,mc.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:bT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ie(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(XC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ne(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&&WC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let 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=YC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,zC(["init"])).pipe(jC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ye(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;fT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];fT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ra(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ie(t))}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let p=Ot(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,mc.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Hi({limits:e,lowestAvailableQuality:(c=(0,vT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?GC(i,e.max):!0,u=e.min?QC(i,e.min):!0;o&&u||r(e)}};import{assertNever as yT,debounce as t0,merge as TT,observableFrom as r0,Subscription as i0,map as IT,ValueSubject as a0,ErrorCategory as bc,VideoQuality as s0}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as JC}from"@vkontakte/videoplayer-shared/es2018";var ST=["stun:videostun.mycdn.me:80"],ZC=1e3,e0=3,fc=()=>null,Un=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=fc;this.externalStopCallback=fc;this.externalErrorCallback=fc;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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:ST}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await 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})}async onPeerConnectionStream(e){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()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await 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),ZC)}normalizeOptions(e={}){let t={stunServerList:ST,maxRetryNumber:e0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ga=class{constructor(e){this.videoState=new R("stopped");this.maxSeekBackTime$=new a0(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 yT(e)}};this.subscription=new i0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Se(e.container,e.tuning),this.liveStreamClient=new Un(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ye(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:bc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};TT(this.videoState.stateChangeStarted$.pipe(IT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(IT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Ie(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Ne(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Te(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return yT(n.to)}},r)).add(TT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r0(["init"])).pipe(t0(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(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:s0.INVARIANT}),this.video.srcObject=e,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:bc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Wa=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 Ut,ErrorCategory as Hn,filter as kT,isNonNullable as LT,isNullable as h0,map as m0,merge as f0,once as b0,Subject as se,Subscription as $T,ValueSubject as M,flattenObject as RT}from"@vkontakte/videoplayer-shared/es2018";import{Observable as n0,map as ET,Subscription as o0,Subject as u0}from"@vkontakte/videoplayer-shared/es2018";var xT=a=>new n0(e=>{let t=new o0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(ET(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(ET(({type:l})=>l!==void 0)),n=new u0,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 l0,Subscription as c0,combine as d0,filter as wT,once as AT}from"@vkontakte/videoplayer-shared/es2018";function PT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as p0}from"@vkontakte/videoplayer-shared/es2018";var Ya=class Ya{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ce;this.subscriptions=new c0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(wT(s=>!!s.type),AT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){p0.isSafari&&e!=="MPEG"||this.subscriptions.add(d0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(wT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),AT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=PT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await 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:Ya.errorId,category:l0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ya.errorId} exception`,thrown:e})}};Ya.errorId="VolumeMultiplierManager";var oi=Ya;var g0={chunkDuration:5e3,maxParallelRequests:5},Ka=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new se;this.noAvailableProvidersError$=new se;this.volumeMultiplierError$=new se;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new se,fetcherError$:new se,fetcherRecoverableError$:new se,warning$:new se,willSeekEvent$:new se,soundProhibitedEvent$:new se,seekedEvent$:new se,loopedEvent$:new se,endedEvent$:new se,firstBytesEvent$:new se,loadedMetadataEvent$:new se,firstFrameEvent$:new se,canplay$:new se,isLive$:new M(void 0),isLiveEnded$:new M(null),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),severeStallOccurred$:new se,availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M(""),getCurrentTime$:new M(null)};this.subscription=new $T;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=Zv([...tS(this.params.tuning),...eS(this.params.tuning)],this.params.tuning).filter(l=>LT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,gc.default)(i,l)),...t.filter(l=>(0,gc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",RT(s)),this.screenFormatsIterator=new Wa(s);let n=[...yl(!0),...yl(!1)];this.chromecastFormatsIterator=new Wa(n.filter(l=>LT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&oi.isSupported()&&(this.volumeMultiplierManager=new oi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(h0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Hn.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 Ut(o),new Na({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Fa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ut(o),Jr||!this.params.tuning.useHlsJs?new ja({...n,source:o}):new Ua({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Ha({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Qa({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ut(o),new gv({...n,source:o,config:{...g0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Ga({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 Ut(o),new Ni({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{...e,url:r(e.url)}}return(0,DT.default)((0,MT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new $T,t=!1,r=0;return e.add(f0(this.providerOutput.error$.pipe(kT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),xT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(m0(i=>({id:`ProviderHangup:${i}`,category:Hn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(kT(({to:s})=>s==="playing"),b0()).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===Hn.NETWORK,u=i.category===Hn.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={...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",RT(n))})),e}};import{fromEvent as jn,once as v0,combine as S0,Subscription as CT,ValueSubject as vc,map as y0,filter as T0,isNonNullable as Qn,now as Ce,safeStorage as Sc}from"@vkontakte/videoplayer-shared/es2018";var I0=5e3,VT="one_video_throughput",BT="one_video_rtt",gt=window.navigator.connection,OT=()=>{let a=gt==null?void 0:gt.downlink;if(Qn(a)&&a!==10)return a*1e3},_T=()=>{let a=gt==null?void 0:gt.rtt;if(Qn(a)&&a!==3e3)return a},NT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},yc=class a{constructor(e){this.subscription=new CT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(VT)||(e.useBrowserEstimation?OT():void 0)||I0,r=(s=(i=a.load(BT))!=null?i:e.useBrowserEstimation?_T():void 0)!=null?s:0;if(this.throughput$=new vc(t),this.rtt$=new vc(r),this.rttAdjustedThroughput$=new vc(NT(t,r,e.rttPenaltyRequestSize)),this.throughput=fr.getSmoothedValue(t,-1,e),this.rtt=fr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=OT();u&&this.throughput.next(u);let l=_T();Qn(l)&&this.rtt.next(l)};gt&&"onchange"in gt&&this.subscription.add(jn(gt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Sc.set(VT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Sc.set(BT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(S0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(y0(({throughput:n,rtt:o})=>NT(n,o,e.rttPenaltyRequestSize)),T0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Ce(),i=new CT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(jn(e,"progress").pipe(v0()).subscribe(s=>{t=s.loaded,r=Ce()}));break;case 1:case 0:i.add(jn(e,"loadstart").subscribe(()=>{t=0,r=Ce()}));break}i.add(jn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ce(),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=Ce(),n=0,o=Ce(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,Ce()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ce();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=Ce()}else n+=d.byteLength;o=Ce()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ce()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ce()-o,this.concurrentDownloads.size),n=0,o=Ce());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Sc.get(e);if(Qn(t))return(r=parseInt(t,10))!=null?r:void 0}},FT=yc;import{fillWithDefault as E0,VideoQuality as Gn}from"@vkontakte/videoplayer-shared/es2018";var qT={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:Gn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Gn.Q_720P,trafficSavingLimit:Gn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Gn.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:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!0,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:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1},UT=a=>{var e;return{...E0(a,qT),configName:[...(e=a.configName)!=null?e:[],...qT.configName]}};import{assertNonNullable as Wn,combine as vt,ErrorCategory as Yn,filter as ve,filterChanged as H,fromEvent as Ic,isNonNullable as $0,isNullable as R0,Logger as M0,map as N,mapTo as GT,merge as Ht,now as zn,once as nt,Subject as G,Subscription as WT,tap as Ec,ValueSubject as P,isHigher as D0,isInvariantQuality as YT,flattenObject as jt,throttle as xc,getTraceSubscriptionMethod as zT,Tracer as C0,InternalsExposure as V0}from"@vkontakte/videoplayer-shared/es2018";import{merge as x0,map as P0,filter as HT,isNonNullable as w0}from"@vkontakte/videoplayer-shared/es2018";var Tc=({seekState:a,position$:e})=>x0(a.stateChangeEnded$.pipe(P0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),HT(w0)),e.pipe(HT(()=>a.getState().state==="none")));import{assertNonNullable as A0}from"@vkontakte/videoplayer-shared/es2018";var jT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return A0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as k0,once as L0}from"@vkontakte/videoplayer-shared/es2018";var QT=(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(k0(i=>i.length>0),L0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Kn=class{constructor(e={configName:[]},t=C0.createRootTracer(!1)){this.subscription=new WT;this.logger=new M0;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 R("stopped"),seekState:new R({state:"none"}),volume:new R({volume:1,muted:!1}),videoTrack:new R(void 0),videoStream:new R(void 0),audioStream:new R(void 0),autoVideoTrackSwitching:new R(!0),autoVideoTrackLimits:new R({}),isLooped:new R(!1),isLowLatency:new R(!1),playbackRate:new R(1),externalTextTracks:new R([]),internalTextTracks:new R([]),currentTextTrack:new R(void 0),textTrackCuesSettings:new R({}),cameraOrientation:new R({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({}),predefinedQualityLimitType$:new P("unknown"),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 G,ready$:new G,started$:new G,playing$:new G,paused$:new G,stopped$:new G,willStart$:new G,willResume$:new G,willPause$:new G,willStop$:new G,willDestruct$:new G,watchCoverageRecord$:new G,watchCoverageLive$:new G,managedError$:new G,fatalError$:new G,fetcherRecoverableError$:new G,ended$:new G,looped$:new G,seeked$:new G,willSeek$:new G,autoplaySoundProhibited$:new G,firstBytes$:new G,loadedMetadata$:new G,firstFrame$:new G,canplay$:new G,log$:new G,fetcherError$:new G,severeStallOccured$:new G};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:qg,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=UT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new gs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new FT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new V0("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,KT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Yn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",jt(r)),this.domContainer=jT(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new Ka({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],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(),(o=this.internalsExposure)==null||o.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!zi()?(this.tracer.log("request play from hidden tab"),Ic(document,"visibilitychange").pipe(nt()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t})),this}seekPercent(e){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,t){let r=this.desiredState.volume,i=this.info.muted$.getValue(),s=t!=null?t:this.tuning.isAudioDisabled||i;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:s}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):r.startTransitionTo({volume:e,muted:s}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e,r=this.info.volume$.getValue();return this.tracer.log("setMuted",{isMuted:e,nextMuted:t,volume:r,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:r,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Wn(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),nt()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",jt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}return this.setAutoQualityLimits(i),this}setPlaybackRate(e){var r;Wn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",jt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return QT(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}),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(R0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return $0(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ht(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(sl({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ve(({from:e})=>e==="stopped"),nt()).subscribe(()=>{this.initedAt=zn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",jt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Yn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(nt()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",jt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(N(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(N(n=>n.destination),H()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(vt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(N(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>YT(u)?1:YT(l)?-1:D0(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(H()).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(H((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(H((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(H()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(H()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(H()).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(N(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(Ec(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(vt({hasLiveOffsetByPaused:Ht(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(n=>n.to),H(),N(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(vt({atLiveEdge:vt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Tc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(N(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),H(),Ec(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(N(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(vt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(N(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),H(),Ec(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(N(n=>n.muted),H()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(N(n=>n.volume),H()).subscribe(this.info.volume$)).add(Tc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ht(e.providerOutput.endedEvent$.pipe(GT(!0)),e.providerOutput.seekedEvent$.pipe(GT(!1))).pipe(H()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(N(n=>({id:n?`No${n}`:"NoProviders",category:Yn.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(nt(),N(n=>n!=null?n:zn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(nt(),N(()=>zn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(nt(),N(()=>zn()-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(ve(({to:n})=>n==="playing"),nt()).subscribe(()=>r.next(!1)));let i=0,s=Ht(e.providerOutput.isBuffering$,t,r).pipe(N(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),H());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Ht(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ht(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(N(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 WT;this.subscription.add(t),this.subscription.add(e.current$.pipe(H((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),nt()).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=Ot(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Ht(this.desiredState.videoTrack.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(N(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;Wn(this.providerContainer),Wn(e),Fg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Ng(r)),this.providerContainer.current$.subscribe(({type:r})=>Ui("provider",r)),e.duration$.subscribe(r=>Ui("duration",r)),e.availableVideoTracks$.pipe(ve(r=>!!r.length),nt()).subscribe(r=>Ui("tracks",r)),this.events.fatalError$.subscribe(new fe("fatalError")),this.events.managedError$.subscribe(new fe("managedError")),e.position$.subscribe(new fe("position")),e.currentVideoTrack$.pipe(N(r=>r==null?void 0:r.quality)).subscribe(new fe("quality")),this.info.currentBuffer$.subscribe(new fe("buffer")),e.isBuffering$.subscribe(new fe("isBuffering"))].forEach(r=>this.subscription.add(r)),Ui("codecs",Jv())}initTracerSubscription(){let e=zT(this.tracer.log.bind(this.tracer)),t=zT(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(H()).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(vt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ve(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),H((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ve(r=>r>0),H()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ve(r=>r>0),H()).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(vt({currentBuffer:this.info.currentBuffer$.pipe(ve(r=>r.end>0),H((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(H())}).pipe(xc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(H()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(H()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(H()).subscribe(e("canChangePlaybackSpeed"))).add(vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ve(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),xc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(H(),ve(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(H(),ve(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(H()).subscribe(e("muted"))).add(this.info.volume$.pipe(H()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(H(),ve(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ve(({throughputEstimation:r,rtt:i})=>!!r&&!!i),xc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(H(),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=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Yn.DOM,message:String(i)})})};this.subscription.add(Ht(Ic(document,"visibilitychange"),Ic(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",jt({quality:t,availableTracks:jt(e),track:jt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as N4,Observable as F4,Subject as q4,ValueSubject as U4,VideoQuality as H4}from"@vkontakte/videoplayer-shared/es2018";var j4=`@vkontakte/videoplayer-core@${cd}`;export{cs as ChromecastState,ro as HttpConnectionType,F4 as Observable,ke as PlaybackState,Kn as Player,ds as PredefinedQualityLimits,j4 as SDK_VERSION,q4 as Subject,N4 as Subscription,io as Surface,cd as VERSION,U4 as ValueSubject,At as VideoFormat,H4 as VideoQuality};