@vkontakte/videoplayer-core 2.0.124-dev.3c5ab8e6.0 → 2.0.124-dev.da742f3e.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +4 -4
- package/es2015.esm.js +4 -4
- package/es2018.cjs.js +4 -4
- package/es2018.esm.js +4 -4
- package/esnext.cjs.js +4 -4
- package/esnext.esm.js +4 -4
- package/evergreen.esm.js +4 -4
- package/package.json +2 -2
- package/types/providers/utils/HTMLVideoElement/pool.d.ts +2 -2
- package/types/utils/tuningConfig.d.ts +1 -0
package/es2018.esm.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.124-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.124-dev.da742f3e.0
|
|
3
|
+
* Thu, 16 Jan 2025 13:37:38 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-124/doc/
|
|
5
5
|
*/
|
|
6
6
|
var CT=Object.create;var Hc=Object.defineProperty;var OT=Object.getOwnPropertyDescriptor;var VT=Object.getOwnPropertyNames;var BT=Object.getPrototypeOf,_T=Object.prototype.hasOwnProperty;var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var NT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of VT(e))!_T.call(a,i)&&i!==t&&Hc(a,i,{get:()=>e[i],enumerable:!(r=OT(e,i))||r.enumerable});return a};var V=(a,e,t)=>(t=a!=null?CT(BT(a)):{},NT(e||!a||!a.__esModule?Hc(t,"default",{value:a,enumerable:!0}):t,a));var X=f((Yn,Gc)=>{"use strict";var fi=function(a){return a&&a.Math===Math&&a};Gc.exports=fi(typeof globalThis=="object"&&globalThis)||fi(typeof window=="object"&&window)||fi(typeof self=="object"&&self)||fi(typeof global=="object"&&global)||fi(typeof Yn=="object"&&Yn)||function(){return this}()||Function("return this")()});var ue=f((m0,Qc)=>{"use strict";Qc.exports=function(a){try{return!!a()}catch(e){return!0}}});var bi=f((f0,Wc)=>{"use strict";var FT=ue();Wc.exports=!FT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var zn=f((b0,Xc)=>{"use strict";var qT=bi(),Kc=Function.prototype,Yc=Kc.apply,zc=Kc.call;Xc.exports=typeof Reflect=="object"&&Reflect.apply||(qT?zc.bind(Yc):function(){return zc.apply(Yc,arguments)})});var re=f((g0,ed)=>{"use strict";var Jc=bi(),Zc=Function.prototype,Kn=Zc.call,UT=Jc&&Zc.bind.bind(Kn,Kn);ed.exports=Jc?UT:function(a){return function(){return Kn.apply(a,arguments)}}});var Xt=f((v0,rd)=>{"use strict";var td=re(),HT=td({}.toString),jT=td("".slice);rd.exports=function(a){return jT(HT(a),8,-1)}});var Xn=f((S0,id)=>{"use strict";var GT=Xt(),QT=re();id.exports=function(a){if(GT(a)==="Function")return QT(a)}});var z=f((y0,ad)=>{"use strict";var Jn=typeof document=="object"&&document.all;ad.exports=typeof Jn=="undefined"&&Jn!==void 0?function(a){return typeof a=="function"||a===Jn}:function(a){return typeof a=="function"}});var Ae=f((T0,sd)=>{"use strict";var WT=ue();sd.exports=!WT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ke=f((I0,nd)=>{"use strict";var YT=bi(),ls=Function.prototype.call;nd.exports=YT?ls.bind(ls):function(){return ls.apply(ls,arguments)}});var Zn=f(ld=>{"use strict";var od={}.propertyIsEnumerable,ud=Object.getOwnPropertyDescriptor,zT=ud&&!od.call({1:2},1);ld.f=zT?function(e){var t=ud(this,e);return!!t&&t.enumerable}:od});var gi=f((x0,cd)=>{"use strict";cd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var pd=f((P0,dd)=>{"use strict";var KT=re(),XT=ue(),JT=Xt(),eo=Object,ZT=KT("".split);dd.exports=XT(function(){return!eo("z").propertyIsEnumerable(0)})?function(a){return JT(a)==="String"?ZT(a,""):eo(a)}:eo});var kr=f((w0,hd)=>{"use strict";hd.exports=function(a){return a==null}});var At=f((A0,md)=>{"use strict";var eI=kr(),tI=TypeError;md.exports=function(a){if(eI(a))throw new tI("Can't call method on "+a);return a}});var Jt=f((k0,fd)=>{"use strict";var rI=pd(),iI=At();fd.exports=function(a){return rI(iI(a))}});var Re=f((R0,bd)=>{"use strict";var aI=z();bd.exports=function(a){return typeof a=="object"?a!==null:aI(a)}});var Rr=f(($0,gd)=>{"use strict";gd.exports={}});var ot=f((L0,Sd)=>{"use strict";var to=Rr(),ro=X(),sI=z(),vd=function(a){return sI(a)?a:void 0};Sd.exports=function(a,e){return arguments.length<2?vd(to[a])||vd(ro[a]):to[a]&&to[a][e]||ro[a]&&ro[a][e]}});var vi=f((M0,yd)=>{"use strict";var nI=re();yd.exports=nI({}.isPrototypeOf)});var Zt=f((D0,Ed)=>{"use strict";var oI=X(),Td=oI.navigator,Id=Td&&Td.userAgent;Ed.exports=Id?String(Id):""});var ao=f((C0,Rd)=>{"use strict";var kd=X(),io=Zt(),xd=kd.process,Pd=kd.Deno,wd=xd&&xd.versions||Pd&&Pd.version,Ad=wd&&wd.v8,je,cs;Ad&&(je=Ad.split("."),cs=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!cs&&io&&(je=io.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=io.match(/Chrome\/(\d+)/),je&&(cs=+je[1])));Rd.exports=cs});var so=f((O0,Ld)=>{"use strict";var $d=ao(),uI=ue(),lI=X(),cI=lI.String;Ld.exports=!!Object.getOwnPropertySymbols&&!uI(function(){var a=Symbol("symbol detection");return!cI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&$d&&$d<41})});var no=f((V0,Md)=>{"use strict";var dI=so();Md.exports=dI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var oo=f((B0,Dd)=>{"use strict";var pI=ot(),hI=z(),mI=vi(),fI=no(),bI=Object;Dd.exports=fI?function(a){return typeof a=="symbol"}:function(a){var e=pI("Symbol");return hI(e)&&mI(e.prototype,bI(a))}});var Si=f((_0,Cd)=>{"use strict";var gI=String;Cd.exports=function(a){try{return gI(a)}catch(e){return"Object"}}});var et=f((N0,Od)=>{"use strict";var vI=z(),SI=Si(),yI=TypeError;Od.exports=function(a){if(vI(a))return a;throw new yI(SI(a)+" is not a function")}});var yi=f((F0,Vd)=>{"use strict";var TI=et(),II=kr();Vd.exports=function(a,e){var t=a[e];return II(t)?void 0:TI(t)}});var _d=f((q0,Bd)=>{"use strict";var uo=ke(),lo=z(),co=Re(),EI=TypeError;Bd.exports=function(a,e){var t,r;if(e==="string"&&lo(t=a.toString)&&!co(r=uo(t,a))||lo(t=a.valueOf)&&!co(r=uo(t,a))||e!=="string"&&lo(t=a.toString)&&!co(r=uo(t,a)))return r;throw new EI("Can't convert object to primitive value")}});var Ge=f((U0,Nd)=>{"use strict";Nd.exports=!0});var Ud=f((H0,qd)=>{"use strict";var Fd=X(),xI=Object.defineProperty;qd.exports=function(a,e){try{xI(Fd,a,{value:e,configurable:!0,writable:!0})}catch(t){Fd[a]=e}return e}});var Ti=f((j0,Gd)=>{"use strict";var PI=Ge(),wI=X(),AI=Ud(),Hd="__core-js_shared__",jd=Gd.exports=wI[Hd]||AI(Hd,{});(jd.versions||(jd.versions=[])).push({version:"3.38.0",mode:PI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var po=f((G0,Wd)=>{"use strict";var Qd=Ti();Wd.exports=function(a,e){return Qd[a]||(Qd[a]=e||{})}});var $r=f((Q0,Yd)=>{"use strict";var kI=At(),RI=Object;Yd.exports=function(a){return RI(kI(a))}});var Qe=f((W0,zd)=>{"use strict";var $I=re(),LI=$r(),MI=$I({}.hasOwnProperty);zd.exports=Object.hasOwn||function(e,t){return MI(LI(e),t)}});var ho=f((Y0,Kd)=>{"use strict";var DI=re(),CI=0,OI=Math.random(),VI=DI(1 .toString);Kd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+VI(++CI+OI,36)}});var le=f((z0,Jd)=>{"use strict";var BI=X(),_I=po(),Xd=Qe(),NI=ho(),FI=so(),qI=no(),Lr=BI.Symbol,mo=_I("wks"),UI=qI?Lr.for||Lr:Lr&&Lr.withoutSetter||NI;Jd.exports=function(a){return Xd(mo,a)||(mo[a]=FI&&Xd(Lr,a)?Lr[a]:UI("Symbol."+a)),mo[a]}});var rp=f((K0,tp)=>{"use strict";var HI=ke(),Zd=Re(),ep=oo(),jI=yi(),GI=_d(),QI=le(),WI=TypeError,YI=QI("toPrimitive");tp.exports=function(a,e){if(!Zd(a)||ep(a))return a;var t=jI(a,YI),r;if(t){if(e===void 0&&(e="default"),r=HI(t,a,e),!Zd(r)||ep(r))return r;throw new WI("Can't convert object to primitive value")}return e===void 0&&(e="number"),GI(a,e)}});var fo=f((X0,ip)=>{"use strict";var zI=rp(),KI=oo();ip.exports=function(a){var e=zI(a,"string");return KI(e)?e:e+""}});var ds=f((J0,sp)=>{"use strict";var XI=X(),ap=Re(),bo=XI.document,JI=ap(bo)&&ap(bo.createElement);sp.exports=function(a){return JI?bo.createElement(a):{}}});var go=f((Z0,np)=>{"use strict";var ZI=Ae(),eE=ue(),tE=ds();np.exports=!ZI&&!eE(function(){return Object.defineProperty(tE("div"),"a",{get:function(){return 7}}).a!==7})});var lp=f(up=>{"use strict";var rE=Ae(),iE=ke(),aE=Zn(),sE=gi(),nE=Jt(),oE=fo(),uE=Qe(),lE=go(),op=Object.getOwnPropertyDescriptor;up.f=rE?op:function(e,t){if(e=nE(e),t=oE(t),lE)try{return op(e,t)}catch(r){}if(uE(e,t))return sE(!iE(aE.f,e,t),e[t])}});var vo=f((tO,cp)=>{"use strict";var cE=ue(),dE=z(),pE=/#|\.prototype\./,Ii=function(a,e){var t=mE[hE(a)];return t===bE?!0:t===fE?!1:dE(e)?cE(e):!!e},hE=Ii.normalize=function(a){return String(a).replace(pE,".").toLowerCase()},mE=Ii.data={},fE=Ii.NATIVE="N",bE=Ii.POLYFILL="P";cp.exports=Ii});var Mr=f((rO,pp)=>{"use strict";var dp=Xn(),gE=et(),vE=bi(),SE=dp(dp.bind);pp.exports=function(a,e){return gE(a),e===void 0?a:vE?SE(a,e):function(){return a.apply(e,arguments)}}});var So=f((iO,hp)=>{"use strict";var yE=Ae(),TE=ue();hp.exports=yE&&TE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var tt=f((aO,mp)=>{"use strict";var IE=Re(),EE=String,xE=TypeError;mp.exports=function(a){if(IE(a))return a;throw new xE(EE(a)+" is not an object")}});var er=f(bp=>{"use strict";var PE=Ae(),wE=go(),AE=So(),ps=tt(),fp=fo(),kE=TypeError,yo=Object.defineProperty,RE=Object.getOwnPropertyDescriptor,To="enumerable",Io="configurable",Eo="writable";bp.f=PE?AE?function(e,t,r){if(ps(e),t=fp(t),ps(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Eo in r&&!r[Eo]){var i=RE(e,t);i&&i[Eo]&&(e[t]=r.value,r={configurable:Io in r?r[Io]:i[Io],enumerable:To in r?r[To]:i[To],writable:!1})}return yo(e,t,r)}:yo:function(e,t,r){if(ps(e),t=fp(t),ps(r),wE)try{return yo(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new kE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Dr=f((nO,gp)=>{"use strict";var $E=Ae(),LE=er(),ME=gi();gp.exports=$E?function(a,e,t){return LE.f(a,e,ME(1,t))}:function(a,e,t){return a[e]=t,a}});var ee=f((oO,Sp)=>{"use strict";var Ei=X(),DE=zn(),CE=Xn(),OE=z(),VE=lp().f,BE=vo(),Cr=Rr(),_E=Mr(),Or=Dr(),vp=Qe();Ti();var NE=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 DE(a,this,arguments)};return e.prototype=a.prototype,e};Sp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Ei:i?Ei[t]:Ei[t]&&Ei[t].prototype,o=r?Cr:Cr[t]||Or(Cr,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=BE(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&vp(n,p),m=o[p],c&&(a.dontCallGetSet?(v=VE(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=_E(h,Ei):a.wrap&&c?g=NE(h):s&&OE(h)?g=CE(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Or(g,"sham",!0),Or(o,p,g),s&&(d=t+"Prototype",vp(Cr,d)||Or(Cr,d,{}),Or(Cr[d],p,h),a.real&&u&&(l||!u[p])&&Or(u,p,h)))}});var Tp=f((uO,yp)=>{"use strict";var FE=Math.ceil,qE=Math.floor;yp.exports=Math.trunc||function(e){var t=+e;return(t>0?qE:FE)(t)}});var xi=f((lO,Ip)=>{"use strict";var UE=Tp();Ip.exports=function(a){var e=+a;return e!==e||e===0?0:UE(e)}});var xp=f((cO,Ep)=>{"use strict";var HE=xi(),jE=Math.max,GE=Math.min;Ep.exports=function(a,e){var t=HE(a);return t<0?jE(t+e,0):GE(t,e)}});var xo=f((dO,Pp)=>{"use strict";var QE=xi(),WE=Math.min;Pp.exports=function(a){var e=QE(a);return e>0?WE(e,9007199254740991):0}});var Vr=f((pO,wp)=>{"use strict";var YE=xo();wp.exports=function(a){return YE(a.length)}});var Po=f((hO,kp)=>{"use strict";var zE=Jt(),KE=xp(),XE=Vr(),Ap=function(a){return function(e,t,r){var i=zE(e),s=XE(i);if(s===0)return!a&&-1;var n=KE(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}};kp.exports={includes:Ap(!0),indexOf:Ap(!1)}});var Pi=f((mO,Rp)=>{"use strict";Rp.exports=function(){}});var $p=f(()=>{"use strict";var JE=ee(),ZE=Po().includes,ex=ue(),tx=Pi(),rx=ex(function(){return!Array(1).includes()});JE({target:"Array",proto:!0,forced:rx},{includes:function(e){return ZE(this,e,arguments.length>1?arguments[1]:void 0)}});tx("includes")});var kt=f((gO,Lp)=>{"use strict";var ix=ot();Lp.exports=ix});var Dp=f((vO,Mp)=>{"use strict";$p();var ax=kt();Mp.exports=ax("Array","includes")});var Op=f((SO,Cp)=>{"use strict";var sx=Dp();Cp.exports=sx});var We=f((yO,Vp)=>{"use strict";var nx=Op();Vp.exports=nx});var fs=f((MO,jp)=>{"use strict";var mx=po(),fx=ho(),Hp=mx("keys");jp.exports=function(a){return Hp[a]||(Hp[a]=fx(a))}});var Qp=f((DO,Gp)=>{"use strict";var bx=ue();Gp.exports=!bx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var bs=f((CO,Yp)=>{"use strict";var gx=Qe(),vx=z(),Sx=$r(),yx=fs(),Tx=Qp(),Wp=yx("IE_PROTO"),ko=Object,Ix=ko.prototype;Yp.exports=Tx?ko.getPrototypeOf:function(a){var e=Sx(a);if(gx(e,Wp))return e[Wp];var t=e.constructor;return vx(t)&&e instanceof t?t.prototype:e instanceof ko?Ix:null}});var gs=f((OO,zp)=>{"use strict";zp.exports={}});var Jp=f((VO,Xp)=>{"use strict";var Ex=re(),Ro=Qe(),xx=Jt(),Px=Po().indexOf,wx=gs(),Kp=Ex([].push);Xp.exports=function(a,e){var t=xx(a),r=0,i=[],s;for(s in t)!Ro(wx,s)&&Ro(t,s)&&Kp(i,s);for(;e.length>r;)Ro(t,s=e[r++])&&(~Px(i,s)||Kp(i,s));return i}});var $o=f((BO,Zp)=>{"use strict";Zp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Lo=f((_O,eh)=>{"use strict";var Ax=Jp(),kx=$o();eh.exports=Object.keys||function(e){return Ax(e,kx)}});var Mo=f((NO,sh)=>{"use strict";var rh=Ae(),Rx=ue(),ih=re(),$x=bs(),Lx=Lo(),Mx=Jt(),Dx=Zn().f,ah=ih(Dx),Cx=ih([].push),Ox=rh&&Rx(function(){var a=Object.create(null);return a[2]=2,!ah(a,2)}),th=function(a){return function(e){for(var t=Mx(e),r=Lx(t),i=Ox&&$x(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!rh||(i?u in t:ah(t,u)))&&Cx(o,a?[u,t[u]]:t[u]);return o}};sh.exports={entries:th(!0),values:th(!1)}});var nh=f(()=>{"use strict";var Vx=ee(),Bx=Mo().entries;Vx({target:"Object",stat:!0},{entries:function(e){return Bx(e)}})});var uh=f((UO,oh)=>{"use strict";nh();var _x=Rr();oh.exports=_x.Object.entries});var ch=f((HO,lh)=>{"use strict";var Nx=uh();lh.exports=Nx});var Br=f((jO,dh)=>{"use strict";var Fx=ch();dh.exports=Fx});var tr=f((GO,ph)=>{"use strict";ph.exports={}});var fh=f((QO,mh)=>{"use strict";var qx=X(),Ux=z(),hh=qx.WeakMap;mh.exports=Ux(hh)&&/native code/.test(String(hh))});var Vo=f((WO,vh)=>{"use strict";var Hx=fh(),gh=X(),jx=Re(),Gx=Dr(),Do=Qe(),Co=Ti(),Qx=fs(),Wx=gs(),bh="Object already initialized",Oo=gh.TypeError,Yx=gh.WeakMap,vs,wi,Ss,zx=function(a){return Ss(a)?wi(a):vs(a,{})},Kx=function(a){return function(e){var t;if(!jx(e)||(t=wi(e)).type!==a)throw new Oo("Incompatible receiver, "+a+" required");return t}};Hx||Co.state?(Ye=Co.state||(Co.state=new Yx),Ye.get=Ye.get,Ye.has=Ye.has,Ye.set=Ye.set,vs=function(a,e){if(Ye.has(a))throw new Oo(bh);return e.facade=a,Ye.set(a,e),e},wi=function(a){return Ye.get(a)||{}},Ss=function(a){return Ye.has(a)}):(rr=Qx("state"),Wx[rr]=!0,vs=function(a,e){if(Do(a,rr))throw new Oo(bh);return e.facade=a,Gx(a,rr,e),e},wi=function(a){return Do(a,rr)?a[rr]:{}},Ss=function(a){return Do(a,rr)});var Ye,rr;vh.exports={set:vs,get:wi,has:Ss,enforce:zx,getterFor:Kx}});var No=f((YO,yh)=>{"use strict";var Bo=Ae(),Xx=Qe(),Sh=Function.prototype,Jx=Bo&&Object.getOwnPropertyDescriptor,_o=Xx(Sh,"name"),Zx=_o&&function(){}.name==="something",eP=_o&&(!Bo||Bo&&Jx(Sh,"name").configurable);yh.exports={EXISTS:_o,PROPER:Zx,CONFIGURABLE:eP}});var Ih=f(Th=>{"use strict";var tP=Ae(),rP=So(),iP=er(),aP=tt(),sP=Jt(),nP=Lo();Th.f=tP&&!rP?Object.defineProperties:function(e,t){aP(e);for(var r=sP(t),i=nP(t),s=i.length,n=0,o;s>n;)iP.f(e,o=i[n++],r[o]);return e}});var Fo=f((KO,Eh)=>{"use strict";var oP=ot();Eh.exports=oP("document","documentElement")});var jo=f((XO,$h)=>{"use strict";var uP=tt(),lP=Ih(),xh=$o(),cP=gs(),dP=Fo(),pP=ds(),hP=fs(),Ph=">",wh="<",Uo="prototype",Ho="script",kh=hP("IE_PROTO"),qo=function(){},Rh=function(a){return wh+Ho+Ph+a+wh+"/"+Ho+Ph},Ah=function(a){a.write(Rh("")),a.close();var e=a.parentWindow.Object;return a=null,e},mP=function(){var a=pP("iframe"),e="java"+Ho+":",t;return a.style.display="none",dP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Rh("document.F=Object")),t.close(),t.F},ys,Ts=function(){try{ys=new ActiveXObject("htmlfile")}catch(e){}Ts=typeof document!="undefined"?document.domain&&ys?Ah(ys):mP():Ah(ys);for(var a=xh.length;a--;)delete Ts[Uo][xh[a]];return Ts()};cP[kh]=!0;$h.exports=Object.create||function(e,t){var r;return e!==null?(qo[Uo]=uP(e),r=new qo,qo[Uo]=null,r[kh]=e):r=Ts(),t===void 0?r:lP.f(r,t)}});var _r=f((JO,Lh)=>{"use strict";var fP=Dr();Lh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:fP(a,e,t),a}});var Yo=f((ZO,Ch)=>{"use strict";var bP=ue(),gP=z(),vP=Re(),SP=jo(),Mh=bs(),yP=_r(),TP=le(),IP=Ge(),Wo=TP("iterator"),Dh=!1,ut,Go,Qo;[].keys&&(Qo=[].keys(),"next"in Qo?(Go=Mh(Mh(Qo)),Go!==Object.prototype&&(ut=Go)):Dh=!0);var EP=!vP(ut)||bP(function(){var a={};return ut[Wo].call(a)!==a});EP?ut={}:IP&&(ut=SP(ut));gP(ut[Wo])||yP(ut,Wo,function(){return this});Ch.exports={IteratorPrototype:ut,BUGGY_SAFARI_ITERATORS:Dh}});var Is=f((eV,Vh)=>{"use strict";var xP=le(),PP=xP("toStringTag"),Oh={};Oh[PP]="z";Vh.exports=String(Oh)==="[object z]"});var Ai=f((tV,Bh)=>{"use strict";var wP=Is(),AP=z(),Es=Xt(),kP=le(),RP=kP("toStringTag"),$P=Object,LP=Es(function(){return arguments}())==="Arguments",MP=function(a,e){try{return a[e]}catch(t){}};Bh.exports=wP?Es:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=MP(e=$P(a),RP))=="string"?t:LP?Es(e):(r=Es(e))==="Object"&&AP(e.callee)?"Arguments":r}});var Nh=f((rV,_h)=>{"use strict";var DP=Is(),CP=Ai();_h.exports=DP?{}.toString:function(){return"[object "+CP(this)+"]"}});var ki=f((iV,qh)=>{"use strict";var OP=Is(),VP=er().f,BP=Dr(),_P=Qe(),NP=Nh(),FP=le(),Fh=FP("toStringTag");qh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(_P(i,Fh)||VP(i,Fh,{configurable:!0,value:e}),r&&!OP&&BP(i,"toString",NP))}});var Hh=f((aV,Uh)=>{"use strict";var qP=Yo().IteratorPrototype,UP=jo(),HP=gi(),jP=ki(),GP=tr(),QP=function(){return this};Uh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=UP(qP,{next:HP(+!r,t)}),jP(a,i,!1,!0),GP[i]=QP,a}});var Gh=f((sV,jh)=>{"use strict";var WP=re(),YP=et();jh.exports=function(a,e,t){try{return WP(YP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Wh=f((nV,Qh)=>{"use strict";var zP=Re();Qh.exports=function(a){return zP(a)||a===null}});var zh=f((oV,Yh)=>{"use strict";var KP=Wh(),XP=String,JP=TypeError;Yh.exports=function(a){if(KP(a))return a;throw new JP("Can't set "+XP(a)+" as a prototype")}});var zo=f((uV,Kh)=>{"use strict";var ZP=Gh(),ew=Re(),tw=At(),rw=zh();Kh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=ZP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return tw(i),rw(s),ew(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var om=f((lV,nm)=>{"use strict";var iw=ee(),aw=ke(),xs=Ge(),am=No(),sw=z(),nw=Hh(),Xh=bs(),Jh=zo(),ow=ki(),uw=Dr(),Ko=_r(),lw=le(),Zh=tr(),sm=Yo(),cw=am.PROPER,dw=am.CONFIGURABLE,em=sm.IteratorPrototype,Ps=sm.BUGGY_SAFARI_ITERATORS,Ri=lw("iterator"),tm="keys",$i="values",rm="entries",im=function(){return this};nm.exports=function(a,e,t,r,i,s,n){nw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ps&&v&&v in c)return c[v];switch(v){case tm:return function(){return new t(this,v)};case $i:return function(){return new t(this,v)};case rm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Ri]||c["@@iterator"]||i&&c[i],p=!Ps&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=Xh(h.call(new a)),m!==Object.prototype&&m.next&&(!xs&&Xh(m)!==em&&(Jh?Jh(m,em):sw(m[Ri])||Ko(m,Ri,im)),ow(m,u,!0,!0),xs&&(Zh[u]=im))),cw&&i===$i&&d&&d.name!==$i&&(!xs&&dw?uw(c,"name",$i):(l=!0,p=function(){return aw(d,this)})),i)if(b={values:o($i),keys:s?p:o(tm),entries:o(rm)},n)for(g in b)(Ps||l||!(g in c))&&Ko(c,g,b[g]);else iw({target:e,proto:!0,forced:Ps||l},b);return(!xs||n)&&c[Ri]!==p&&Ko(c,Ri,p,{name:i}),Zh[e]=p,b}});var lm=f((cV,um)=>{"use strict";um.exports=function(a,e){return{value:a,done:e}}});var Jo=f((dV,mm)=>{"use strict";var pw=Jt(),Xo=Pi(),cm=tr(),pm=Vo(),hw=er().f,mw=om(),ws=lm(),fw=Ge(),bw=Ae(),hm="Array Iterator",gw=pm.set,vw=pm.getterFor(hm);mm.exports=mw(Array,"Array",function(a,e){gw(this,{type:hm,target:pw(a),index:0,kind:e})},function(){var a=vw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ws(void 0,!0);switch(a.kind){case"keys":return ws(t,!1);case"values":return ws(e[t],!1)}return ws([t,e[t]],!1)},"values");var dm=cm.Arguments=cm.Array;Xo("keys");Xo("values");Xo("entries");if(!fw&&bw&&dm.name!=="values")try{hw(dm,"name",{value:"values"})}catch(a){}});var bm=f((pV,fm)=>{"use strict";var Sw=le(),yw=tr(),Tw=Sw("iterator"),Iw=Array.prototype;fm.exports=function(a){return a!==void 0&&(yw.Array===a||Iw[Tw]===a)}});var Zo=f((hV,vm)=>{"use strict";var Ew=Ai(),gm=yi(),xw=kr(),Pw=tr(),ww=le(),Aw=ww("iterator");vm.exports=function(a){if(!xw(a))return gm(a,Aw)||gm(a,"@@iterator")||Pw[Ew(a)]}});var ym=f((mV,Sm)=>{"use strict";var kw=ke(),Rw=et(),$w=tt(),Lw=Si(),Mw=Zo(),Dw=TypeError;Sm.exports=function(a,e){var t=arguments.length<2?Mw(a):e;if(Rw(t))return $w(kw(t,a));throw new Dw(Lw(a)+" is not iterable")}});var Em=f((fV,Im)=>{"use strict";var Cw=ke(),Tm=tt(),Ow=yi();Im.exports=function(a,e,t){var r,i;Tm(a);try{if(r=Ow(a,"return"),!r){if(e==="throw")throw t;return t}r=Cw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Tm(r),t}});var ks=f((bV,Am)=>{"use strict";var Vw=Mr(),Bw=ke(),_w=tt(),Nw=Si(),Fw=bm(),qw=Vr(),xm=vi(),Uw=ym(),Hw=Zo(),Pm=Em(),jw=TypeError,As=function(a,e){this.stopped=a,this.result=e},wm=As.prototype;Am.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=Vw(e,r),l,c,d,p,h,m,b,g=function(S){return l&&Pm(l,"normal",S),new As(!0,S)},v=function(S){return i?(_w(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=Hw(a),!c)throw new jw(Nw(a)+" is not iterable");if(Fw(c)){for(d=0,p=qw(a);p>d;d++)if(h=v(a[d]),h&&xm(wm,h))return h;return new As(!1)}l=Uw(a,c)}for(m=s?a.next:l.next;!(b=Bw(m,l)).done;){try{h=v(b.value)}catch(S){Pm(l,"throw",S)}if(typeof h=="object"&&h&&xm(wm,h))return h}return new As(!1)}});var Rm=f((gV,km)=>{"use strict";var Gw=Ae(),Qw=er(),Ww=gi();km.exports=function(a,e,t){Gw?Qw.f(a,e,Ww(0,t)):a[e]=t}});var $m=f(()=>{"use strict";var Yw=ee(),zw=ks(),Kw=Rm();Yw({target:"Object",stat:!0},{fromEntries:function(e){var t={};return zw(e,function(r,i){Kw(t,r,i)},{AS_ENTRIES:!0}),t}})});var Mm=f((yV,Lm)=>{"use strict";Jo();$m();var Xw=Rr();Lm.exports=Xw.Object.fromEntries});var Cm=f((TV,Dm)=>{"use strict";Dm.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 Vm=f(()=>{"use strict";Jo();var Jw=Cm(),Zw=X(),eA=ki(),Om=tr();for(Rs in Jw)eA(Zw[Rs],Rs),Om[Rs]=Om.Array;var Rs});var _m=f((xV,Bm)=>{"use strict";var tA=Mm();Vm();Bm.exports=tA});var eu=f((PV,Nm)=>{"use strict";var rA=_m();Nm.exports=rA});var Fm=f(()=>{"use strict"});var tu=f((kV,qm)=>{"use strict";var Li=X(),iA=Zt(),aA=Xt(),$s=function(a){return iA.slice(0,a.length)===a};qm.exports=function(){return $s("Bun/")?"BUN":$s("Cloudflare-Workers")?"CLOUDFLARE":$s("Deno/")?"DENO":$s("Node.js/")?"NODE":Li.Bun&&typeof Bun.version=="string"?"BUN":Li.Deno&&typeof Deno.version=="object"?"DENO":aA(Li.process)==="process"?"NODE":Li.window&&Li.document?"BROWSER":"REST"}()});var Ls=f((RV,Um)=>{"use strict";var sA=tu();Um.exports=sA==="NODE"});var jm=f(($V,Hm)=>{"use strict";var nA=er();Hm.exports=function(a,e,t){return nA.f(a,e,t)}});var Wm=f((LV,Qm)=>{"use strict";var oA=ot(),uA=jm(),lA=le(),cA=Ae(),Gm=lA("species");Qm.exports=function(a){var e=oA(a);cA&&e&&!e[Gm]&&uA(e,Gm,{configurable:!0,get:function(){return this}})}});var zm=f((MV,Ym)=>{"use strict";var dA=vi(),pA=TypeError;Ym.exports=function(a,e){if(dA(e,a))return a;throw new pA("Incorrect invocation")}});var iu=f((DV,Km)=>{"use strict";var hA=re(),mA=z(),ru=Ti(),fA=hA(Function.toString);mA(ru.inspectSource)||(ru.inspectSource=function(a){return fA(a)});Km.exports=ru.inspectSource});var su=f((CV,tf)=>{"use strict";var bA=re(),gA=ue(),Xm=z(),vA=Ai(),SA=ot(),yA=iu(),Jm=function(){},Zm=SA("Reflect","construct"),au=/^\s*(?:class|function)\b/,TA=bA(au.exec),IA=!au.test(Jm),Mi=function(e){if(!Xm(e))return!1;try{return Zm(Jm,[],e),!0}catch(t){return!1}},ef=function(e){if(!Xm(e))return!1;switch(vA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return IA||!!TA(au,yA(e))}catch(t){return!0}};ef.sham=!0;tf.exports=!Zm||gA(function(){var a;return Mi(Mi.call)||!Mi(Object)||!Mi(function(){a=!0})||a})?ef:Mi});var af=f((OV,rf)=>{"use strict";var EA=su(),xA=Si(),PA=TypeError;rf.exports=function(a){if(EA(a))return a;throw new PA(xA(a)+" is not a constructor")}});var nu=f((VV,nf)=>{"use strict";var sf=tt(),wA=af(),AA=kr(),kA=le(),RA=kA("species");nf.exports=function(a,e){var t=sf(a).constructor,r;return t===void 0||AA(r=sf(t)[RA])?e:wA(r)}});var uf=f((BV,of)=>{"use strict";var $A=re();of.exports=$A([].slice)});var cf=f((_V,lf)=>{"use strict";var LA=TypeError;lf.exports=function(a,e){if(a<e)throw new LA("Not enough arguments");return a}});var ou=f((NV,df)=>{"use strict";var MA=Zt();df.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(MA)});var bu=f((FV,yf)=>{"use strict";var $e=X(),DA=zn(),CA=Mr(),pf=z(),OA=Qe(),Sf=ue(),hf=Fo(),VA=uf(),mf=ds(),BA=cf(),_A=ou(),NA=Ls(),hu=$e.setImmediate,mu=$e.clearImmediate,FA=$e.process,uu=$e.Dispatch,qA=$e.Function,ff=$e.MessageChannel,UA=$e.String,lu=0,Di={},bf="onreadystatechange",Ci,ir,cu,du;Sf(function(){Ci=$e.location});var fu=function(a){if(OA(Di,a)){var e=Di[a];delete Di[a],e()}},pu=function(a){return function(){fu(a)}},gf=function(a){fu(a.data)},vf=function(a){$e.postMessage(UA(a),Ci.protocol+"//"+Ci.host)};(!hu||!mu)&&(hu=function(e){BA(arguments.length,1);var t=pf(e)?e:qA(e),r=VA(arguments,1);return Di[++lu]=function(){DA(t,void 0,r)},ir(lu),lu},mu=function(e){delete Di[e]},NA?ir=function(a){FA.nextTick(pu(a))}:uu&&uu.now?ir=function(a){uu.now(pu(a))}:ff&&!_A?(cu=new ff,du=cu.port2,cu.port1.onmessage=gf,ir=CA(du.postMessage,du)):$e.addEventListener&&pf($e.postMessage)&&!$e.importScripts&&Ci&&Ci.protocol!=="file:"&&!Sf(vf)?(ir=vf,$e.addEventListener("message",gf,!1)):bf in mf("script")?ir=function(a){hf.appendChild(mf("script"))[bf]=function(){hf.removeChild(this),fu(a)}}:ir=function(a){setTimeout(pu(a),0)});yf.exports={set:hu,clear:mu}});var Ef=f((qV,If)=>{"use strict";var Tf=X(),HA=Ae(),jA=Object.getOwnPropertyDescriptor;If.exports=function(a){if(!HA)return Tf[a];var e=jA(Tf,a);return e&&e.value}});var gu=f((UV,Pf)=>{"use strict";var xf=function(){this.head=null,this.tail=null};xf.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}}};Pf.exports=xf});var Af=f((HV,wf)=>{"use strict";var GA=Zt();wf.exports=/ipad|iphone|ipod/i.test(GA)&&typeof Pebble!="undefined"});var Rf=f((jV,kf)=>{"use strict";var QA=Zt();kf.exports=/web0s(?!.*chrome)/i.test(QA)});var Vf=f((GV,Of)=>{"use strict";var Fr=X(),WA=Ef(),$f=Mr(),vu=bu().set,YA=gu(),zA=ou(),KA=Af(),XA=Rf(),Su=Ls(),Lf=Fr.MutationObserver||Fr.WebKitMutationObserver,Mf=Fr.document,Df=Fr.process,Ms=Fr.Promise,Iu=WA("queueMicrotask"),Nr,yu,Tu,Ds,Cf;Iu||(Oi=new YA,Vi=function(){var a,e;for(Su&&(a=Df.domain)&&a.exit();e=Oi.get();)try{e()}catch(t){throw Oi.head&&Nr(),t}a&&a.enter()},!zA&&!Su&&!XA&&Lf&&Mf?(yu=!0,Tu=Mf.createTextNode(""),new Lf(Vi).observe(Tu,{characterData:!0}),Nr=function(){Tu.data=yu=!yu}):!KA&&Ms&&Ms.resolve?(Ds=Ms.resolve(void 0),Ds.constructor=Ms,Cf=$f(Ds.then,Ds),Nr=function(){Cf(Vi)}):Su?Nr=function(){Df.nextTick(Vi)}:(vu=$f(vu,Fr),Nr=function(){vu(Vi)}),Iu=function(a){Oi.head||Nr(),Oi.add(a)});var Oi,Vi;Of.exports=Iu});var _f=f((QV,Bf)=>{"use strict";Bf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Cs=f((WV,Nf)=>{"use strict";Nf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ar=f((YV,Ff)=>{"use strict";var JA=X();Ff.exports=JA.Promise});var qr=f((zV,jf)=>{"use strict";var ZA=X(),Bi=ar(),ek=z(),tk=vo(),rk=iu(),ik=le(),qf=tu(),ak=Ge(),Eu=ao(),Uf=Bi&&Bi.prototype,sk=ik("species"),xu=!1,Hf=ek(ZA.PromiseRejectionEvent),nk=tk("Promise",function(){var a=rk(Bi),e=a!==String(Bi);if(!e&&Eu===66||ak&&!(Uf.catch&&Uf.finally))return!0;if(!Eu||Eu<51||!/native code/.test(a)){var t=new Bi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[sk]=r,xu=t.then(function(){})instanceof r,!xu)return!0}return!e&&(qf==="BROWSER"||qf==="DENO")&&!Hf});jf.exports={CONSTRUCTOR:nk,REJECTION_EVENT:Hf,SUBCLASSING:xu}});var Ur=f((KV,Qf)=>{"use strict";var Gf=et(),ok=TypeError,uk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new ok("Bad Promise constructor");e=r,t=i}),this.resolve=Gf(e),this.reject=Gf(t)};Qf.exports.f=function(a){return new uk(a)}});var db=f(()=>{"use strict";var lk=ee(),ck=Ge(),_s=Ls(),Rt=X(),Qr=ke(),Wf=_r(),Yf=zo(),dk=ki(),pk=Wm(),hk=et(),Bs=z(),mk=Re(),fk=zm(),bk=nu(),Zf=bu().set,Ru=Vf(),gk=_f(),vk=Cs(),Sk=gu(),eb=Vo(),Ns=ar(),$u=qr(),tb=Ur(),Fs="Promise",rb=$u.CONSTRUCTOR,yk=$u.REJECTION_EVENT,Tk=$u.SUBCLASSING,Pu=eb.getterFor(Fs),Ik=eb.set,Hr=Ns&&Ns.prototype,sr=Ns,Os=Hr,ib=Rt.TypeError,wu=Rt.document,Lu=Rt.process,Au=tb.f,Ek=Au,xk=!!(wu&&wu.createEvent&&Rt.dispatchEvent),ab="unhandledrejection",Pk="rejectionhandled",zf=0,sb=1,wk=2,Mu=1,nb=2,Vs,Kf,Ak,Xf,ob=function(a){var e;return mk(a)&&Bs(e=a.then)?e:!1},ub=function(a,e){var t=e.value,r=e.state===sb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===nb&&Rk(e),e.rejection=Mu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new ib("Promise-chain cycle")):(l=ob(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,Ru(function(){for(var t=a.reactions,r;r=t.get();)ub(r,a);a.notified=!1,e&&!a.rejection&&kk(a)}))},cb=function(a,e,t){var r,i;xk?(r=wu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Rt.dispatchEvent(r)):r={promise:e,reason:t},!yk&&(i=Rt["on"+a])?i(r):a===ab&&gk("Unhandled promise rejection",t)},kk=function(a){Qr(Zf,Rt,function(){var e=a.facade,t=a.value,r=Jf(a),i;if(r&&(i=vk(function(){_s?Lu.emit("unhandledRejection",t,e):cb(ab,e,t)}),a.rejection=_s||Jf(a)?nb:Mu,i.error))throw i.value})},Jf=function(a){return a.rejection!==Mu&&!a.parent},Rk=function(a){Qr(Zf,Rt,function(){var e=a.facade;_s?Lu.emit("rejectionHandled",e):cb(Pk,e,a.value)})},jr=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=wk,lb(a,!0))},ku=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new ib("Promise can't be resolved itself");var r=ob(e);r?Ru(function(){var i={done:!1};try{Qr(r,e,jr(ku,i,a),jr(Gr,i,a))}catch(s){Gr(i,s,a)}}):(a.value=e,a.state=sb,lb(a,!1))}catch(i){Gr({done:!1},i,a)}}};if(rb&&(sr=function(e){fk(this,Os),hk(e),Qr(Vs,this);var t=Pu(this);try{e(jr(ku,t),jr(Gr,t))}catch(r){Gr(t,r)}},Os=sr.prototype,Vs=function(e){Ik(this,{type:Fs,done:!1,notified:!1,parent:!1,reactions:new Sk,rejection:!1,state:zf,value:void 0})},Vs.prototype=Wf(Os,"then",function(e,t){var r=Pu(this),i=Au(bk(this,sr));return r.parent=!0,i.ok=Bs(e)?e:!0,i.fail=Bs(t)&&t,i.domain=_s?Lu.domain:void 0,r.state===zf?r.reactions.add(i):Ru(function(){ub(i,r)}),i.promise}),Kf=function(){var a=new Vs,e=Pu(a);this.promise=a,this.resolve=jr(ku,e),this.reject=jr(Gr,e)},tb.f=Au=function(a){return a===sr||a===Ak?new Kf(a):Ek(a)},!ck&&Bs(Ns)&&Hr!==Object.prototype)){Xf=Hr.then,Tk||Wf(Hr,"then",function(e,t){var r=this;return new sr(function(i,s){Qr(Xf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Hr.constructor}catch(a){}Yf&&Yf(Hr,Os)}lk({global:!0,constructor:!0,wrap:!0,forced:rb},{Promise:sr});dk(sr,Fs,!1,!0);pk(Fs)});var bb=f((ZV,fb)=>{"use strict";var $k=le(),hb=$k("iterator"),mb=!1;try{pb=0,Du={next:function(){return{done:!!pb++}},return:function(){mb=!0}},Du[hb]=function(){return this},Array.from(Du,function(){throw 2})}catch(a){}var pb,Du;fb.exports=function(a,e){try{if(!e&&!mb)return!1}catch(i){return!1}var t=!1;try{var r={};r[hb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Cu=f((eB,gb)=>{"use strict";var Lk=ar(),Mk=bb(),Dk=qr().CONSTRUCTOR;gb.exports=Dk||!Mk(function(a){Lk.all(a).then(void 0,function(){})})});var vb=f(()=>{"use strict";var Ck=ee(),Ok=ke(),Vk=et(),Bk=Ur(),_k=Cs(),Nk=ks(),Fk=Cu();Ck({target:"Promise",stat:!0,forced:Fk},{all:function(e){var t=this,r=Bk.f(t),i=r.resolve,s=r.reject,n=_k(function(){var o=Vk(t.resolve),u=[],l=0,c=1;Nk(e,function(d){var p=l++,h=!1;c++,Ok(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 yb=f(()=>{"use strict";var qk=ee(),Uk=Ge(),Hk=qr().CONSTRUCTOR,Vu=ar(),jk=ot(),Gk=z(),Qk=_r(),Sb=Vu&&Vu.prototype;qk({target:"Promise",proto:!0,forced:Hk,real:!0},{catch:function(a){return this.then(void 0,a)}});!Uk&&Gk(Vu)&&(Ou=jk("Promise").prototype.catch,Sb.catch!==Ou&&Qk(Sb,"catch",Ou,{unsafe:!0}));var Ou});var Tb=f(()=>{"use strict";var Wk=ee(),Yk=ke(),zk=et(),Kk=Ur(),Xk=Cs(),Jk=ks(),Zk=Cu();Wk({target:"Promise",stat:!0,forced:Zk},{race:function(e){var t=this,r=Kk.f(t),i=r.reject,s=Xk(function(){var n=zk(t.resolve);Jk(e,function(o){Yk(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Ib=f(()=>{"use strict";var eR=ee(),tR=Ur(),rR=qr().CONSTRUCTOR;eR({target:"Promise",stat:!0,forced:rR},{reject:function(e){var t=tR.f(this),r=t.reject;return r(e),t.promise}})});var Bu=f((lB,Eb)=>{"use strict";var iR=tt(),aR=Re(),sR=Ur();Eb.exports=function(a,e){if(iR(a),aR(e)&&e.constructor===a)return e;var t=sR.f(a),r=t.resolve;return r(e),t.promise}});var wb=f(()=>{"use strict";var nR=ee(),oR=ot(),xb=Ge(),uR=ar(),Pb=qr().CONSTRUCTOR,lR=Bu(),cR=oR("Promise"),dR=xb&&!Pb;nR({target:"Promise",stat:!0,forced:xb||Pb},{resolve:function(e){return lR(dR&&this===cR?uR:this,e)}})});var Ab=f(()=>{"use strict";db();vb();yb();Tb();Ib();wb()});var Lb=f(()=>{"use strict";var pR=ee(),hR=Ge(),qs=ar(),mR=ue(),Rb=ot(),$b=z(),fR=nu(),kb=Bu(),bR=_r(),Nu=qs&&qs.prototype,gR=!!qs&&mR(function(){Nu.finally.call({then:function(){}},function(){})});pR({target:"Promise",proto:!0,real:!0,forced:gR},{finally:function(a){var e=fR(this,Rb("Promise")),t=$b(a);return this.then(t?function(r){return kb(e,a()).then(function(){return r})}:a,t?function(r){return kb(e,a()).then(function(){throw r})}:a)}});!hR&&$b(qs)&&(_u=Rb("Promise").prototype.finally,Nu.finally!==_u&&bR(Nu,"finally",_u,{unsafe:!0}));var _u});var Db=f((bB,Mb)=>{"use strict";Fm();Ab();Lb();var vR=kt();Mb.exports=vR("Promise","finally")});var Ob=f((gB,Cb)=>{"use strict";var SR=Db();Cb.exports=SR});var Us=f((vB,Vb)=>{"use strict";var yR=Ob();Vb.exports=yR});var zb=f(()=>{"use strict";var CR=ee(),OR=Mo().values;CR({target:"Object",stat:!0},{values:function(e){return OR(e)}})});var Xb=f((r_,Kb)=>{"use strict";zb();var VR=Rr();Kb.exports=VR.Object.values});var Zb=f((i_,Jb)=>{"use strict";var BR=Xb();Jb.exports=BR});var Yr=f((a_,eg)=>{"use strict";var _R=Zb();eg.exports=_R});var hg=f(()=>{"use strict";var e$=ee(),t$=$r(),r$=Vr(),i$=xi(),a$=Pi();e$({target:"Array",proto:!0},{at:function(e){var t=t$(this),r=r$(t),i=i$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});a$("at")});var fg=f((M_,mg)=>{"use strict";hg();var s$=kt();mg.exports=s$("Array","at")});var gg=f((D_,bg)=>{"use strict";var n$=fg();bg.exports=n$});var Kr=f((C_,vg)=>{"use strict";var o$=gg();vg.exports=o$});var ul=f((nF,Yg)=>{"use strict";var U$=Xt();Yg.exports=Array.isArray||function(e){return U$(e)==="Array"}});var Kg=f((oF,zg)=>{"use strict";var H$=TypeError,j$=9007199254740991;zg.exports=function(a){if(a>j$)throw H$("Maximum allowed index exceeded");return a}});var Zg=f((uF,Jg)=>{"use strict";var G$=ul(),Q$=Vr(),W$=Kg(),Y$=Mr(),Xg=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?Y$(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&G$(d)?(p=Q$(d),u=Xg(a,e,d,p,u,s-1)-1):(W$(u+1),a[u]=d),u++),l++;return u};Jg.exports=Xg});var iv=f((lF,rv)=>{"use strict";var ev=ul(),z$=su(),K$=Re(),X$=le(),J$=X$("species"),tv=Array;rv.exports=function(a){var e;return ev(a)&&(e=a.constructor,z$(e)&&(e===tv||ev(e.prototype))?e=void 0:K$(e)&&(e=e[J$],e===null&&(e=void 0))),e===void 0?tv:e}});var sv=f((cF,av)=>{"use strict";var Z$=iv();av.exports=function(a,e){return new(Z$(a))(e===0?0:e)}});var nv=f(()=>{"use strict";var eL=ee(),tL=Zg(),rL=et(),iL=$r(),aL=Vr(),sL=sv();eL({target:"Array",proto:!0},{flatMap:function(e){var t=iL(this),r=aL(t),i;return rL(e),i=sL(t,0),i.length=tL(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var ov=f(()=>{"use strict";var nL=Pi();nL("flatMap")});var lv=f((fF,uv)=>{"use strict";nv();ov();var oL=kt();uv.exports=oL("Array","flatMap")});var dv=f((bF,cv)=>{"use strict";var uL=lv();cv.exports=uL});var ll=f((gF,pv)=>{"use strict";var lL=dv();pv.exports=lL});var Ji=f((AF,Mv)=>{"use strict";var gL=Ai(),vL=String;Mv.exports=function(a){if(gL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return vL(a)}});var dl=f((kF,Dv)=>{"use strict";Dv.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 Vv=f((RF,Ov)=>{"use strict";var SL=re(),yL=At(),TL=Ji(),hl=dl(),Cv=SL("".replace),IL=RegExp("^["+hl+"]+"),EL=RegExp("(^|[^"+hl+"])["+hl+"]+$"),pl=function(a){return function(e){var t=TL(yL(e));return a&1&&(t=Cv(t,IL,"")),a&2&&(t=Cv(t,EL,"$1")),t}};Ov.exports={start:pl(1),end:pl(2),trim:pl(3)}});var Fv=f(($F,Nv)=>{"use strict";var xL=No().PROPER,PL=ue(),Bv=dl(),_v="\u200B\x85\u180E";Nv.exports=function(a){return PL(function(){return!!Bv[a]()||_v[a]()!==_v||xL&&Bv[a].name!==a})}});var ml=f((LF,qv)=>{"use strict";var wL=Vv().start,AL=Fv();qv.exports=AL("trimStart")?function(){return wL(this)}:"".trimStart});var Hv=f(()=>{"use strict";var kL=ee(),Uv=ml();kL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Uv},{trimLeft:Uv})});var Gv=f(()=>{"use strict";Hv();var RL=ee(),jv=ml();RL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==jv},{trimStart:jv})});var Wv=f((VF,Qv)=>{"use strict";Gv();var $L=kt();Qv.exports=$L("String","trimLeft")});var zv=f((BF,Yv)=>{"use strict";var LL=Wv();Yv.exports=LL});var Xv=f((_F,Kv)=>{"use strict";var ML=zv();Kv.exports=ML});var hS=f(()=>{"use strict"});var mS=f(()=>{"use strict"});var bS=f((u1,fS)=>{"use strict";var tM=Re(),rM=Xt(),iM=le(),aM=iM("match");fS.exports=function(a){var e;return tM(a)&&((e=a[aM])!==void 0?!!e:rM(a)==="RegExp")}});var vS=f((l1,gS)=>{"use strict";var sM=tt();gS.exports=function(){var a=sM(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 TS=f((c1,yS)=>{"use strict";var nM=ke(),oM=Qe(),uM=vi(),lM=vS(),SS=RegExp.prototype;yS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in SS)&&!oM(a,"flags")&&uM(SS,a)?nM(lM,a):e}});var ES=f((d1,IS)=>{"use strict";var El=re(),cM=$r(),dM=Math.floor,Tl=El("".charAt),pM=El("".replace),Il=El("".slice),hM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,mM=/\$([$&'`]|\d{1,2})/g;IS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=mM;return i!==void 0&&(i=cM(i),u=hM),pM(s,u,function(l,c){var d;switch(Tl(c,0)){case"$":return"$";case"&":return a;case"`":return Il(e,0,t);case"'":return Il(e,n);case"<":d=i[Il(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=dM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Tl(c,1):r[h-1]+Tl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var wS=f(()=>{"use strict";var fM=ee(),bM=ke(),Pl=re(),xS=At(),gM=z(),vM=kr(),SM=bS(),ri=Ji(),yM=yi(),TM=TS(),IM=ES(),EM=le(),xM=Ge(),PM=EM("replace"),wM=TypeError,xl=Pl("".indexOf),AM=Pl("".replace),PS=Pl("".slice),kM=Math.max;fM({target:"String",proto:!0},{replaceAll:function(e,t){var r=xS(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!vM(e)){if(i=SM(e),i&&(s=ri(xS(TM(e))),!~xl(s,"g")))throw new wM("`.replaceAll` does not allow non-global regexes");if(n=yM(e,PM),n)return bM(n,e,r,t);if(xM&&i)return AM(ri(r),e,t)}for(o=ri(r),u=ri(e),l=gM(t),l||(t=ri(t)),c=u.length,d=kM(1,c),p=xl(o,u);p!==-1;)h=l?ri(t(u,p,o)):IM(u,o,p,[],void 0,t),b+=PS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:xl(o,u,p+d);return m<o.length&&(b+=PS(o,m)),b}})});var kS=f((m1,AS)=>{"use strict";hS();mS();wS();var RM=kt();AS.exports=RM("String","replaceAll")});var $S=f((f1,RS)=>{"use strict";var $M=kS();RS.exports=$M});var MS=f((b1,LS)=>{"use strict";var LM=$S();LS.exports=LM});var CS=f((g1,DS)=>{"use strict";var MM=xi(),DM=Ji(),CM=At(),OM=RangeError;DS.exports=function(e){var t=DM(CM(this)),r="",i=MM(e);if(i<0||i===1/0)throw new OM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var NS=f((v1,_S)=>{"use strict";var BS=re(),VM=xo(),OS=Ji(),BM=CS(),_M=At(),NM=BS(BM),FM=BS("".slice),qM=Math.ceil,VS=function(a){return function(e,t,r){var i=OS(_M(e)),s=VM(t),n=i.length,o=r===void 0?" ":OS(r),u,l;return s<=n||o===""?i:(u=s-n,l=NM(o,qM(u/o.length)),l.length>u&&(l=FM(l,0,u)),a?i+l:l+i)}};_S.exports={start:VS(!1),end:VS(!0)}});var qS=f((S1,FS)=>{"use strict";var UM=Zt();FS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(UM)});var US=f(()=>{"use strict";var HM=ee(),jM=NS().start,GM=qS();HM({target:"String",proto:!0,forced:GM},{padStart:function(e){return jM(this,e,arguments.length>1?arguments[1]:void 0)}})});var jS=f((I1,HS)=>{"use strict";US();var QM=kt();HS.exports=QM("String","padStart")});var QS=f((E1,GS)=>{"use strict";var WM=jS();GS.exports=WM});var YS=f((x1,WS)=>{"use strict";var YM=QS();WS.exports=YM});var jc="2.0.124-dev.3c5ab8e6.0";var be=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(be||{}),wt=(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))(wt||{});var us=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(us||{}),Qn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Qn||{});var Wn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Wn||{});var PT=V(We(),1);import{assertNever as Up,assertNonNullable as ox,isNonNullable as hs,ValueSubject as wo,Subject as ux,Subscription as lx,merge as cx,observableFrom as dx,fromEvent as _p,map as Np,tap as Fp,filterChanged as px,isNullable as Ao,ErrorCategory as qp}from"@vkontakte/videoplayer-shared/es2018";var Bp=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 ms=class{constructor(e){this.connection$=new wo(void 0);this.castState$=new wo("NOT_AVAILABLE");this.errorEvent$=new ux;this.realCastState$=new wo("NOT_AVAILABLE");this.subscription=new lx;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=hs((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||Bp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:qp.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){hs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ao(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ao(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(_p(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 Up(i.sessionState)}})).add(cx(_p(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Fp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Np(i=>i.castState)),dx([r.getCastState()])).pipe(px(),Np(hx),Fp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=hs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();ox(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Ao(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?hs(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:qp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},hx=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 Up(a)}};var ic=V(We(),1),sT=V(Br(),1),nT=V(eu(),1);var Qb=V(Us(),1);import{assertNever as Bb}from"@vkontakte/videoplayer-shared/es2018";var ce=(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:Bb(t)}return a},Hs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Bb(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as TR,Subject as js,merge as _b}from"@vkontakte/videoplayer-shared/es2018";var L=class{constructor(e){this.transitionStarted$=new js;this.transitionEnded$=new js;this.transitionUpdated$=new js;this.forceChanged$=new js;this.stateChangeStarted$=_b(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=_b(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||TR(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 IR}from"@vkontakte/videoplayer-shared/es2018";var Nb=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 IR(a)}};import{assertNever as Wr,assertNonNullable as nr,debounce as Fb,ErrorCategory as qb,fromEvent as or,isNonNullable as Ub,map as Hb,merge as jb,observableFrom as ER,Subject as xR,Subscription as Fu,timeout as PR,getHighestQuality as wR}from"@vkontakte/videoplayer-shared/es2018";var AR=5,kR=5,RR=500,Gb=7e3,_i=class{constructor(e){this.subscription=new Fu;this.loadMediaTimeoutSubscription=new Fu;this.videoState=new L("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:Wr(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:Wr(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:Wr(e)}break}default:Wr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Nb(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 Fu;this.subscription.add(e),this.subscription.add(jb(this.videoState.stateChangeStarted$.pipe(Hb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Hb(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 xR;e.add(i.pipe(Fb(RR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>AR)&&i.next(o),s=o})),e.add(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<kR&&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:Wr(n)}}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=jb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ER(["init"])).pipe(Fb(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];nr(c);let d=wR(Object.keys(c));nr(d);let p=c[d];nr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];nr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];nr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];nr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];nr(c),r=ce(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:qb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Wr(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 Ub(o)&&(n.metadata.title=o),Ub(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(PR(Gb).subscribe(()=>s(`timeout(${Gb})`)))});(0,Qb.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:qb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var nl=V(We(),1);import{clearVideoElement as Yb}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as $R}from"@vkontakte/videoplayer-shared/es2018";var Wb=a=>{try{a.pause(),a.playbackRate=0,$R(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as LR,Subscription as MR}from"@vkontakte/videoplayer-shared/es2018";var qu=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)}},Uu=window.WeakMap?new WeakMap:new qu,Hu=window.WeakMap?new WeakMap:new Map,DR=(a,e=20)=>{let t=0;return LR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ge=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Yb(t):(t=document.createElement("video"),a.appendChild(t)),Uu.set(t,r);let i=new MR;return i.add(DR(t,e)),Hu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ve=a=>{let e=Hu.get(a);e==null||e.unsubscribe(),Hu.delete(a);let t=Uu.get(a);Uu.delete(a),t?Yb(a):Wb(a)};var Gu=V(Yr(),1);import{assertNonNullable as Ni,isNonNullable as it,isNullable as qR,fromEvent as zr,merge as tg,observableFrom as rg,filterChanged as ig,map as Fi,Subject as ag,Subscription as UR,ValueSubject as HR,ErrorCategory as jR}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as ju,isNullable as NR,Subscription as FR}from"@vkontakte/videoplayer-shared/es2018";var Gs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=NR(i),l=new FR;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},rt=(a,e,t)=>Gs(e,()=>a.loop,r=>{ju(r)&&(a.loop=r)},{onError:t}),Se=(a,e,t,r)=>Gs(e,()=>({muted:a.muted,volume:a.volume}),i=>{ju(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Oe=(a,e,t,r)=>Gs(e,()=>a.playbackRate,i=>{ju(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),$t=Gs;var GR=a=>["__",a.language,a.label].join("|"),QR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Qu=class a{constructor(e){this.available$=new ag;this.current$=new HR(void 0);this.error$=new ag;this.subscription=new UR;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:jR.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,Gu.default)(this.internalTracks),s=>{it(s)&&this.setInternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Fi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add($t(t.externalTextTracks,()=>(0,Gu.default)(this.externalTracks),s=>{it(s)&&this.setExternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Fi(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(){Ni(this.video);let{textTracks:e}=this.video;this.subscription.add(zr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(tg(zr(e,"addtrack"),zr(e,"removetrack"),rg(["init"])).pipe(Fi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),ig((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(tg(zr(e,"change"),rg(["init"])).pipe(Fi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Fi(r=>r&&this.htmlTextTrackToITextTrack(r).id),ig()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(zr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(zr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;it(t.align)&&(i.align=t.align),it(t.position)&&(i.position=t.position),it(t.size)&&(i.size=t.size),it(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Ni(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:GR(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){Ni(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(qR(e)||!QR(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){Ni(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){Ni(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)}},Ve=Qu;var ct=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var sg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Wu=a=>{let e=sg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ng=a=>{let e=sg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Be,map as Lt,merge as ug,filterChanged as YR,isNonNullable as lg,Subject as zR,filter as cg,mapTo as dg,combine as KR,once as XR,ErrorCategory as JR,ValueSubject as pg,clientChecker as ZR}from"@vkontakte/videoplayer-shared/es2018";var WR=3,og=(a,e,t=WR)=>{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 ye=a=>{let e=y=>Be(a,y).pipe(dg(void 0)),r=ug(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Be(a,y))).pipe(Lt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),YR()),i=ug(Be(a,"progress"),Be(a,"timeupdate")).pipe(Lt(()=>og(a.buffered,a.currentTime))),s=ZR.isSafari?KR({play:e("play").pipe(XR()),playing:e("playing")}).pipe(dg(void 0)):e("playing"),n=Be(a,"volumechange").pipe(Lt(()=>({muted:a.muted,volume:a.volume}))),o=Be(a,"ratechange").pipe(Lt(()=>a.playbackRate)),u=Be(a,"error").pipe(cg(()=>!!(a.error||a.played.length)),Lt(()=>{var x;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:JR.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(x=a.error)!=null?x:void 0}})),l=Be(a,"timeupdate").pipe(Lt(()=>a.currentTime)),c=new zR,d=.3,p;l.subscribe(y=>{a.loop&&lg(p)&&lg(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(cg(()=>!a.error&&p!==a.duration)),m=Be(a,"enterpictureinpicture"),b=Be(a,"leavepictureinpicture"),g=new pg(ng(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new pg(Wu(a));return Be(a,"fullscreenchange").pipe(Lt(()=>Wu(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$:Be(a,"durationchange").pipe(Lt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as Mt}from"@vkontakte/videoplayer-shared/es2018";var Dt=a=>{switch(a){case"mobile":return Mt.Q_144P;case"lowest":return Mt.Q_240P;case"low":return Mt.Q_360P;case"sd":case"medium":return Mt.Q_480P;case"hd":case"high":return Mt.Q_720P;case"fullhd":case"full":return Mt.Q_1080P;case"quadhd":case"quad":return Mt.Q_1440P;case"ultrahd":case"ultra":return Mt.Q_2160P}};var Ct=V(Kr(),1),Pg=V(We(),1),Qs=V(Br(),1);import{isNonNullable as ie,isNullable as zu,now as wg,isHigher as Ku,isHigherOrEqual as Xu,isInvariantQuality as Ig,isLower as Eg,isLowerOrEqual as Ju,videoSizeToQuality as u$,assertNotEmptyArray as Ag,assertNonNullable as l$}from"@vkontakte/videoplayer-shared/es2018";var Yu=!1,dt={},Sg=a=>{Yu=a},yg=()=>{dt={}},Tg=a=>{a(dt)},qi=(a,e)=>{var t;Yu&&(dt.meta=(t=dt.meta)!=null?t:{},dt.meta[a]=e)},he=class{constructor(e){this.name=e}next(e){var r,i;if(!Yu)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}};var c$=new he("best_bitrate"),kg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Zu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ui=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=wg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Rg='Assertion "ABR Tracks is empty array" failed',Ws=(a,e,t,r)=>{var u;let i=[...e].sort(Zu(1)),s=[...t].sort(Zu(1)),n=s.filter(l=>ie(l.bitrate)&&ie(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Ct.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Ct.default)(s,-1);return o&&(0,Pg.default)(n,o)?o:n.length?(0,Ct.default)(n,-1):(0,Ct.default)(s,0)},xg=a=>"quality"in a,$g=(a,e,t,r)=>{var n;let i=ie((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&ie(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&wg()-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=xg(o)?"video":"audio",l=xg(o)?o.quality:o.bitrate;return e({message:`
|
|
7
|
+
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Vv=f((RF,Ov)=>{"use strict";var SL=re(),yL=At(),TL=Ji(),hl=dl(),Cv=SL("".replace),IL=RegExp("^["+hl+"]+"),EL=RegExp("(^|[^"+hl+"])["+hl+"]+$"),pl=function(a){return function(e){var t=TL(yL(e));return a&1&&(t=Cv(t,IL,"")),a&2&&(t=Cv(t,EL,"$1")),t}};Ov.exports={start:pl(1),end:pl(2),trim:pl(3)}});var Fv=f(($F,Nv)=>{"use strict";var xL=No().PROPER,PL=ue(),Bv=dl(),_v="\u200B\x85\u180E";Nv.exports=function(a){return PL(function(){return!!Bv[a]()||_v[a]()!==_v||xL&&Bv[a].name!==a})}});var ml=f((LF,qv)=>{"use strict";var wL=Vv().start,AL=Fv();qv.exports=AL("trimStart")?function(){return wL(this)}:"".trimStart});var Hv=f(()=>{"use strict";var kL=ee(),Uv=ml();kL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Uv},{trimLeft:Uv})});var Gv=f(()=>{"use strict";Hv();var RL=ee(),jv=ml();RL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==jv},{trimStart:jv})});var Wv=f((VF,Qv)=>{"use strict";Gv();var $L=kt();Qv.exports=$L("String","trimLeft")});var zv=f((BF,Yv)=>{"use strict";var LL=Wv();Yv.exports=LL});var Xv=f((_F,Kv)=>{"use strict";var ML=zv();Kv.exports=ML});var hS=f(()=>{"use strict"});var mS=f(()=>{"use strict"});var bS=f((u1,fS)=>{"use strict";var tM=Re(),rM=Xt(),iM=le(),aM=iM("match");fS.exports=function(a){var e;return tM(a)&&((e=a[aM])!==void 0?!!e:rM(a)==="RegExp")}});var vS=f((l1,gS)=>{"use strict";var sM=tt();gS.exports=function(){var a=sM(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 TS=f((c1,yS)=>{"use strict";var nM=ke(),oM=Qe(),uM=vi(),lM=vS(),SS=RegExp.prototype;yS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in SS)&&!oM(a,"flags")&&uM(SS,a)?nM(lM,a):e}});var ES=f((d1,IS)=>{"use strict";var El=re(),cM=$r(),dM=Math.floor,Tl=El("".charAt),pM=El("".replace),Il=El("".slice),hM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,mM=/\$([$&'`]|\d{1,2})/g;IS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=mM;return i!==void 0&&(i=cM(i),u=hM),pM(s,u,function(l,c){var d;switch(Tl(c,0)){case"$":return"$";case"&":return a;case"`":return Il(e,0,t);case"'":return Il(e,n);case"<":d=i[Il(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=dM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Tl(c,1):r[h-1]+Tl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var wS=f(()=>{"use strict";var fM=ee(),bM=ke(),Pl=re(),xS=At(),gM=z(),vM=kr(),SM=bS(),ri=Ji(),yM=yi(),TM=TS(),IM=ES(),EM=le(),xM=Ge(),PM=EM("replace"),wM=TypeError,xl=Pl("".indexOf),AM=Pl("".replace),PS=Pl("".slice),kM=Math.max;fM({target:"String",proto:!0},{replaceAll:function(e,t){var r=xS(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!vM(e)){if(i=SM(e),i&&(s=ri(xS(TM(e))),!~xl(s,"g")))throw new wM("`.replaceAll` does not allow non-global regexes");if(n=yM(e,PM),n)return bM(n,e,r,t);if(xM&&i)return AM(ri(r),e,t)}for(o=ri(r),u=ri(e),l=gM(t),l||(t=ri(t)),c=u.length,d=kM(1,c),p=xl(o,u);p!==-1;)h=l?ri(t(u,p,o)):IM(u,o,p,[],void 0,t),b+=PS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:xl(o,u,p+d);return m<o.length&&(b+=PS(o,m)),b}})});var kS=f((m1,AS)=>{"use strict";hS();mS();wS();var RM=kt();AS.exports=RM("String","replaceAll")});var $S=f((f1,RS)=>{"use strict";var $M=kS();RS.exports=$M});var MS=f((b1,LS)=>{"use strict";var LM=$S();LS.exports=LM});var CS=f((g1,DS)=>{"use strict";var MM=xi(),DM=Ji(),CM=At(),OM=RangeError;DS.exports=function(e){var t=DM(CM(this)),r="",i=MM(e);if(i<0||i===1/0)throw new OM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var NS=f((v1,_S)=>{"use strict";var BS=re(),VM=xo(),OS=Ji(),BM=CS(),_M=At(),NM=BS(BM),FM=BS("".slice),qM=Math.ceil,VS=function(a){return function(e,t,r){var i=OS(_M(e)),s=VM(t),n=i.length,o=r===void 0?" ":OS(r),u,l;return s<=n||o===""?i:(u=s-n,l=NM(o,qM(u/o.length)),l.length>u&&(l=FM(l,0,u)),a?i+l:l+i)}};_S.exports={start:VS(!1),end:VS(!0)}});var qS=f((S1,FS)=>{"use strict";var UM=Zt();FS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(UM)});var US=f(()=>{"use strict";var HM=ee(),jM=NS().start,GM=qS();HM({target:"String",proto:!0,forced:GM},{padStart:function(e){return jM(this,e,arguments.length>1?arguments[1]:void 0)}})});var jS=f((I1,HS)=>{"use strict";US();var QM=kt();HS.exports=QM("String","padStart")});var QS=f((E1,GS)=>{"use strict";var WM=jS();GS.exports=WM});var YS=f((x1,WS)=>{"use strict";var YM=QS();WS.exports=YM});var jc="2.0.124-dev.da742f3e.0";var be=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(be||{}),wt=(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))(wt||{});var us=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(us||{}),Qn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Qn||{});var Wn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Wn||{});var PT=V(We(),1);import{assertNever as Up,assertNonNullable as ox,isNonNullable as hs,ValueSubject as wo,Subject as ux,Subscription as lx,merge as cx,observableFrom as dx,fromEvent as _p,map as Np,tap as Fp,filterChanged as px,isNullable as Ao,ErrorCategory as qp}from"@vkontakte/videoplayer-shared/es2018";var Bp=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 ms=class{constructor(e){this.connection$=new wo(void 0);this.castState$=new wo("NOT_AVAILABLE");this.errorEvent$=new ux;this.realCastState$=new wo("NOT_AVAILABLE");this.subscription=new lx;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=hs((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||Bp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:qp.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){hs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ao(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ao(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(_p(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 Up(i.sessionState)}})).add(cx(_p(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Fp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Np(i=>i.castState)),dx([r.getCastState()])).pipe(px(),Np(hx),Fp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=hs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();ox(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Ao(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?hs(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:qp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},hx=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 Up(a)}};var ic=V(We(),1),sT=V(Br(),1),nT=V(eu(),1);var Qb=V(Us(),1);import{assertNever as Bb}from"@vkontakte/videoplayer-shared/es2018";var ce=(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:Bb(t)}return a},Hs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Bb(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as TR,Subject as js,merge as _b}from"@vkontakte/videoplayer-shared/es2018";var L=class{constructor(e){this.transitionStarted$=new js;this.transitionEnded$=new js;this.transitionUpdated$=new js;this.forceChanged$=new js;this.stateChangeStarted$=_b(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=_b(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||TR(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 IR}from"@vkontakte/videoplayer-shared/es2018";var Nb=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 IR(a)}};import{assertNever as Wr,assertNonNullable as nr,debounce as Fb,ErrorCategory as qb,fromEvent as or,isNonNullable as Ub,map as Hb,merge as jb,observableFrom as ER,Subject as xR,Subscription as Fu,timeout as PR,getHighestQuality as wR}from"@vkontakte/videoplayer-shared/es2018";var AR=5,kR=5,RR=500,Gb=7e3,_i=class{constructor(e){this.subscription=new Fu;this.loadMediaTimeoutSubscription=new Fu;this.videoState=new L("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:Wr(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:Wr(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:Wr(e)}break}default:Wr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Nb(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 Fu;this.subscription.add(e),this.subscription.add(jb(this.videoState.stateChangeStarted$.pipe(Hb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Hb(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 xR;e.add(i.pipe(Fb(RR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>AR)&&i.next(o),s=o})),e.add(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<kR&&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:Wr(n)}}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=jb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ER(["init"])).pipe(Fb(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];nr(c);let d=wR(Object.keys(c));nr(d);let p=c[d];nr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];nr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];nr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];nr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];nr(c),r=ce(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:qb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Wr(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 Ub(o)&&(n.metadata.title=o),Ub(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(PR(Gb).subscribe(()=>s(`timeout(${Gb})`)))});(0,Qb.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:qb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var nl=V(We(),1);import{clearVideoElement as Yb}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as $R}from"@vkontakte/videoplayer-shared/es2018";var Wb=a=>{try{a.pause(),a.playbackRate=0,$R(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as LR,Subscription as MR}from"@vkontakte/videoplayer-shared/es2018";var qu=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)}},Uu=window.WeakMap?new WeakMap:new qu,Hu=window.WeakMap?new WeakMap:new Map,DR=(a,e=20)=>{let t=0;return LR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ge=(a,{audioVideoSyncRate:e,useCrossOriginAnonymous:t})=>{let r=a.querySelector("video"),i=!!r;r?Yb(r):(r=document.createElement("video"),a.appendChild(r)),Uu.set(r,i);let s=new MR;return s.add(DR(r,e)),Hu.set(r,s),t&&r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},ve=a=>{let e=Hu.get(a);e==null||e.unsubscribe(),Hu.delete(a);let t=Uu.get(a);Uu.delete(a),t?Yb(a):Wb(a)};var Gu=V(Yr(),1);import{assertNonNullable as Ni,isNonNullable as it,isNullable as qR,fromEvent as zr,merge as tg,observableFrom as rg,filterChanged as ig,map as Fi,Subject as ag,Subscription as UR,ValueSubject as HR,ErrorCategory as jR}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as ju,isNullable as NR,Subscription as FR}from"@vkontakte/videoplayer-shared/es2018";var Gs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=NR(i),l=new FR;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},rt=(a,e,t)=>Gs(e,()=>a.loop,r=>{ju(r)&&(a.loop=r)},{onError:t}),Se=(a,e,t,r)=>Gs(e,()=>({muted:a.muted,volume:a.volume}),i=>{ju(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Oe=(a,e,t,r)=>Gs(e,()=>a.playbackRate,i=>{ju(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),$t=Gs;var GR=a=>["__",a.language,a.label].join("|"),QR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Qu=class a{constructor(e){this.available$=new ag;this.current$=new HR(void 0);this.error$=new ag;this.subscription=new UR;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:jR.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,Gu.default)(this.internalTracks),s=>{it(s)&&this.setInternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Fi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add($t(t.externalTextTracks,()=>(0,Gu.default)(this.externalTracks),s=>{it(s)&&this.setExternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Fi(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(){Ni(this.video);let{textTracks:e}=this.video;this.subscription.add(zr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(tg(zr(e,"addtrack"),zr(e,"removetrack"),rg(["init"])).pipe(Fi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),ig((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(tg(zr(e,"change"),rg(["init"])).pipe(Fi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Fi(r=>r&&this.htmlTextTrackToITextTrack(r).id),ig()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(zr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(zr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;it(t.align)&&(i.align=t.align),it(t.position)&&(i.position=t.position),it(t.size)&&(i.size=t.size),it(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Ni(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:GR(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){Ni(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(qR(e)||!QR(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){Ni(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){Ni(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)}},Ve=Qu;var ct=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var sg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Wu=a=>{let e=sg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ng=a=>{let e=sg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Be,map as Lt,merge as ug,filterChanged as YR,isNonNullable as lg,Subject as zR,filter as cg,mapTo as dg,combine as KR,once as XR,ErrorCategory as JR,ValueSubject as pg,clientChecker as ZR}from"@vkontakte/videoplayer-shared/es2018";var WR=3,og=(a,e,t=WR)=>{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 ye=a=>{let e=y=>Be(a,y).pipe(dg(void 0)),r=ug(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Be(a,y))).pipe(Lt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),YR()),i=ug(Be(a,"progress"),Be(a,"timeupdate")).pipe(Lt(()=>og(a.buffered,a.currentTime))),s=ZR.isSafari?KR({play:e("play").pipe(XR()),playing:e("playing")}).pipe(dg(void 0)):e("playing"),n=Be(a,"volumechange").pipe(Lt(()=>({muted:a.muted,volume:a.volume}))),o=Be(a,"ratechange").pipe(Lt(()=>a.playbackRate)),u=Be(a,"error").pipe(cg(()=>!!(a.error||a.played.length)),Lt(()=>{var x;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:JR.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(x=a.error)!=null?x:void 0}})),l=Be(a,"timeupdate").pipe(Lt(()=>a.currentTime)),c=new zR,d=.3,p;l.subscribe(y=>{a.loop&&lg(p)&&lg(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(cg(()=>!a.error&&p!==a.duration)),m=Be(a,"enterpictureinpicture"),b=Be(a,"leavepictureinpicture"),g=new pg(ng(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new pg(Wu(a));return Be(a,"fullscreenchange").pipe(Lt(()=>Wu(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$:Be(a,"durationchange").pipe(Lt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as Mt}from"@vkontakte/videoplayer-shared/es2018";var Dt=a=>{switch(a){case"mobile":return Mt.Q_144P;case"lowest":return Mt.Q_240P;case"low":return Mt.Q_360P;case"sd":case"medium":return Mt.Q_480P;case"hd":case"high":return Mt.Q_720P;case"fullhd":case"full":return Mt.Q_1080P;case"quadhd":case"quad":return Mt.Q_1440P;case"ultrahd":case"ultra":return Mt.Q_2160P}};var Ct=V(Kr(),1),Pg=V(We(),1),Qs=V(Br(),1);import{isNonNullable as ie,isNullable as zu,now as wg,isHigher as Ku,isHigherOrEqual as Xu,isInvariantQuality as Ig,isLower as Eg,isLowerOrEqual as Ju,videoSizeToQuality as u$,assertNotEmptyArray as Ag,assertNonNullable as l$}from"@vkontakte/videoplayer-shared/es2018";var Yu=!1,dt={},Sg=a=>{Yu=a},yg=()=>{dt={}},Tg=a=>{a(dt)},qi=(a,e)=>{var t;Yu&&(dt.meta=(t=dt.meta)!=null?t:{},dt.meta[a]=e)},he=class{constructor(e){this.name=e}next(e){var r,i;if(!Yu)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}};var c$=new he("best_bitrate"),kg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Zu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ui=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=wg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Rg='Assertion "ABR Tracks is empty array" failed',Ws=(a,e,t,r)=>{var u;let i=[...e].sort(Zu(1)),s=[...t].sort(Zu(1)),n=s.filter(l=>ie(l.bitrate)&&ie(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Ct.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Ct.default)(s,-1);return o&&(0,Pg.default)(n,o)?o:n.length?(0,Ct.default)(n,-1):(0,Ct.default)(s,0)},xg=a=>"quality"in a,$g=(a,e,t,r)=>{var n;let i=ie((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&ie(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&wg()-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=xg(o)?"video":"audio",l=xg(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
9
|
`}),o}return r==null||r.recordSwitch(t),t},d$=(a,e)=>Math.log(e)/Math.log(a),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 N,A,k,j,Z,w;Ag(a,Rg);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let $=r.pixelRatioLogBase,[R=0,te=0,Me=0]=r.pixelRatioLogCoefficients,gt=d$($,R*T+te)+Me;Number.isFinite(gt)&&(b*=gt)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,v=r.considerPlaybackRate&&ie(o)?o:1,S=a.filter(T=>!Ig(T.quality)).sort((T,$)=>Ku(T.quality,$.quality)?-1:1),y=(N=(0,Ct.default)(S,-1))==null?void 0:N.quality,x=(A=(0,Ct.default)(S,0))==null?void 0:A.quality,I=zu(i)||ie(i.min)&&ie(i.max)&&Eg(i.max,i.min)||ie(i.min)&&x&&Ku(i.min,x)||ie(i.max)&&y&&Eg(i.max,y),M=v*kg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),C={},O=S.filter(T=>{let $=!0;if(g)if(T.size)$=T.size.width<=g.width&&T.size.height<=g.height;else{let oe=g&&u$(g);$=oe?Ju(T.quality,oe):!0}if(!$)return C[T.quality]="FitsContainer",!1;let R=h||t;if(!(ie(R)&&isFinite(R)&&ie(T.bitrate)?R-s>=T.bitrate*M:!0))return C[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&ie(r.minBufferToSwitchUp)&&u&&!Ig(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Ku(T.quality,u.quality))return C[T.quality]="Buffer",!1;if(!!d&&Xu(T.quality,d))return C[T.quality]="DroppedFramesLimit",!1;if(!!p&&Xu(T.quality,p))return C[T.quality]="StallsLimit",!1;let F=I||(zu(i.max)||Ju(T.quality,i.max))&&(zu(i.min)||Xu(T.quality,i.min)),ne=ie(c)&&!c?Ju(T.quality,r.backgroundVideoQualityLimit):!0;return!F||!ne?(C[T.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&c$.next(O.bitrate);let B=(k=O!=null?O:(0,Ct.default)(S,-1))!=null?k:a[0];return B.quality!==((j=l==null?void 0:l.last)==null?void 0:j.quality)&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
@@ -123,4 +123,4 @@ void main(void) {
|
|
|
123
123
|
}
|
|
124
124
|
`;var xn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new In(this.params.fov,this.params.orientation),this.cameraRotationManager=new En(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Ty,this.gl.VERTEX_SHADER),r=this.createShader(Iy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as vD,now as Ey,Subscription as SD,filter as yD,combine as xy,ValueSubject as Hl,isNonNullable as TD}from"@vkontakte/videoplayer-shared/es2018";var jl=class{constructor(){this.isSeeked$=new Hl(!1);this.isBuffering$=new Hl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new SD;this.severeStallOccurred$=new Hl(!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(xy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(yD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(xy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(vD(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=Ey(),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,TD(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=Ey(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Py=jl;import{combine as ID,map as ED,observeElementSize as xD,Subscription as PD,ValueSubject as Gl,noop as wD}from"@vkontakte/videoplayer-shared/es2018";var Pn=class{constructor(){this.subscription=new PD;this.pipSize$=new Gl(void 0);this.videoSize$=new Gl(void 0);this.elementSize$=new Gl(void 0);this.pictureInPictureWindowRemoveEventListener=wD}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(xD(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(ID({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(ED(({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 vr=class{constructor(e){this.subscription=new DD;this.videoState=new L("stopped");this.droppedFramesManager=new Xs;this.stallsManager=new Py;this.elementSizeManager=new Pn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ui;this.audioTrackSwitchHistory=new Ui;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 RD(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new xn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ve(e.source.url),this.params=e,this.video=ge(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(ae(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Tn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ye(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Ql.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(wy(c=>!!c.length),ky()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Wl(c=>c.to.state!=="none"),Va());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Va()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(wy(Ay),ky()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Wl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Se(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Oe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(_e(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:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if($D(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of d.audio){h.push(Rl(m));let b=[];for(let g of m.representations){let v=ZS(g);b.push(v),this.audioTracksMap.set(v,{stream:m,representation:g})}this.audioStreamsMap.set(m,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push($l(h));let m=[];for(let b of h.representations){let g=JS({...b,streamId:h.id});g&&(m.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let m of h.representations){let b=ey(h,m);this.textTracksMap.set(b,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:Ql.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(wn(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$,MD(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Ry.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,b=[...this.videoTracksMap.keys()].find(v=>{var S;return((S=this.videoTracksMap.get(v))==null?void 0:S.representation.id)===h.id});Ay(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),m){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,v).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Va()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next($l(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Va()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Rl(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(Wl(({to:c})=>c==="ready"),Va());this.subscription.add(wn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Yl(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(wn(u,this.player.state$.stateChangeEnded$,Yl(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=wn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Yl(["init"])).pipe(LD(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var M,C,U,O,B,N,A,k,j,Z,w,T,$;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(M=e.videoTrack.getState())==null?void 0:M.id,n=[...this.videoTracksMap.keys()].find(({id:R})=>R===i),o=t.currentVideoTrack$.getValue(),u=((O=(U=e.videoStream.getState())!=null?U:n&&((C=this.videoTracksMap.get(n))==null?void 0:C.stream))!=null?O:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:R})=>R===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=at(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(B=e.audioStream.getState())!=null?B:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(N=[...this.audioStreamsMap.keys()].find(({id:R})=>R===(m==null?void 0:m.id)))!=null?N:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let R=Ws(n,c,(A=this.audioStreamsMap.get(b))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(k=R==null?void 0:R.bitrate)!=null?k:-1/0)}if(o){let R=Ws(o,c,(j=this.audioStreamsMap.get(b))!=null?j:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(Z=R==null?void 0:R.bitrate)!=null?Z:-1/0)}}let v=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:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),S=r?v!=null?v:n:n!=null?n:v,y=b&&Lg(S,c,(w=this.audioStreamsMap.get(b))!=null?w:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),x=(T=this.videoTracksMap.get(S))==null?void 0:T.representation,I=y&&(($=this.audioTracksMap.get(y))==null?void 0:$.representation);if(x&&I)return[x,I];if(x&&!I&&this.audioTracksMap.size===0)return[x,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(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:Ql.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),ve(this.video),this.tracer.end()}};var Ba=class extends vr{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 $y,interval as CD,map as Ly}from"@vkontakte/videoplayer-shared/es2018";var _a=class extends vr{constructor(e){super(e),this.liveOffset=new ct,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(Ly(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add($y({interval:CD(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($y({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Ly(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=ty(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 Dy=V(Us(),1);import{assertNever as Na,assertNonNullable as My,debounce as OD,ErrorCategory as An,filter as VD,isNonNullable as BD,isNullable as _D,map as kn,merge as ND,Observable as FD,observableFrom as qD,Subscription as UD,videoSizeToQuality as HD}from"@vkontakte/videoplayer-shared/es2018";var Xe={};var ni=(a,e)=>new FD(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Fa=class{constructor(e){this.subscription=new UD;this.videoState=new L("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:Na(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Na(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Na(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:Na(e)}break;default:Na(t)}};this.textTracksManager=new Ve(e.source.url),this.video=ge(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(ae(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),ve(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:An.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Dy.default)(import("hls.js").then(i=>{e||(Xe.Hls=i.default,Xe.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){My(Xe.Hls,"hls.js not loaded"),this.hls=new Xe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){My(Xe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:An.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=ye(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(rt(this.video,e.isLooped,r)),this.subscription.add(Se(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Oe(this.video,e.playbackRate,i.playbackRateState$,r)),s(_e(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(kn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ni(this.hls,Xe.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:An.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(ni(this.hls,Xe.Events.MANIFEST_PARSED).pipe(kn(({levels:l})=>l.reduce((c,d)=>{var S,y;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(y=Dt((S=d.attrs.QUALITY)!=null?S:""))!=null?y:HD({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,Xe.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,Xe.Events.LEVEL_LOADING).pipe(kn(({url:l})=>ae(l))),t.hostname$),s(ni(this.hls,Xe.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($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=ni(this.hls,Xe.Events.LEVEL_SWITCHED).pipe(kn(({level:l})=>n(this.hls.levels[l])));o.pipe(VD(BD)).subscribe(t.currentVideoTrack$,r),this.subscription.add($t(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(_D(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=ND(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,qD(["init"])).pipe(OD(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 Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:An.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 Cy="X-Playback-Duration",zl=async a=>{var i;let e=await ze(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(Cy)?parseInt(e.headers.get(Cy),10):void 0};import{assertNever as eC,combine as tC,debounce as rC,ErrorCategory as Ln,filter as iC,filterChanged as aC,isNonNullable as By,isNullable as Mn,map as _y,merge as sC,observableFrom as nC,Subscription as oC,ValueSubject as Jl,VideoQuality as uC}from"@vkontakte/videoplayer-shared/es2018";var Xl=V(eu(),1);import{videoSizeToQuality as jD,getExponentialDelay as GD}from"@vkontakte/videoplayer-shared/es2018";var QD=a=>{let e=null;if(a.QUALITY&&(e=Dt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=jD({width:t,height:r})}return e!=null?e:null},WD=(a,e)=>{var s,n;let t=a.split(`
|
|
125
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,Xl.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=QD(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[S,y]=d.RESOLUTION.split("x").map(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:m,size:g,fps:b})}if(c){let d=(0,Xl.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}},YD=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Kl=0,Oy=async(a,e=a,t,r)=>{let s=await(await ze(a,r)).text();Kl+=1;try{let{qualityManifests:n,textTracks:o}=WD(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Kl<=t.manifestRetryMaxCount)return await YD(GD(Kl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Oy(a,e,t)}return{qualityManifests:[],textTracks:[]}},Rn=Oy;import{isNonNullable as zD,Subscription as KD,throttle as XD,ValueSubject as Vy,Subject as JD,ErrorCategory as ZD}from"@vkontakte/videoplayer-shared/es2018";var $n=class{constructor(e,t,r,i,s){this.subscription=new KD;this.abortControllers={destroy:new de,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Vy(null);this.getCurrentTime$=new Vy(null);this.error$=new JD;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(XD(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 ze(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
|
|
126
|
-
`),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(zD(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 de;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:ZD.WTF,thrown:t,message:e})}};var qa=class{constructor(e){this.subscription=new oC;this.videoState=new L("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Jl([]);this.liveOffset=new ct;this.manifestStartTime$=new Jl(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 eC(t)}};var r;this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:uC.INVARIANT,url:this.params.source.url};let t=(i,s)=>Rn(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 Ve(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:Ln.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:Ln.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(ae(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Jl((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:Ln.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ye(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(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,r)),s(_e(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(aC(),_y(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&&By(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(ae(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(iC(By)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(_y(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=sC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,nC(["init"])).pipe(rC(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),ve(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Mn(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=ce(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),zl(n).then(c=>{var d;if(!Mn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Mn(p)||!isFinite(p))&&ze(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();zl(g).then(v=>{Mn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Te(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:Ln.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=ce(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 cC,ErrorCategory as Zl,fromEvent as ec,isNonNullable as dC,isNullable as pC,map as Ny,merge as Fy,observableFrom as qy,Subscription as hC,ValueSubject as mC,VideoQuality as fC,clientChecker as bC}from"@vkontakte/videoplayer-shared/es2018";var Ua=class{constructor(e){this.subscription=new hC;this.videoState=new L("stopped");this.manifests$=new mC([]);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 Ve(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:fC.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(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Rn(ce(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Zl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Zl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ye(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(Ny(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(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&&dC(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(ae(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(Ny(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(Fy(ec(o,"addtrack"),ec(o,"removetrack"),ec(o,"change"),qy(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Fy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,qy(["init"])).pipe(cC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ve(this.video)}prepare(){var s,n;let e=this.selectManifest();if(pC(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Te(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:Zl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Gy=V(Br(),1),Ha=V(Yr(),1);import{assertNever as gC,assertNonNullable as Uy,debounce as vC,ErrorCategory as Hy,isHigher as SC,isHigherOrEqual as yC,isInvariantQuality as jy,isLowerOrEqual as TC,isNonNullable as IC,merge as EC,observableFrom as xC,Subscription as PC,map as wC}from"@vkontakte/videoplayer-shared/es2018";var ja=class{constructor(e){this.subscription=new PC;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Ve;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?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 gC(e)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Gy.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,Ha.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:Hy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ye(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(wC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,r)),s(_e(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&&IC(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=EC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,xC(["init"])).pipe(vC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ve(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Uy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Uy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Aa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ae(t))}playIfAllowed(){Te(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:Hy.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Ha.default)(this.trackUrls).find(d=>!jy(d.track.quality)&&TC(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&yC(c.quality,u.quality)&&(t=u),!t){let d=(0,Ha.default)(this.trackUrls).filter(h=>!jy(h.track.quality)&&SC(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Ha.default)(this.trackUrls).map(l=>l.track);t=Ot(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Wy,debounce as $C,merge as Yy,observableFrom as LC,Subscription as MC,map as zy,ValueSubject as DC,ErrorCategory as rc,VideoQuality as CC}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as AC}from"@vkontakte/videoplayer-shared/es2018";var Qy=["stun:videostun.mycdn.me:80"],kC=1e3,RC=3,tc=()=>null,Dn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=tc;this.externalStopCallback=tc;this.externalErrorCallback=tc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}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:Qy}]};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:AC.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),kC)}normalizeOptions(e={}){let t={stunServerList:Qy,maxRetryNumber:RC,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 L("stopped");this.maxSeekBackTime$=new DC(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 Wy(e)}};this.subscription=new MC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ge(e.container,e.tuning),this.liveStreamClient=new Dn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:rc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Yy(this.videoState.stateChangeStarted$.pipe(zy(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(zy(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ye(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(_e(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(Se(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 Wy(n.to)}},r)).add(Yy(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,LC(["init"])).pipe($C(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(ae(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:CC.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:rc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Te(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:rc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qa=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 Ya,assertNonNullable as qt,ErrorCategory as Cn,filter as tT,isNonNullable as rT,isNullable as UC,map as HC,merge as jC,once as GC,Subject as we,Subscription as iT,ValueSubject as D,flattenObject as aT}from"@vkontakte/videoplayer-shared/es2018";import{Observable as OC,map as Ky,Subscription as VC,Subject as BC}from"@vkontakte/videoplayer-shared/es2018";var Xy=a=>new OC(e=>{let t=new VC,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(Ky(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(Ky(({type:l})=>l!==void 0)),n=new BC,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 _C,Subscription as NC,combine as FC,filter as Zy,once as eT}from"@vkontakte/videoplayer-shared/es2018";function Jy(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as qC}from"@vkontakte/videoplayer-shared/es2018";var Wa=class Wa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new de;this.subscriptions=new NC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Zy(s=>!!s.type),eT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){qC.isSafari&&e!=="MPEG"||this.subscriptions.add(FC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Zy(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),eT()).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=Jy();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:Wa.errorId,category:_C.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Wa.errorId} exception`,thrown:e})}};Wa.errorId="VolumeMultiplierManager";var oi=Wa;var QC={chunkDuration:5e3,maxParallelRequests:5},za=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new we;this.noAvailableProvidersError$=new we;this.volumeMultiplierError$=new we;this.providerOutput={position$:new D(0),duration$:new D(1/0),volume$:new D({muted:!1,volume:1}),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableVideoTracks$:new D([]),currentVideoTrack$:new D(void 0),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0),isAudioAvailable$:new D(!0),autoVideoTrackLimitingAvailable$:new D(!1),autoVideoTrackLimits$:new D(void 0),currentBuffer$:new D(void 0),isBuffering$:new D(!0),error$:new we,warning$:new we,willSeekEvent$:new we,soundProhibitedEvent$:new we,seekedEvent$:new we,loopedEvent$:new we,endedEvent$:new we,firstBytesEvent$:new we,loadedMetadataEvent$:new we,firstFrameEvent$:new we,canplay$:new we,isLive$:new D(void 0),isLowLatency$:new D(!1),canChangePlaybackSpeed$:new D(!0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),inPiP$:new D(!1),inFullscreen$:new D(!1),element$:new D(void 0),elementVisible$:new D(!0),availableSources$:new D(void 0),is3DVideo$:new D(!1),playbackState$:new D(""),getCurrentTime$:new D(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=kv([...$v(this.params.tuning),...Rv(this.params.tuning)],this.params.tuning).filter(l=>rT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,ic.default)(i,l)),...t.filter(l=>(0,ic.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",aT(s)),this.screenFormatsIterator=new Qa(s);let n=[...cl(!0),...cl(!1)];this.chromecastFormatsIterator=new Qa(n.filter(l=>rT(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(UC(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Cn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ya(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return qt(o),new Ba({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return qt(o),new _a({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return qt(o),ei||!this.params.tuning.useHlsJs?new Ua({...n,source:o}):new Fa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return qt(o),new qa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return qt(o),new ja({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return qt(o),new Qg({...n,source:o,config:{...QC,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return qt(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 Ya(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return qt(o),new _i({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 Ya(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ya(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 Ya(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,nT.default)((0,sT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new iT,t=!1,r=0;return e.add(jC(this.providerOutput.error$.pipe(tT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),Xy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(HC(i=>({id:`ProviderHangup:${i}`,category:Cn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(tT(({to:s})=>s==="playing"),GC()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Cn.NETWORK,u=i.category===Cn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...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",aT(n))})),e}};import{fromEvent as On,once as WC,combine as YC,Subscription as oT,ValueSubject as ac,map as zC,filter as KC,isNonNullable as Vn,now as Le,safeStorage as sc}from"@vkontakte/videoplayer-shared/es2018";var XC=5e3,uT="one_video_throughput",lT="one_video_rtt",ft=window.navigator.connection,cT=()=>{let a=ft==null?void 0:ft.downlink;if(Vn(a)&&a!==10)return a*1e3},dT=()=>{let a=ft==null?void 0:ft.rtt;if(Vn(a)&&a!==3e3)return a},pT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},nc=class a{constructor(e){this.subscription=new oT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(uT)||(e.useBrowserEstimation?cT():void 0)||XC,r=(s=(i=a.load(lT))!=null?i:e.useBrowserEstimation?dT():void 0)!=null?s:0;if(this.throughput$=new ac(t),this.rtt$=new ac(r),this.rttAdjustedThroughput$=new ac(pT(t,r,e.rttPenaltyRequestSize)),this.throughput=mr.getSmoothedValue(t,-1,e),this.rtt=mr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=cT();u&&this.throughput.next(u);let l=dT();Vn(l)&&this.rtt.next(l)};ft&&"onchange"in ft&&this.subscription.add(On(ft,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{sc.set(uT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{sc.set(lT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(YC({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(zC(({throughput:n,rtt:o})=>pT(n,o,e.rttPenaltyRequestSize)),KC(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=Le(),i=new oT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(On(e,"progress").pipe(WC()).subscribe(s=>{t=s.loaded,r=Le()}));break;case 1:case 0:i.add(On(e,"loadstart").subscribe(()=>{t=0,r=Le()}));break}i.add(On(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Le(),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=Le(),n=0,o=Le(),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,Le()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Le();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=Le()}else n+=d.byteLength;o=Le()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Le()-o,this.concurrentDownloads.size),n=0,o=Le());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(Vn(t))return(r=parseInt(t,10))!=null?r:void 0}},hT=nc;import{fillWithDefault as JC,VideoQuality as mT}from"@vkontakte/videoplayer-shared/es2018";var fT={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:mT.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:mT.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},bT=a=>{var e;return{...JC(a,fT),configName:[...(e=a.configName)!=null?e:[],...fT.configName]}};import{assertNonNullable as Bn,combine as bt,ErrorCategory as _n,filter as fe,filterChanged as q,fromEvent as uc,isNonNullable as s0,isNullable as n0,Logger as o0,map as _,mapTo as yT,merge as Ut,now as Nn,once as st,Subject as Q,Subscription as TT,tap as IT,ValueSubject as P,isHigher as u0,isInvariantQuality as ET,flattenObject as Ht,throttle as lc,getTraceSubscriptionMethod as xT,Tracer as l0,InternalsExposure as c0}from"@vkontakte/videoplayer-shared/es2018";import{merge as ZC,map as e0,filter as gT,isNonNullable as t0}from"@vkontakte/videoplayer-shared/es2018";var oc=({seekState:a,position$:e})=>ZC(a.stateChangeEnded$.pipe(e0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),gT(t0)),e.pipe(gT(()=>a.getState().state==="none")));import{assertNonNullable as r0}from"@vkontakte/videoplayer-shared/es2018";var vT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return r0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as i0,once as a0}from"@vkontakte/videoplayer-shared/es2018";var ST=(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),a0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Fn=class{constructor(e={configName:[]},t=l0.createRootTracer(!1)){this.subscription=new TT;this.logger=new o0;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 L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),isLowLatency:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),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 Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,autoplaySoundProhibited$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Tg,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=bT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ms({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new hT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new c0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(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,PT.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:_n.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",Ht(r)),this.domContainer=vT(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new za({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&&!Wi()?(this.tracer.log("request play from hidden tab"),uc(document,"visibilitychange").pipe(st()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Bn(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(fe(r=>r.length>0),st()).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",Ht(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Bn(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",Ht(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return ST(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(n0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return s0(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(Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(fe(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=Nn(),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",Ht(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:_n.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(st()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Ht(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(bt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(_(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>ET(u)?1:ET(l)?-1:u0(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(q()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(_(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(bt({hasLiveOffsetByPaused:Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(n=>n.to),q(),_(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(bt({atLiveEdge:bt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:oc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),q(),IT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(_(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(bt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(_(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),IT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),q()).subscribe(this.info.volume$)).add(oc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ut(e.providerOutput.endedEvent$.pipe(yT(!0)),e.providerOutput.seekedEvent$.pipe(yT(!1))).pipe(q()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:_n.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(st(),_(n=>n!=null?n:Nn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),_(()=>Nn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),_(()=>Nn()-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(fe(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let i=0,s=Ut(e.providerOutput.isBuffering$,t,r).pipe(_(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),q());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Ut(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(Ut(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(_(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 TT;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(fe(r=>r.length>0),st()).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(Ut(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(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;Bn(this.providerContainer),Bn(e),yg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Sg(r)),this.providerContainer.current$.subscribe(({type:r})=>qi("provider",r)),e.duration$.subscribe(r=>qi("duration",r)),e.availableVideoTracks$.pipe(fe(r=>!!r.length),st()).subscribe(r=>qi("tracks",r)),this.events.fatalError$.subscribe(new he("fatalError")),this.events.managedError$.subscribe(new he("managedError")),e.position$.subscribe(new he("position")),e.currentVideoTrack$.pipe(_(r=>r==null?void 0:r.quality)).subscribe(new he("quality")),this.info.currentBuffer$.subscribe(new he("buffer")),e.isBuffering$.subscribe(new he("isBuffering"))].forEach(r=>this.subscription.add(r)),qi("codecs",Av())}initTracerSubscription(){let e=xT(this.tracer.log.bind(this.tracer)),t=xT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(bt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(fe(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(fe(r=>r>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(fe(r=>r>0),q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(bt({currentBuffer:this.info.currentBuffer$.pipe(fe(r=>r.end>0),q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(q())}).pipe(lc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(bt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(fe(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),lc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),fe(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),fe(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),fe(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(bt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(fe(({throughputEstimation:r,rtt:i})=>!!r&&!!i),lc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),fe(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:_n.DOM,message:String(i)})})};this.subscription.add(Ut(uc(document,"visibilitychange"),uc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Ht({quality:t,availableTracks:Ht(e),track:Ht(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as jz,Observable as Gz,Subject as Qz,ValueSubject as Wz,VideoQuality as Yz}from"@vkontakte/videoplayer-shared/es2018";var zz=`@vkontakte/videoplayer-core@${jc}`;export{us as ChromecastState,Qn as HttpConnectionType,Gz as Observable,be as PlaybackState,Fn as Player,zz as SDK_VERSION,Qz as Subject,jz as Subscription,Wn as Surface,jc as VERSION,Wz as ValueSubject,wt as VideoFormat,Yz as VideoQuality};
|
|
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(zD(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 de;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:ZD.WTF,thrown:t,message:e})}};var qa=class{constructor(e){this.subscription=new oC;this.videoState=new L("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Jl([]);this.liveOffset=new ct;this.manifestStartTime$=new Jl(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 eC(t)}};var r;this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:uC.INVARIANT,url:this.params.source.url};let t=(i,s)=>Rn(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 Ve(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:Ln.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:Ln.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(ae(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Jl((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:Ln.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ye(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(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,r)),s(_e(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(aC(),_y(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&&By(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(ae(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(iC(By)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(_y(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=sC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,nC(["init"])).pipe(rC(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),ve(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Mn(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=ce(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),zl(n).then(c=>{var d;if(!Mn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Mn(p)||!isFinite(p))&&ze(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();zl(g).then(v=>{Mn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Te(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:Ln.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=ce(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 cC,ErrorCategory as Zl,fromEvent as ec,isNonNullable as dC,isNullable as pC,map as Ny,merge as Fy,observableFrom as qy,Subscription as hC,ValueSubject as mC,VideoQuality as fC,clientChecker as bC}from"@vkontakte/videoplayer-shared/es2018";var Ua=class{constructor(e){this.subscription=new hC;this.videoState=new L("stopped");this.manifests$=new mC([]);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 Ve(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:fC.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(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Rn(ce(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Zl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Zl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ye(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(Ny(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(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&&dC(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(ae(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(Ny(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(Fy(ec(o,"addtrack"),ec(o,"removetrack"),ec(o,"change"),qy(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Fy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,qy(["init"])).pipe(cC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ve(this.video)}prepare(){var s,n;let e=this.selectManifest();if(pC(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Te(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:Zl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Gy=V(Br(),1),Ha=V(Yr(),1);import{assertNever as gC,assertNonNullable as Uy,debounce as vC,ErrorCategory as Hy,isHigher as SC,isHigherOrEqual as yC,isInvariantQuality as jy,isLowerOrEqual as TC,isNonNullable as IC,merge as EC,observableFrom as xC,Subscription as PC,map as wC}from"@vkontakte/videoplayer-shared/es2018";var ja=class{constructor(e){this.subscription=new PC;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Ve;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?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 gC(e)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Gy.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,Ha.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:Hy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ye(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(wC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,r)),s(_e(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&&IC(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=EC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,xC(["init"])).pipe(vC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ve(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Uy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Uy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Aa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ae(t))}playIfAllowed(){Te(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:Hy.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Ha.default)(this.trackUrls).find(d=>!jy(d.track.quality)&&TC(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&yC(c.quality,u.quality)&&(t=u),!t){let d=(0,Ha.default)(this.trackUrls).filter(h=>!jy(h.track.quality)&&SC(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Ha.default)(this.trackUrls).map(l=>l.track);t=Ot(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Wy,debounce as $C,merge as Yy,observableFrom as LC,Subscription as MC,map as zy,ValueSubject as DC,ErrorCategory as rc,VideoQuality as CC}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as AC}from"@vkontakte/videoplayer-shared/es2018";var Qy=["stun:videostun.mycdn.me:80"],kC=1e3,RC=3,tc=()=>null,Dn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=tc;this.externalStopCallback=tc;this.externalErrorCallback=tc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}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:Qy}]};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:AC.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),kC)}normalizeOptions(e={}){let t={stunServerList:Qy,maxRetryNumber:RC,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 L("stopped");this.maxSeekBackTime$=new DC(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 Wy(e)}};this.subscription=new MC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ge(e.container,e.tuning),this.liveStreamClient=new Dn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:rc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Yy(this.videoState.stateChangeStarted$.pipe(zy(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(zy(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ye(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(_e(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(Se(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 Wy(n.to)}},r)).add(Yy(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,LC(["init"])).pipe($C(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(ae(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:CC.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:rc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Te(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:rc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qa=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 Ya,assertNonNullable as qt,ErrorCategory as Cn,filter as tT,isNonNullable as rT,isNullable as UC,map as HC,merge as jC,once as GC,Subject as we,Subscription as iT,ValueSubject as D,flattenObject as aT}from"@vkontakte/videoplayer-shared/es2018";import{Observable as OC,map as Ky,Subscription as VC,Subject as BC}from"@vkontakte/videoplayer-shared/es2018";var Xy=a=>new OC(e=>{let t=new VC,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(Ky(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(Ky(({type:l})=>l!==void 0)),n=new BC,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 _C,Subscription as NC,combine as FC,filter as Zy,once as eT}from"@vkontakte/videoplayer-shared/es2018";function Jy(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as qC}from"@vkontakte/videoplayer-shared/es2018";var Wa=class Wa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new de;this.subscriptions=new NC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Zy(s=>!!s.type),eT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){qC.isSafari&&e!=="MPEG"||this.subscriptions.add(FC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Zy(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),eT()).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=Jy();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:Wa.errorId,category:_C.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Wa.errorId} exception`,thrown:e})}};Wa.errorId="VolumeMultiplierManager";var oi=Wa;var QC={chunkDuration:5e3,maxParallelRequests:5},za=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new we;this.noAvailableProvidersError$=new we;this.volumeMultiplierError$=new we;this.providerOutput={position$:new D(0),duration$:new D(1/0),volume$:new D({muted:!1,volume:1}),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableVideoTracks$:new D([]),currentVideoTrack$:new D(void 0),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0),isAudioAvailable$:new D(!0),autoVideoTrackLimitingAvailable$:new D(!1),autoVideoTrackLimits$:new D(void 0),currentBuffer$:new D(void 0),isBuffering$:new D(!0),error$:new we,warning$:new we,willSeekEvent$:new we,soundProhibitedEvent$:new we,seekedEvent$:new we,loopedEvent$:new we,endedEvent$:new we,firstBytesEvent$:new we,loadedMetadataEvent$:new we,firstFrameEvent$:new we,canplay$:new we,isLive$:new D(void 0),isLowLatency$:new D(!1),canChangePlaybackSpeed$:new D(!0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),inPiP$:new D(!1),inFullscreen$:new D(!1),element$:new D(void 0),elementVisible$:new D(!0),availableSources$:new D(void 0),is3DVideo$:new D(!1),playbackState$:new D(""),getCurrentTime$:new D(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=kv([...$v(this.params.tuning),...Rv(this.params.tuning)],this.params.tuning).filter(l=>rT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,ic.default)(i,l)),...t.filter(l=>(0,ic.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",aT(s)),this.screenFormatsIterator=new Qa(s);let n=[...cl(!0),...cl(!1)];this.chromecastFormatsIterator=new Qa(n.filter(l=>rT(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(UC(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Cn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ya(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return qt(o),new Ba({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return qt(o),new _a({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return qt(o),ei||!this.params.tuning.useHlsJs?new Ua({...n,source:o}):new Fa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return qt(o),new qa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return qt(o),new ja({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return qt(o),new Qg({...n,source:o,config:{...QC,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return qt(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 Ya(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return qt(o),new _i({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 Ya(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ya(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 Ya(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,nT.default)((0,sT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new iT,t=!1,r=0;return e.add(jC(this.providerOutput.error$.pipe(tT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),Xy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(HC(i=>({id:`ProviderHangup:${i}`,category:Cn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(tT(({to:s})=>s==="playing"),GC()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Cn.NETWORK,u=i.category===Cn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...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",aT(n))})),e}};import{fromEvent as On,once as WC,combine as YC,Subscription as oT,ValueSubject as ac,map as zC,filter as KC,isNonNullable as Vn,now as Le,safeStorage as sc}from"@vkontakte/videoplayer-shared/es2018";var XC=5e3,uT="one_video_throughput",lT="one_video_rtt",ft=window.navigator.connection,cT=()=>{let a=ft==null?void 0:ft.downlink;if(Vn(a)&&a!==10)return a*1e3},dT=()=>{let a=ft==null?void 0:ft.rtt;if(Vn(a)&&a!==3e3)return a},pT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},nc=class a{constructor(e){this.subscription=new oT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(uT)||(e.useBrowserEstimation?cT():void 0)||XC,r=(s=(i=a.load(lT))!=null?i:e.useBrowserEstimation?dT():void 0)!=null?s:0;if(this.throughput$=new ac(t),this.rtt$=new ac(r),this.rttAdjustedThroughput$=new ac(pT(t,r,e.rttPenaltyRequestSize)),this.throughput=mr.getSmoothedValue(t,-1,e),this.rtt=mr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=cT();u&&this.throughput.next(u);let l=dT();Vn(l)&&this.rtt.next(l)};ft&&"onchange"in ft&&this.subscription.add(On(ft,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{sc.set(uT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{sc.set(lT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(YC({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(zC(({throughput:n,rtt:o})=>pT(n,o,e.rttPenaltyRequestSize)),KC(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=Le(),i=new oT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(On(e,"progress").pipe(WC()).subscribe(s=>{t=s.loaded,r=Le()}));break;case 1:case 0:i.add(On(e,"loadstart").subscribe(()=>{t=0,r=Le()}));break}i.add(On(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Le(),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=Le(),n=0,o=Le(),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,Le()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Le();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=Le()}else n+=d.byteLength;o=Le()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Le()-o,this.concurrentDownloads.size),n=0,o=Le());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(Vn(t))return(r=parseInt(t,10))!=null?r:void 0}},hT=nc;import{fillWithDefault as JC,VideoQuality as mT}from"@vkontakte/videoplayer-shared/es2018";var fT={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:mT.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:mT.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,useCrossOriginAnonymous:!1},bT=a=>{var e;return{...JC(a,fT),configName:[...(e=a.configName)!=null?e:[],...fT.configName]}};import{assertNonNullable as Bn,combine as bt,ErrorCategory as _n,filter as fe,filterChanged as q,fromEvent as uc,isNonNullable as s0,isNullable as n0,Logger as o0,map as _,mapTo as yT,merge as Ut,now as Nn,once as st,Subject as Q,Subscription as TT,tap as IT,ValueSubject as P,isHigher as u0,isInvariantQuality as ET,flattenObject as Ht,throttle as lc,getTraceSubscriptionMethod as xT,Tracer as l0,InternalsExposure as c0}from"@vkontakte/videoplayer-shared/es2018";import{merge as ZC,map as e0,filter as gT,isNonNullable as t0}from"@vkontakte/videoplayer-shared/es2018";var oc=({seekState:a,position$:e})=>ZC(a.stateChangeEnded$.pipe(e0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),gT(t0)),e.pipe(gT(()=>a.getState().state==="none")));import{assertNonNullable as r0}from"@vkontakte/videoplayer-shared/es2018";var vT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return r0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as i0,once as a0}from"@vkontakte/videoplayer-shared/es2018";var ST=(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),a0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Fn=class{constructor(e={configName:[]},t=l0.createRootTracer(!1)){this.subscription=new TT;this.logger=new o0;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 L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),isLowLatency:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),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 Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,autoplaySoundProhibited$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Tg,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=bT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ms({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new hT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new c0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(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,PT.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:_n.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",Ht(r)),this.domContainer=vT(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new za({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&&!Wi()?(this.tracer.log("request play from hidden tab"),uc(document,"visibilitychange").pipe(st()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Bn(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(fe(r=>r.length>0),st()).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",Ht(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Bn(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",Ht(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return ST(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(n0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return s0(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(Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(fe(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=Nn(),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",Ht(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:_n.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(st()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Ht(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(bt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(_(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>ET(u)?1:ET(l)?-1:u0(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(q()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(_(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(bt({hasLiveOffsetByPaused:Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(n=>n.to),q(),_(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(bt({atLiveEdge:bt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:oc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),q(),IT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(_(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(bt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(_(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),IT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),q()).subscribe(this.info.volume$)).add(oc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ut(e.providerOutput.endedEvent$.pipe(yT(!0)),e.providerOutput.seekedEvent$.pipe(yT(!1))).pipe(q()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:_n.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(st(),_(n=>n!=null?n:Nn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),_(()=>Nn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),_(()=>Nn()-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(fe(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let i=0,s=Ut(e.providerOutput.isBuffering$,t,r).pipe(_(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),q());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Ut(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(Ut(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(_(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 TT;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(fe(r=>r.length>0),st()).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(Ut(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(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;Bn(this.providerContainer),Bn(e),yg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Sg(r)),this.providerContainer.current$.subscribe(({type:r})=>qi("provider",r)),e.duration$.subscribe(r=>qi("duration",r)),e.availableVideoTracks$.pipe(fe(r=>!!r.length),st()).subscribe(r=>qi("tracks",r)),this.events.fatalError$.subscribe(new he("fatalError")),this.events.managedError$.subscribe(new he("managedError")),e.position$.subscribe(new he("position")),e.currentVideoTrack$.pipe(_(r=>r==null?void 0:r.quality)).subscribe(new he("quality")),this.info.currentBuffer$.subscribe(new he("buffer")),e.isBuffering$.subscribe(new he("isBuffering"))].forEach(r=>this.subscription.add(r)),qi("codecs",Av())}initTracerSubscription(){let e=xT(this.tracer.log.bind(this.tracer)),t=xT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(bt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(fe(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(fe(r=>r>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(fe(r=>r>0),q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(bt({currentBuffer:this.info.currentBuffer$.pipe(fe(r=>r.end>0),q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(q())}).pipe(lc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(bt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(fe(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),lc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),fe(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),fe(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),fe(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(bt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(fe(({throughputEstimation:r,rtt:i})=>!!r&&!!i),lc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),fe(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:_n.DOM,message:String(i)})})};this.subscription.add(Ut(uc(document,"visibilitychange"),uc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Ht({quality:t,availableTracks:Ht(e),track:Ht(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as jz,Observable as Gz,Subject as Qz,ValueSubject as Wz,VideoQuality as Yz}from"@vkontakte/videoplayer-shared/es2018";var zz=`@vkontakte/videoplayer-core@${jc}`;export{us as ChromecastState,Qn as HttpConnectionType,Gz as Observable,be as PlaybackState,Fn as Player,zz as SDK_VERSION,Qz as Subject,jz as Subscription,Wn as Surface,jc as VERSION,Wz as ValueSubject,wt as VideoFormat,Yz as VideoQuality};
|