@vkontakte/videoplayer-core 2.0.129-dev.085da0ee.0 → 2.0.129-dev.107d6e94.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 +3 -3
- package/es2015.esm.js +4 -4
- package/es2018.cjs.js +3 -3
- package/es2018.esm.js +4 -4
- package/esnext.cjs.js +3 -3
- package/esnext.esm.js +3 -3
- package/evergreen.esm.js +3 -3
- package/package.json +2 -2
package/es2015.esm.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.129-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.129-dev.107d6e94.0
|
|
3
|
+
* Fri, 21 Mar 2025 08:15:27 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-129/doc/
|
|
5
5
|
*/
|
|
6
6
|
var eI=Object.create;var ao=Object.defineProperty,tI=Object.defineProperties,rI=Object.getOwnPropertyDescriptor,iI=Object.getOwnPropertyDescriptors,aI=Object.getOwnPropertyNames,hs=Object.getOwnPropertySymbols,sI=Object.getPrototypeOf,so=Object.prototype.hasOwnProperty,bd=Object.prototype.propertyIsEnumerable;var nI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,fd=(a,e,t)=>e in a?ao(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,P=(a,e)=>{for(var t in e||(e={}))so.call(e,t)&&fd(a,t,e[t]);if(hs)for(var t of hs(e))bd.call(e,t)&&fd(a,t,e[t]);return a},M=(a,e)=>tI(a,iI(e));var gd=(a,e)=>{var t={};for(var r in a)so.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&hs)for(var r of hs(a))e.indexOf(r)<0&&bd.call(a,r)&&(t[r]=a[r]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var oI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of aI(e))!so.call(a,i)&&i!==t&&ao(a,i,{get:()=>e[i],enumerable:!(r=rI(e,i))||r.enumerable});return a};var B=(a,e,t)=>(t=a!=null?eI(sI(a)):{},oI(e||!a||!a.__esModule?ao(t,"default",{value:a,enumerable:!0}):t,a));var E=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),ms=function(a,e){this[0]=a,this[1]=e},ue=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof ms,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[nI("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var ne=f((uo,Sd)=>{"use strict";var gi=function(a){return a&&a.Math===Math&&a};Sd.exports=gi(typeof globalThis=="object"&&globalThis)||gi(typeof window=="object"&&window)||gi(typeof self=="object"&&self)||gi(typeof global=="object"&&global)||gi(typeof uo=="object"&&uo)||function(){return this}()||Function("return this")()});var me=f((O0,yd)=>{"use strict";yd.exports=function(a){try{return!!a()}catch(e){return!0}}});var vi=f((_0,Td)=>{"use strict";var uI=me();Td.exports=!uI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var lo=f((B0,Pd)=>{"use strict";var lI=vi(),xd=Function.prototype,Id=xd.apply,Ed=xd.call;Pd.exports=typeof Reflect=="object"&&Reflect.apply||(lI?Ed.bind(Id):function(){return Ed.apply(Id,arguments)})});var ce=f((N0,Ad)=>{"use strict";var wd=vi(),kd=Function.prototype,co=kd.call,cI=wd&&kd.bind.bind(co,co);Ad.exports=wd?cI:function(a){return function(){return co.apply(a,arguments)}}});var tr=f((F0,Rd)=>{"use strict";var $d=ce(),dI=$d({}.toString),pI=$d("".slice);Rd.exports=function(a){return pI(dI(a),8,-1)}});var po=f((q0,Ld)=>{"use strict";var hI=tr(),mI=ce();Ld.exports=function(a){if(hI(a)==="Function")return mI(a)}});var ae=f((U0,Md)=>{"use strict";var ho=typeof document=="object"&&document.all;Md.exports=typeof ho=="undefined"&&ho!==void 0?function(a){return typeof a=="function"||a===ho}:function(a){return typeof a=="function"}});var Ce=f((H0,Dd)=>{"use strict";var fI=me();Dd.exports=!fI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ve=f((j0,Cd)=>{"use strict";var bI=vi(),gs=Function.prototype.call;Cd.exports=bI?gs.bind(gs):function(){return gs.apply(gs,arguments)}});var mo=f(_d=>{"use strict";var Vd={}.propertyIsEnumerable,Od=Object.getOwnPropertyDescriptor,gI=Od&&!Vd.call({1:2},1);_d.f=gI?function(e){var t=Od(this,e);return!!t&&t.enumerable}:Vd});var Si=f((G0,Bd)=>{"use strict";Bd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Fd=f((W0,Nd)=>{"use strict";var vI=ce(),SI=me(),yI=tr(),fo=Object,TI=vI("".split);Nd.exports=SI(function(){return!fo("z").propertyIsEnumerable(0)})?function(a){return yI(a)==="String"?TI(a,""):fo(a)}:fo});var $r=f((Y0,qd)=>{"use strict";qd.exports=function(a){return a==null}});var Lt=f((z0,Ud)=>{"use strict";var II=$r(),EI=TypeError;Ud.exports=function(a){if(II(a))throw new EI("Can't call method on "+a);return a}});var rr=f((K0,Hd)=>{"use strict";var xI=Fd(),PI=Lt();Hd.exports=function(a){return xI(PI(a))}});var Oe=f((X0,jd)=>{"use strict";var wI=ae();jd.exports=function(a){return typeof a=="object"?a!==null:wI(a)}});var Rr=f((J0,Qd)=>{"use strict";Qd.exports={}});var ht=f((Z0,Wd)=>{"use strict";var bo=Rr(),go=ne(),kI=ae(),Gd=function(a){return kI(a)?a:void 0};Wd.exports=function(a,e){return arguments.length<2?Gd(bo[a])||Gd(go[a]):bo[a]&&bo[a][e]||go[a]&&go[a][e]}});var yi=f((eV,Yd)=>{"use strict";var AI=ce();Yd.exports=AI({}.isPrototypeOf)});var ir=f((tV,Xd)=>{"use strict";var $I=ne(),zd=$I.navigator,Kd=zd&&zd.userAgent;Xd.exports=Kd?String(Kd):""});var So=f((rV,ip)=>{"use strict";var rp=ne(),vo=ir(),Jd=rp.process,Zd=rp.Deno,ep=Jd&&Jd.versions||Zd&&Zd.version,tp=ep&&ep.v8,ze,vs;tp&&(ze=tp.split("."),vs=ze[0]>0&&ze[0]<4?1:+(ze[0]+ze[1]));!vs&&vo&&(ze=vo.match(/Edge\/(\d+)/),(!ze||ze[1]>=74)&&(ze=vo.match(/Chrome\/(\d+)/),ze&&(vs=+ze[1])));ip.exports=vs});var yo=f((iV,sp)=>{"use strict";var ap=So(),RI=me(),LI=ne(),MI=LI.String;sp.exports=!!Object.getOwnPropertySymbols&&!RI(function(){var a=Symbol("symbol detection");return!MI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&ap&&ap<41})});var To=f((aV,np)=>{"use strict";var DI=yo();np.exports=DI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Io=f((sV,op)=>{"use strict";var CI=ht(),VI=ae(),OI=yi(),_I=To(),BI=Object;op.exports=_I?function(a){return typeof a=="symbol"}:function(a){var e=CI("Symbol");return VI(e)&&OI(e.prototype,BI(a))}});var Ti=f((nV,up)=>{"use strict";var NI=String;up.exports=function(a){try{return NI(a)}catch(e){return"Object"}}});var st=f((oV,lp)=>{"use strict";var FI=ae(),qI=Ti(),UI=TypeError;lp.exports=function(a){if(FI(a))return a;throw new UI(qI(a)+" is not a function")}});var Ii=f((uV,cp)=>{"use strict";var HI=st(),jI=$r();cp.exports=function(a,e){var t=a[e];return jI(t)?void 0:HI(t)}});var pp=f((lV,dp)=>{"use strict";var Eo=Ve(),xo=ae(),Po=Oe(),QI=TypeError;dp.exports=function(a,e){var t,r;if(e==="string"&&xo(t=a.toString)&&!Po(r=Eo(t,a))||xo(t=a.valueOf)&&!Po(r=Eo(t,a))||e!=="string"&&xo(t=a.toString)&&!Po(r=Eo(t,a)))return r;throw new QI("Can't convert object to primitive value")}});var Ke=f((cV,hp)=>{"use strict";hp.exports=!0});var bp=f((dV,fp)=>{"use strict";var mp=ne(),GI=Object.defineProperty;fp.exports=function(a,e){try{GI(mp,a,{value:e,configurable:!0,writable:!0})}catch(t){mp[a]=e}return e}});var Ei=f((pV,Sp)=>{"use strict";var WI=Ke(),YI=ne(),zI=bp(),gp="__core-js_shared__",vp=Sp.exports=YI[gp]||zI(gp,{});(vp.versions||(vp.versions=[])).push({version:"3.38.0",mode:WI?"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 wo=f((hV,Tp)=>{"use strict";var yp=Ei();Tp.exports=function(a,e){return yp[a]||(yp[a]=e||{})}});var Lr=f((mV,Ip)=>{"use strict";var KI=Lt(),XI=Object;Ip.exports=function(a){return XI(KI(a))}});var Xe=f((fV,Ep)=>{"use strict";var JI=ce(),ZI=Lr(),eE=JI({}.hasOwnProperty);Ep.exports=Object.hasOwn||function(e,t){return eE(ZI(e),t)}});var ko=f((bV,xp)=>{"use strict";var tE=ce(),rE=0,iE=Math.random(),aE=tE(1 .toString);xp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+aE(++rE+iE,36)}});var fe=f((gV,wp)=>{"use strict";var sE=ne(),nE=wo(),Pp=Xe(),oE=ko(),uE=yo(),lE=To(),Mr=sE.Symbol,Ao=nE("wks"),cE=lE?Mr.for||Mr:Mr&&Mr.withoutSetter||oE;wp.exports=function(a){return Pp(Ao,a)||(Ao[a]=uE&&Pp(Mr,a)?Mr[a]:cE("Symbol."+a)),Ao[a]}});var Rp=f((vV,$p)=>{"use strict";var dE=Ve(),kp=Oe(),Ap=Io(),pE=Ii(),hE=pp(),mE=fe(),fE=TypeError,bE=mE("toPrimitive");$p.exports=function(a,e){if(!kp(a)||Ap(a))return a;var t=pE(a,bE),r;if(t){if(e===void 0&&(e="default"),r=dE(t,a,e),!kp(r)||Ap(r))return r;throw new fE("Can't convert object to primitive value")}return e===void 0&&(e="number"),hE(a,e)}});var $o=f((SV,Lp)=>{"use strict";var gE=Rp(),vE=Io();Lp.exports=function(a){var e=gE(a,"string");return vE(e)?e:e+""}});var Ss=f((yV,Dp)=>{"use strict";var SE=ne(),Mp=Oe(),Ro=SE.document,yE=Mp(Ro)&&Mp(Ro.createElement);Dp.exports=function(a){return yE?Ro.createElement(a):{}}});var Lo=f((TV,Cp)=>{"use strict";var TE=Ce(),IE=me(),EE=Ss();Cp.exports=!TE&&!IE(function(){return Object.defineProperty(EE("div"),"a",{get:function(){return 7}}).a!==7})});var _p=f(Op=>{"use strict";var xE=Ce(),PE=Ve(),wE=mo(),kE=Si(),AE=rr(),$E=$o(),RE=Xe(),LE=Lo(),Vp=Object.getOwnPropertyDescriptor;Op.f=xE?Vp:function(e,t){if(e=AE(e),t=$E(t),LE)try{return Vp(e,t)}catch(r){}if(RE(e,t))return kE(!PE(wE.f,e,t),e[t])}});var Mo=f((EV,Bp)=>{"use strict";var ME=me(),DE=ae(),CE=/#|\.prototype\./,xi=function(a,e){var t=OE[VE(a)];return t===BE?!0:t===_E?!1:DE(e)?ME(e):!!e},VE=xi.normalize=function(a){return String(a).replace(CE,".").toLowerCase()},OE=xi.data={},_E=xi.NATIVE="N",BE=xi.POLYFILL="P";Bp.exports=xi});var Dr=f((xV,Fp)=>{"use strict";var Np=po(),NE=st(),FE=vi(),qE=Np(Np.bind);Fp.exports=function(a,e){return NE(a),e===void 0?a:FE?qE(a,e):function(){return a.apply(e,arguments)}}});var Do=f((PV,qp)=>{"use strict";var UE=Ce(),HE=me();qp.exports=UE&&HE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=f((wV,Up)=>{"use strict";var jE=Oe(),QE=String,GE=TypeError;Up.exports=function(a){if(jE(a))return a;throw new GE(QE(a)+" is not an object")}});var ar=f(jp=>{"use strict";var WE=Ce(),YE=Lo(),zE=Do(),ys=nt(),Hp=$o(),KE=TypeError,Co=Object.defineProperty,XE=Object.getOwnPropertyDescriptor,Vo="enumerable",Oo="configurable",_o="writable";jp.f=WE?zE?function(e,t,r){if(ys(e),t=Hp(t),ys(r),typeof e=="function"&&t==="prototype"&&"value"in r&&_o in r&&!r[_o]){var i=XE(e,t);i&&i[_o]&&(e[t]=r.value,r={configurable:Oo in r?r[Oo]:i[Oo],enumerable:Vo in r?r[Vo]:i[Vo],writable:!1})}return Co(e,t,r)}:Co:function(e,t,r){if(ys(e),t=Hp(t),ys(r),YE)try{return Co(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 Cr=f((AV,Qp)=>{"use strict";var JE=Ce(),ZE=ar(),ex=Si();Qp.exports=JE?function(a,e,t){return ZE.f(a,e,ex(1,t))}:function(a,e,t){return a[e]=t,a}});var le=f(($V,Wp)=>{"use strict";var Pi=ne(),tx=lo(),rx=po(),ix=ae(),ax=_p().f,sx=Mo(),Vr=Rr(),nx=Dr(),Or=Cr(),Gp=Xe();Ei();var ox=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 tx(a,this,arguments)};return e.prototype=a.prototype,e};Wp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Pi:i?Pi[t]:Pi[t]&&Pi[t].prototype,o=r?Vr:Vr[t]||Or(Vr,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=sx(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Gp(n,p),m=o[p],c&&(a.dontCallGetSet?(v=ax(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=nx(h,Pi):a.wrap&&c?g=ox(h):s&&ix(h)?g=rx(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Or(g,"sham",!0),Or(o,p,g),s&&(d=t+"Prototype",Gp(Vr,d)||Or(Vr,d,{}),Or(Vr[d],p,h),a.real&&u&&(l||!u[p])&&Or(u,p,h)))}});var zp=f((RV,Yp)=>{"use strict";var ux=Math.ceil,lx=Math.floor;Yp.exports=Math.trunc||function(e){var t=+e;return(t>0?lx:ux)(t)}});var wi=f((LV,Kp)=>{"use strict";var cx=zp();Kp.exports=function(a){var e=+a;return e!==e||e===0?0:cx(e)}});var Jp=f((MV,Xp)=>{"use strict";var dx=wi(),px=Math.max,hx=Math.min;Xp.exports=function(a,e){var t=dx(a);return t<0?px(t+e,0):hx(t,e)}});var Bo=f((DV,Zp)=>{"use strict";var mx=wi(),fx=Math.min;Zp.exports=function(a){var e=mx(a);return e>0?fx(e,9007199254740991):0}});var _r=f((CV,eh)=>{"use strict";var bx=Bo();eh.exports=function(a){return bx(a.length)}});var No=f((VV,rh)=>{"use strict";var gx=rr(),vx=Jp(),Sx=_r(),th=function(a){return function(e,t,r){var i=gx(e),s=Sx(i);if(s===0)return!a&&-1;var n=vx(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}};rh.exports={includes:th(!0),indexOf:th(!1)}});var ki=f((OV,ih)=>{"use strict";ih.exports=function(){}});var ah=f(()=>{"use strict";var yx=le(),Tx=No().includes,Ix=me(),Ex=ki(),xx=Ix(function(){return!Array(1).includes()});yx({target:"Array",proto:!0,forced:xx},{includes:function(e){return Tx(this,e,arguments.length>1?arguments[1]:void 0)}});Ex("includes")});var Mt=f((NV,sh)=>{"use strict";var Px=ht();sh.exports=Px});var oh=f((FV,nh)=>{"use strict";ah();var wx=Mt();nh.exports=wx("Array","includes")});var lh=f((qV,uh)=>{"use strict";var kx=oh();uh.exports=kx});var Fe=f((UV,ch)=>{"use strict";var Ax=lh();ch.exports=Ax});var Es=f((eO,vh)=>{"use strict";var Ox=wo(),_x=ko(),gh=Ox("keys");vh.exports=function(a){return gh[a]||(gh[a]=_x(a))}});var yh=f((tO,Sh)=>{"use strict";var Bx=me();Sh.exports=!Bx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var xs=f((rO,Ih)=>{"use strict";var Nx=Xe(),Fx=ae(),qx=Lr(),Ux=Es(),Hx=yh(),Th=Ux("IE_PROTO"),Uo=Object,jx=Uo.prototype;Ih.exports=Hx?Uo.getPrototypeOf:function(a){var e=qx(a);if(Nx(e,Th))return e[Th];var t=e.constructor;return Fx(t)&&e instanceof t?t.prototype:e instanceof Uo?jx:null}});var Ps=f((iO,Eh)=>{"use strict";Eh.exports={}});var wh=f((aO,Ph)=>{"use strict";var Qx=ce(),Ho=Xe(),Gx=rr(),Wx=No().indexOf,Yx=Ps(),xh=Qx([].push);Ph.exports=function(a,e){var t=Gx(a),r=0,i=[],s;for(s in t)!Ho(Yx,s)&&Ho(t,s)&&xh(i,s);for(;e.length>r;)Ho(t,s=e[r++])&&(~Wx(i,s)||xh(i,s));return i}});var jo=f((sO,kh)=>{"use strict";kh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Qo=f((nO,Ah)=>{"use strict";var zx=wh(),Kx=jo();Ah.exports=Object.keys||function(e){return zx(e,Kx)}});var Go=f((oO,Dh)=>{"use strict";var Rh=Ce(),Xx=me(),Lh=ce(),Jx=xs(),Zx=Qo(),eP=rr(),tP=mo().f,Mh=Lh(tP),rP=Lh([].push),iP=Rh&&Xx(function(){var a=Object.create(null);return a[2]=2,!Mh(a,2)}),$h=function(a){return function(e){for(var t=eP(e),r=Zx(t),i=iP&&Jx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Rh||(i?u in t:Mh(t,u)))&&rP(o,a?[u,t[u]]:t[u]);return o}};Dh.exports={entries:$h(!0),values:$h(!1)}});var Ch=f(()=>{"use strict";var aP=le(),sP=Go().entries;aP({target:"Object",stat:!0},{entries:function(e){return sP(e)}})});var Oh=f((cO,Vh)=>{"use strict";Ch();var nP=Rr();Vh.exports=nP.Object.entries});var Bh=f((dO,_h)=>{"use strict";var oP=Oh();_h.exports=oP});var Br=f((pO,Nh)=>{"use strict";var uP=Bh();Nh.exports=uP});var sr=f((hO,Fh)=>{"use strict";Fh.exports={}});var Hh=f((mO,Uh)=>{"use strict";var lP=ne(),cP=ae(),qh=lP.WeakMap;Uh.exports=cP(qh)&&/native code/.test(String(qh))});var Ko=f((fO,Gh)=>{"use strict";var dP=Hh(),Qh=ne(),pP=Oe(),hP=Cr(),Wo=Xe(),Yo=Ei(),mP=Es(),fP=Ps(),jh="Object already initialized",zo=Qh.TypeError,bP=Qh.WeakMap,ws,Ai,ks,gP=function(a){return ks(a)?Ai(a):ws(a,{})},vP=function(a){return function(e){var t;if(!pP(e)||(t=Ai(e)).type!==a)throw new zo("Incompatible receiver, "+a+" required");return t}};dP||Yo.state?(Je=Yo.state||(Yo.state=new bP),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,ws=function(a,e){if(Je.has(a))throw new zo(jh);return e.facade=a,Je.set(a,e),e},Ai=function(a){return Je.get(a)||{}},ks=function(a){return Je.has(a)}):(nr=mP("state"),fP[nr]=!0,ws=function(a,e){if(Wo(a,nr))throw new zo(jh);return e.facade=a,hP(a,nr,e),e},Ai=function(a){return Wo(a,nr)?a[nr]:{}},ks=function(a){return Wo(a,nr)});var Je,nr;Gh.exports={set:ws,get:Ai,has:ks,enforce:gP,getterFor:vP}});var Zo=f((bO,Yh)=>{"use strict";var Xo=Ce(),SP=Xe(),Wh=Function.prototype,yP=Xo&&Object.getOwnPropertyDescriptor,Jo=SP(Wh,"name"),TP=Jo&&function(){}.name==="something",IP=Jo&&(!Xo||Xo&&yP(Wh,"name").configurable);Yh.exports={EXISTS:Jo,PROPER:TP,CONFIGURABLE:IP}});var Kh=f(zh=>{"use strict";var EP=Ce(),xP=Do(),PP=ar(),wP=nt(),kP=rr(),AP=Qo();zh.f=EP&&!xP?Object.defineProperties:function(e,t){wP(e);for(var r=kP(t),i=AP(t),s=i.length,n=0,o;s>n;)PP.f(e,o=i[n++],r[o]);return e}});var eu=f((vO,Xh)=>{"use strict";var $P=ht();Xh.exports=$P("document","documentElement")});var au=f((SO,am)=>{"use strict";var RP=nt(),LP=Kh(),Jh=jo(),MP=Ps(),DP=eu(),CP=Ss(),VP=Es(),Zh=">",em="<",ru="prototype",iu="script",rm=VP("IE_PROTO"),tu=function(){},im=function(a){return em+iu+Zh+a+em+"/"+iu+Zh},tm=function(a){a.write(im("")),a.close();var e=a.parentWindow.Object;return a=null,e},OP=function(){var a=CP("iframe"),e="java"+iu+":",t;return a.style.display="none",DP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(im("document.F=Object")),t.close(),t.F},As,$s=function(){try{As=new ActiveXObject("htmlfile")}catch(e){}$s=typeof document!="undefined"?document.domain&&As?tm(As):OP():tm(As);for(var a=Jh.length;a--;)delete $s[ru][Jh[a]];return $s()};MP[rm]=!0;am.exports=Object.create||function(e,t){var r;return e!==null?(tu[ru]=RP(e),r=new tu,tu[ru]=null,r[rm]=e):r=$s(),t===void 0?r:LP.f(r,t)}});var Nr=f((yO,sm)=>{"use strict";var _P=Cr();sm.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:_P(a,e,t),a}});var uu=f((TO,um)=>{"use strict";var BP=me(),NP=ae(),FP=Oe(),qP=au(),nm=xs(),UP=Nr(),HP=fe(),jP=Ke(),ou=HP("iterator"),om=!1,mt,su,nu;[].keys&&(nu=[].keys(),"next"in nu?(su=nm(nm(nu)),su!==Object.prototype&&(mt=su)):om=!0);var QP=!FP(mt)||BP(function(){var a={};return mt[ou].call(a)!==a});QP?mt={}:jP&&(mt=qP(mt));NP(mt[ou])||UP(mt,ou,function(){return this});um.exports={IteratorPrototype:mt,BUGGY_SAFARI_ITERATORS:om}});var Rs=f((IO,cm)=>{"use strict";var GP=fe(),WP=GP("toStringTag"),lm={};lm[WP]="z";cm.exports=String(lm)==="[object z]"});var $i=f((EO,dm)=>{"use strict";var YP=Rs(),zP=ae(),Ls=tr(),KP=fe(),XP=KP("toStringTag"),JP=Object,ZP=Ls(function(){return arguments}())==="Arguments",ew=function(a,e){try{return a[e]}catch(t){}};dm.exports=YP?Ls:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=ew(e=JP(a),XP))=="string"?t:ZP?Ls(e):(r=Ls(e))==="Object"&&zP(e.callee)?"Arguments":r}});var hm=f((xO,pm)=>{"use strict";var tw=Rs(),rw=$i();pm.exports=tw?{}.toString:function(){return"[object "+rw(this)+"]"}});var Ri=f((PO,fm)=>{"use strict";var iw=Rs(),aw=ar().f,sw=Cr(),nw=Xe(),ow=hm(),uw=fe(),mm=uw("toStringTag");fm.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(nw(i,mm)||aw(i,mm,{configurable:!0,value:e}),r&&!iw&&sw(i,"toString",ow))}});var gm=f((wO,bm)=>{"use strict";var lw=uu().IteratorPrototype,cw=au(),dw=Si(),pw=Ri(),hw=sr(),mw=function(){return this};bm.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=cw(lw,{next:dw(+!r,t)}),pw(a,i,!1,!0),hw[i]=mw,a}});var Sm=f((kO,vm)=>{"use strict";var fw=ce(),bw=st();vm.exports=function(a,e,t){try{return fw(bw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Tm=f((AO,ym)=>{"use strict";var gw=Oe();ym.exports=function(a){return gw(a)||a===null}});var Em=f(($O,Im)=>{"use strict";var vw=Tm(),Sw=String,yw=TypeError;Im.exports=function(a){if(vw(a))return a;throw new yw("Can't set "+Sw(a)+" as a prototype")}});var lu=f((RO,xm)=>{"use strict";var Tw=Sm(),Iw=Oe(),Ew=Lt(),xw=Em();xm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Tw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return Ew(i),xw(s),Iw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Vm=f((LO,Cm)=>{"use strict";var Pw=le(),ww=Ve(),Ms=Ke(),Mm=Zo(),kw=ae(),Aw=gm(),Pm=xs(),wm=lu(),$w=Ri(),Rw=Cr(),cu=Nr(),Lw=fe(),km=sr(),Dm=uu(),Mw=Mm.PROPER,Dw=Mm.CONFIGURABLE,Am=Dm.IteratorPrototype,Ds=Dm.BUGGY_SAFARI_ITERATORS,Li=Lw("iterator"),$m="keys",Mi="values",Rm="entries",Lm=function(){return this};Cm.exports=function(a,e,t,r,i,s,n){Aw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ds&&v&&v in c)return c[v];switch(v){case $m:return function(){return new t(this,v)};case Mi: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[Li]||c["@@iterator"]||i&&c[i],p=!Ds&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=Pm(h.call(new a)),m!==Object.prototype&&m.next&&(!Ms&&Pm(m)!==Am&&(wm?wm(m,Am):kw(m[Li])||cu(m,Li,Lm)),$w(m,u,!0,!0),Ms&&(km[u]=Lm))),Mw&&i===Mi&&d&&d.name!==Mi&&(!Ms&&Dw?Rw(c,"name",Mi):(l=!0,p=function(){return ww(d,this)})),i)if(b={values:o(Mi),keys:s?p:o($m),entries:o(Rm)},n)for(g in b)(Ds||l||!(g in c))&&cu(c,g,b[g]);else Pw({target:e,proto:!0,forced:Ds||l},b);return(!Ms||n)&&c[Li]!==p&&cu(c,Li,p,{name:i}),km[e]=p,b}});var _m=f((MO,Om)=>{"use strict";Om.exports=function(a,e){return{value:a,done:e}}});var pu=f((DO,Um)=>{"use strict";var Cw=rr(),du=ki(),Bm=sr(),Fm=Ko(),Vw=ar().f,Ow=Vm(),Cs=_m(),_w=Ke(),Bw=Ce(),qm="Array Iterator",Nw=Fm.set,Fw=Fm.getterFor(qm);Um.exports=Ow(Array,"Array",function(a,e){Nw(this,{type:qm,target:Cw(a),index:0,kind:e})},function(){var a=Fw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Cs(void 0,!0);switch(a.kind){case"keys":return Cs(t,!1);case"values":return Cs(e[t],!1)}return Cs([t,e[t]],!1)},"values");var Nm=Bm.Arguments=Bm.Array;du("keys");du("values");du("entries");if(!_w&&Bw&&Nm.name!=="values")try{Vw(Nm,"name",{value:"values"})}catch(a){}});var jm=f((CO,Hm)=>{"use strict";var qw=fe(),Uw=sr(),Hw=qw("iterator"),jw=Array.prototype;Hm.exports=function(a){return a!==void 0&&(Uw.Array===a||jw[Hw]===a)}});var hu=f((VO,Gm)=>{"use strict";var Qw=$i(),Qm=Ii(),Gw=$r(),Ww=sr(),Yw=fe(),zw=Yw("iterator");Gm.exports=function(a){if(!Gw(a))return Qm(a,zw)||Qm(a,"@@iterator")||Ww[Qw(a)]}});var Ym=f((OO,Wm)=>{"use strict";var Kw=Ve(),Xw=st(),Jw=nt(),Zw=Ti(),ek=hu(),tk=TypeError;Wm.exports=function(a,e){var t=arguments.length<2?ek(a):e;if(Xw(t))return Jw(Kw(t,a));throw new tk(Zw(a)+" is not iterable")}});var Xm=f((_O,Km)=>{"use strict";var rk=Ve(),zm=nt(),ik=Ii();Km.exports=function(a,e,t){var r,i;zm(a);try{if(r=ik(a,"return"),!r){if(e==="throw")throw t;return t}r=rk(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return zm(r),t}});var Os=f((BO,tf)=>{"use strict";var ak=Dr(),sk=Ve(),nk=nt(),ok=Ti(),uk=jm(),lk=_r(),Jm=yi(),ck=Ym(),dk=hu(),Zm=Xm(),pk=TypeError,Vs=function(a,e){this.stopped=a,this.result=e},ef=Vs.prototype;tf.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=ak(e,r),l,c,d,p,h,m,b,g=function(S){return l&&Zm(l,"normal",S),new Vs(!0,S)},v=function(S){return i?(nk(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=dk(a),!c)throw new pk(ok(a)+" is not iterable");if(uk(c)){for(d=0,p=lk(a);p>d;d++)if(h=v(a[d]),h&&Jm(ef,h))return h;return new Vs(!1)}l=ck(a,c)}for(m=s?a.next:l.next;!(b=sk(m,l)).done;){try{h=v(b.value)}catch(S){Zm(l,"throw",S)}if(typeof h=="object"&&h&&Jm(ef,h))return h}return new Vs(!1)}});var af=f((NO,rf)=>{"use strict";var hk=Ce(),mk=ar(),fk=Si();rf.exports=function(a,e,t){hk?mk.f(a,e,fk(0,t)):a[e]=t}});var sf=f(()=>{"use strict";var bk=le(),gk=Os(),vk=af();bk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return gk(e,function(r,i){vk(t,r,i)},{AS_ENTRIES:!0}),t}})});var of=f((UO,nf)=>{"use strict";pu();sf();var Sk=Rr();nf.exports=Sk.Object.fromEntries});var lf=f((HO,uf)=>{"use strict";uf.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var df=f(()=>{"use strict";pu();var yk=lf(),Tk=ne(),Ik=Ri(),cf=sr();for(_s in yk)Ik(Tk[_s],_s),cf[_s]=cf.Array;var _s});var hf=f((GO,pf)=>{"use strict";var Ek=of();df();pf.exports=Ek});var mu=f((WO,mf)=>{"use strict";var xk=hf();mf.exports=xk});var ff=f(()=>{"use strict"});var fu=f((KO,bf)=>{"use strict";var Di=ne(),Pk=ir(),wk=tr(),Bs=function(a){return Pk.slice(0,a.length)===a};bf.exports=function(){return Bs("Bun/")?"BUN":Bs("Cloudflare-Workers")?"CLOUDFLARE":Bs("Deno/")?"DENO":Bs("Node.js/")?"NODE":Di.Bun&&typeof Bun.version=="string"?"BUN":Di.Deno&&typeof Deno.version=="object"?"DENO":wk(Di.process)==="process"?"NODE":Di.window&&Di.document?"BROWSER":"REST"}()});var Ns=f((XO,gf)=>{"use strict";var kk=fu();gf.exports=kk==="NODE"});var Sf=f((JO,vf)=>{"use strict";var Ak=ar();vf.exports=function(a,e,t){return Ak.f(a,e,t)}});var If=f((ZO,Tf)=>{"use strict";var $k=ht(),Rk=Sf(),Lk=fe(),Mk=Ce(),yf=Lk("species");Tf.exports=function(a){var e=$k(a);Mk&&e&&!e[yf]&&Rk(e,yf,{configurable:!0,get:function(){return this}})}});var xf=f((e_,Ef)=>{"use strict";var Dk=yi(),Ck=TypeError;Ef.exports=function(a,e){if(Dk(e,a))return a;throw new Ck("Incorrect invocation")}});var gu=f((t_,Pf)=>{"use strict";var Vk=ce(),Ok=ae(),bu=Ei(),_k=Vk(Function.toString);Ok(bu.inspectSource)||(bu.inspectSource=function(a){return _k(a)});Pf.exports=bu.inspectSource});var Su=f((r_,Rf)=>{"use strict";var Bk=ce(),Nk=me(),wf=ae(),Fk=$i(),qk=ht(),Uk=gu(),kf=function(){},Af=qk("Reflect","construct"),vu=/^\s*(?:class|function)\b/,Hk=Bk(vu.exec),jk=!vu.test(kf),Ci=function(e){if(!wf(e))return!1;try{return Af(kf,[],e),!0}catch(t){return!1}},$f=function(e){if(!wf(e))return!1;switch(Fk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return jk||!!Hk(vu,Uk(e))}catch(t){return!0}};$f.sham=!0;Rf.exports=!Af||Nk(function(){var a;return Ci(Ci.call)||!Ci(Object)||!Ci(function(){a=!0})||a})?$f:Ci});var Mf=f((i_,Lf)=>{"use strict";var Qk=Su(),Gk=Ti(),Wk=TypeError;Lf.exports=function(a){if(Qk(a))return a;throw new Wk(Gk(a)+" is not a constructor")}});var yu=f((a_,Cf)=>{"use strict";var Df=nt(),Yk=Mf(),zk=$r(),Kk=fe(),Xk=Kk("species");Cf.exports=function(a,e){var t=Df(a).constructor,r;return t===void 0||zk(r=Df(t)[Xk])?e:Yk(r)}});var Of=f((s_,Vf)=>{"use strict";var Jk=ce();Vf.exports=Jk([].slice)});var Bf=f((n_,_f)=>{"use strict";var Zk=TypeError;_f.exports=function(a,e){if(a<e)throw new Zk("Not enough arguments");return a}});var Tu=f((o_,Nf)=>{"use strict";var eA=ir();Nf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(eA)});var Ru=f((u_,Yf)=>{"use strict";var _e=ne(),tA=lo(),rA=Dr(),Ff=ae(),iA=Xe(),Wf=me(),qf=eu(),aA=Of(),Uf=Ss(),sA=Bf(),nA=Tu(),oA=Ns(),ku=_e.setImmediate,Au=_e.clearImmediate,uA=_e.process,Iu=_e.Dispatch,lA=_e.Function,Hf=_e.MessageChannel,cA=_e.String,Eu=0,Vi={},jf="onreadystatechange",Oi,or,xu,Pu;Wf(function(){Oi=_e.location});var $u=function(a){if(iA(Vi,a)){var e=Vi[a];delete Vi[a],e()}},wu=function(a){return function(){$u(a)}},Qf=function(a){$u(a.data)},Gf=function(a){_e.postMessage(cA(a),Oi.protocol+"//"+Oi.host)};(!ku||!Au)&&(ku=function(e){sA(arguments.length,1);var t=Ff(e)?e:lA(e),r=aA(arguments,1);return Vi[++Eu]=function(){tA(t,void 0,r)},or(Eu),Eu},Au=function(e){delete Vi[e]},oA?or=function(a){uA.nextTick(wu(a))}:Iu&&Iu.now?or=function(a){Iu.now(wu(a))}:Hf&&!nA?(xu=new Hf,Pu=xu.port2,xu.port1.onmessage=Qf,or=rA(Pu.postMessage,Pu)):_e.addEventListener&&Ff(_e.postMessage)&&!_e.importScripts&&Oi&&Oi.protocol!=="file:"&&!Wf(Gf)?(or=Gf,_e.addEventListener("message",Qf,!1)):jf in Uf("script")?or=function(a){qf.appendChild(Uf("script"))[jf]=function(){qf.removeChild(this),$u(a)}}:or=function(a){setTimeout(wu(a),0)});Yf.exports={set:ku,clear:Au}});var Xf=f((l_,Kf)=>{"use strict";var zf=ne(),dA=Ce(),pA=Object.getOwnPropertyDescriptor;Kf.exports=function(a){if(!dA)return zf[a];var e=pA(zf,a);return e&&e.value}});var Lu=f((c_,Zf)=>{"use strict";var Jf=function(){this.head=null,this.tail=null};Jf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Zf.exports=Jf});var tb=f((d_,eb)=>{"use strict";var hA=ir();eb.exports=/ipad|iphone|ipod/i.test(hA)&&typeof Pebble!="undefined"});var ib=f((p_,rb)=>{"use strict";var mA=ir();rb.exports=/web0s(?!.*chrome)/i.test(mA)});var cb=f((h_,lb)=>{"use strict";var qr=ne(),fA=Xf(),ab=Dr(),Mu=Ru().set,bA=Lu(),gA=Tu(),vA=tb(),SA=ib(),Du=Ns(),sb=qr.MutationObserver||qr.WebKitMutationObserver,nb=qr.document,ob=qr.process,Fs=qr.Promise,Ou=fA("queueMicrotask"),Fr,Cu,Vu,qs,ub;Ou||(_i=new bA,Bi=function(){var a,e;for(Du&&(a=ob.domain)&&a.exit();e=_i.get();)try{e()}catch(t){throw _i.head&&Fr(),t}a&&a.enter()},!gA&&!Du&&!SA&&sb&&nb?(Cu=!0,Vu=nb.createTextNode(""),new sb(Bi).observe(Vu,{characterData:!0}),Fr=function(){Vu.data=Cu=!Cu}):!vA&&Fs&&Fs.resolve?(qs=Fs.resolve(void 0),qs.constructor=Fs,ub=ab(qs.then,qs),Fr=function(){ub(Bi)}):Du?Fr=function(){ob.nextTick(Bi)}:(Mu=ab(Mu,qr),Fr=function(){Mu(Bi)}),Ou=function(a){_i.head||Fr(),_i.add(a)});var _i,Bi;lb.exports=Ou});var pb=f((m_,db)=>{"use strict";db.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Us=f((f_,hb)=>{"use strict";hb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ur=f((b_,mb)=>{"use strict";var yA=ne();mb.exports=yA.Promise});var Ur=f((g_,vb)=>{"use strict";var TA=ne(),Ni=ur(),IA=ae(),EA=Mo(),xA=gu(),PA=fe(),fb=fu(),wA=Ke(),_u=So(),bb=Ni&&Ni.prototype,kA=PA("species"),Bu=!1,gb=IA(TA.PromiseRejectionEvent),AA=EA("Promise",function(){var a=xA(Ni),e=a!==String(Ni);if(!e&&_u===66||wA&&!(bb.catch&&bb.finally))return!0;if(!_u||_u<51||!/native code/.test(a)){var t=new Ni(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[kA]=r,Bu=t.then(function(){})instanceof r,!Bu)return!0}return!e&&(fb==="BROWSER"||fb==="DENO")&&!gb});vb.exports={CONSTRUCTOR:AA,REJECTION_EVENT:gb,SUBCLASSING:Bu}});var Hr=f((v_,yb)=>{"use strict";var Sb=st(),$A=TypeError,RA=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new $A("Bad Promise constructor");e=r,t=i}),this.resolve=Sb(e),this.reject=Sb(t)};yb.exports.f=function(a){return new RA(a)}});var Nb=f(()=>{"use strict";var LA=le(),MA=Ke(),Gs=Ns(),Dt=ne(),Wr=Ve(),Tb=Nr(),Ib=lu(),DA=Ri(),CA=If(),VA=st(),Qs=ae(),OA=Oe(),_A=xf(),BA=yu(),kb=Ru().set,Hu=cb(),NA=pb(),FA=Us(),qA=Lu(),Ab=Ko(),Ws=ur(),ju=Ur(),$b=Hr(),Ys="Promise",Rb=ju.CONSTRUCTOR,UA=ju.REJECTION_EVENT,HA=ju.SUBCLASSING,Nu=Ab.getterFor(Ys),jA=Ab.set,jr=Ws&&Ws.prototype,lr=Ws,Hs=jr,Lb=Dt.TypeError,Fu=Dt.document,Qu=Dt.process,qu=$b.f,QA=qu,GA=!!(Fu&&Fu.createEvent&&Dt.dispatchEvent),Mb="unhandledrejection",WA="rejectionhandled",Eb=0,Db=1,YA=2,Gu=1,Cb=2,js,xb,zA,Pb,Vb=function(a){var e;return OA(a)&&Qs(e=a.then)?e:!1},Ob=function(a,e){var t=e.value,r=e.state===Db,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Cb&&XA(e),e.rejection=Gu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Lb("Promise-chain cycle")):(l=Vb(u))?Wr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},_b=function(a,e){a.notified||(a.notified=!0,Hu(function(){for(var t=a.reactions,r;r=t.get();)Ob(r,a);a.notified=!1,e&&!a.rejection&&KA(a)}))},Bb=function(a,e,t){var r,i;GA?(r=Fu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Dt.dispatchEvent(r)):r={promise:e,reason:t},!UA&&(i=Dt["on"+a])?i(r):a===Mb&&NA("Unhandled promise rejection",t)},KA=function(a){Wr(kb,Dt,function(){var e=a.facade,t=a.value,r=wb(a),i;if(r&&(i=FA(function(){Gs?Qu.emit("unhandledRejection",t,e):Bb(Mb,e,t)}),a.rejection=Gs||wb(a)?Cb:Gu,i.error))throw i.value})},wb=function(a){return a.rejection!==Gu&&!a.parent},XA=function(a){Wr(kb,Dt,function(){var e=a.facade;Gs?Qu.emit("rejectionHandled",e):Bb(WA,e,a.value)})},Qr=function(a,e,t){return function(r){a(e,r,t)}},Gr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=YA,_b(a,!0))},Uu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Lb("Promise can't be resolved itself");var r=Vb(e);r?Hu(function(){var i={done:!1};try{Wr(r,e,Qr(Uu,i,a),Qr(Gr,i,a))}catch(s){Gr(i,s,a)}}):(a.value=e,a.state=Db,_b(a,!1))}catch(i){Gr({done:!1},i,a)}}};if(Rb&&(lr=function(e){_A(this,Hs),VA(e),Wr(js,this);var t=Nu(this);try{e(Qr(Uu,t),Qr(Gr,t))}catch(r){Gr(t,r)}},Hs=lr.prototype,js=function(e){jA(this,{type:Ys,done:!1,notified:!1,parent:!1,reactions:new qA,rejection:!1,state:Eb,value:void 0})},js.prototype=Tb(Hs,"then",function(e,t){var r=Nu(this),i=qu(BA(this,lr));return r.parent=!0,i.ok=Qs(e)?e:!0,i.fail=Qs(t)&&t,i.domain=Gs?Qu.domain:void 0,r.state===Eb?r.reactions.add(i):Hu(function(){Ob(i,r)}),i.promise}),xb=function(){var a=new js,e=Nu(a);this.promise=a,this.resolve=Qr(Uu,e),this.reject=Qr(Gr,e)},$b.f=qu=function(a){return a===lr||a===zA?new xb(a):QA(a)},!MA&&Qs(Ws)&&jr!==Object.prototype)){Pb=jr.then,HA||Tb(jr,"then",function(e,t){var r=this;return new lr(function(i,s){Wr(Pb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete jr.constructor}catch(a){}Ib&&Ib(jr,Hs)}LA({global:!0,constructor:!0,wrap:!0,forced:Rb},{Promise:lr});DA(lr,Ys,!1,!0);CA(Ys)});var jb=f((T_,Hb)=>{"use strict";var JA=fe(),qb=JA("iterator"),Ub=!1;try{Fb=0,Wu={next:function(){return{done:!!Fb++}},return:function(){Ub=!0}},Wu[qb]=function(){return this},Array.from(Wu,function(){throw 2})}catch(a){}var Fb,Wu;Hb.exports=function(a,e){try{if(!e&&!Ub)return!1}catch(i){return!1}var t=!1;try{var r={};r[qb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Yu=f((I_,Qb)=>{"use strict";var ZA=ur(),e$=jb(),t$=Ur().CONSTRUCTOR;Qb.exports=t$||!e$(function(a){ZA.all(a).then(void 0,function(){})})});var Gb=f(()=>{"use strict";var r$=le(),i$=Ve(),a$=st(),s$=Hr(),n$=Us(),o$=Os(),u$=Yu();r$({target:"Promise",stat:!0,forced:u$},{all:function(e){var t=this,r=s$.f(t),i=r.resolve,s=r.reject,n=n$(function(){var o=a$(t.resolve),u=[],l=0,c=1;o$(e,function(d){var p=l++,h=!1;c++,i$(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 l$=le(),c$=Ke(),d$=Ur().CONSTRUCTOR,Ku=ur(),p$=ht(),h$=ae(),m$=Nr(),Wb=Ku&&Ku.prototype;l$({target:"Promise",proto:!0,forced:d$,real:!0},{catch:function(a){return this.then(void 0,a)}});!c$&&h$(Ku)&&(zu=p$("Promise").prototype.catch,Wb.catch!==zu&&m$(Wb,"catch",zu,{unsafe:!0}));var zu});var zb=f(()=>{"use strict";var f$=le(),b$=Ve(),g$=st(),v$=Hr(),S$=Us(),y$=Os(),T$=Yu();f$({target:"Promise",stat:!0,forced:T$},{race:function(e){var t=this,r=v$.f(t),i=r.reject,s=S$(function(){var n=g$(t.resolve);y$(e,function(o){b$(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Kb=f(()=>{"use strict";var I$=le(),E$=Hr(),x$=Ur().CONSTRUCTOR;I$({target:"Promise",stat:!0,forced:x$},{reject:function(e){var t=E$.f(this),r=t.reject;return r(e),t.promise}})});var Xu=f((L_,Xb)=>{"use strict";var P$=nt(),w$=Oe(),k$=Hr();Xb.exports=function(a,e){if(P$(a),w$(e)&&e.constructor===a)return e;var t=k$.f(a),r=t.resolve;return r(e),t.promise}});var eg=f(()=>{"use strict";var A$=le(),$$=ht(),Jb=Ke(),R$=ur(),Zb=Ur().CONSTRUCTOR,L$=Xu(),M$=$$("Promise"),D$=Jb&&!Zb;A$({target:"Promise",stat:!0,forced:Jb||Zb},{resolve:function(e){return L$(D$&&this===M$?R$:this,e)}})});var tg=f(()=>{"use strict";Nb();Gb();Yb();zb();Kb();eg()});var sg=f(()=>{"use strict";var C$=le(),V$=Ke(),zs=ur(),O$=me(),ig=ht(),ag=ae(),_$=yu(),rg=Xu(),B$=Nr(),Zu=zs&&zs.prototype,N$=!!zs&&O$(function(){Zu.finally.call({then:function(){}},function(){})});C$({target:"Promise",proto:!0,real:!0,forced:N$},{finally:function(a){var e=_$(this,ig("Promise")),t=ag(a);return this.then(t?function(r){return rg(e,a()).then(function(){return r})}:a,t?function(r){return rg(e,a()).then(function(){throw r})}:a)}});!V$&&ag(zs)&&(Ju=ig("Promise").prototype.finally,Zu.finally!==Ju&&B$(Zu,"finally",Ju,{unsafe:!0}));var Ju});var og=f((B_,ng)=>{"use strict";ff();tg();sg();var F$=Mt();ng.exports=F$("Promise","finally")});var lg=f((N_,ug)=>{"use strict";var q$=og();ug.exports=q$});var Ks=f((F_,cg)=>{"use strict";var U$=lg();cg.exports=U$});var Eg=f(()=>{"use strict";var rR=le(),iR=Go().values;rR({target:"Object",stat:!0},{values:function(e){return iR(e)}})});var Pg=f((xB,xg)=>{"use strict";Eg();var aR=Rr();xg.exports=aR.Object.values});var kg=f((PB,wg)=>{"use strict";var sR=Pg();wg.exports=sR});var zr=f((wB,Ag)=>{"use strict";var nR=kg();Ag.exports=nR});var Qg=f(()=>{"use strict";var $R=le(),RR=Lr(),LR=_r(),MR=wi(),DR=ki();$R({target:"Array",proto:!0},{at:function(e){var t=RR(this),r=LR(t),i=MR(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});DR("at")});var Wg=f((BN,Gg)=>{"use strict";Qg();var CR=Mt();Gg.exports=CR("Array","at")});var zg=f((NN,Yg)=>{"use strict";var VR=Wg();Yg.exports=VR});var Bt=f((FN,Kg)=>{"use strict";var OR=zg();Kg.exports=OR});var Pl=f((Aq,Lv)=>{"use strict";var SL=tr();Lv.exports=Array.isArray||function(e){return SL(e)==="Array"}});var Dv=f(($q,Mv)=>{"use strict";var yL=TypeError,TL=9007199254740991;Mv.exports=function(a){if(a>TL)throw yL("Maximum allowed index exceeded");return a}});var Ov=f((Rq,Vv)=>{"use strict";var IL=Pl(),EL=_r(),xL=Dv(),PL=Dr(),Cv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?PL(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&IL(d)?(p=EL(d),u=Cv(a,e,d,p,u,s-1)-1):(xL(u+1),a[u]=d),u++),l++;return u};Vv.exports=Cv});var Fv=f((Lq,Nv)=>{"use strict";var _v=Pl(),wL=Su(),kL=Oe(),AL=fe(),$L=AL("species"),Bv=Array;Nv.exports=function(a){var e;return _v(a)&&(e=a.constructor,wL(e)&&(e===Bv||_v(e.prototype))?e=void 0:kL(e)&&(e=e[$L],e===null&&(e=void 0))),e===void 0?Bv:e}});var Uv=f((Mq,qv)=>{"use strict";var RL=Fv();qv.exports=function(a,e){return new(RL(a))(e===0?0:e)}});var Hv=f(()=>{"use strict";var LL=le(),ML=Ov(),DL=st(),CL=Lr(),VL=_r(),OL=Uv();LL({target:"Array",proto:!0},{flatMap:function(e){var t=CL(this),r=VL(t),i;return DL(e),i=OL(t,0),i.length=ML(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var jv=f(()=>{"use strict";var _L=ki();_L("flatMap")});var Gv=f((_q,Qv)=>{"use strict";Hv();jv();var BL=Mt();Qv.exports=BL("Array","flatMap")});var Yv=f((Bq,Wv)=>{"use strict";var NL=Gv();Wv.exports=NL});var wl=f((Nq,zv)=>{"use strict";var FL=Yv();zv.exports=FL});var ra=f((Fq,Kv)=>{"use strict";var qL=$i(),UL=String;Kv.exports=function(a){if(qL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return UL(a)}});var kl=f((qq,Xv)=>{"use strict";Xv.exports=`
|
|
7
|
-
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var eS=f((Uq,Zv)=>{"use strict";var HL=ce(),jL=Lt(),QL=ra(),$l=kl(),Jv=HL("".replace),GL=RegExp("^["+$l+"]+"),WL=RegExp("(^|[^"+$l+"])["+$l+"]+$"),Al=function(a){return function(e){var t=QL(jL(e));return a&1&&(t=Jv(t,GL,"")),a&2&&(t=Jv(t,WL,"$1")),t}};Zv.exports={start:Al(1),end:Al(2),trim:Al(3)}});var aS=f((Hq,iS)=>{"use strict";var YL=Zo().PROPER,zL=me(),tS=kl(),rS="\u200B\x85\u180E";iS.exports=function(a){return zL(function(){return!!tS[a]()||rS[a]()!==rS||YL&&tS[a].name!==a})}});var Rl=f((jq,sS)=>{"use strict";var KL=eS().start,XL=aS();sS.exports=XL("trimStart")?function(){return KL(this)}:"".trimStart});var oS=f(()=>{"use strict";var JL=le(),nS=Rl();JL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==nS},{trimLeft:nS})});var lS=f(()=>{"use strict";oS();var ZL=le(),uS=Rl();ZL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==uS},{trimStart:uS})});var dS=f((zq,cS)=>{"use strict";lS();var eM=Mt();cS.exports=eM("String","trimLeft")});var hS=f((Kq,pS)=>{"use strict";var tM=dS();pS.exports=tM});var fS=f((Xq,mS)=>{"use strict";var rM=hS();mS.exports=rM});var LS=f(()=>{"use strict"});var MS=f(()=>{"use strict"});var CS=f((CH,DS)=>{"use strict";var PM=Oe(),wM=tr(),kM=fe(),AM=kM("match");DS.exports=function(a){var e;return PM(a)&&((e=a[AM])!==void 0?!!e:wM(a)==="RegExp")}});var OS=f((VH,VS)=>{"use strict";var $M=nt();VS.exports=function(){var a=$M(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var NS=f((OH,BS)=>{"use strict";var RM=Ve(),LM=Xe(),MM=yi(),DM=OS(),_S=RegExp.prototype;BS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in _S)&&!LM(a,"flags")&&MM(_S,a)?RM(DM,a):e}});var qS=f((_H,FS)=>{"use strict";var Bl=ce(),CM=Lr(),VM=Math.floor,Ol=Bl("".charAt),OM=Bl("".replace),_l=Bl("".slice),_M=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,BM=/\$([$&'`]|\d{1,2})/g;FS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=BM;return i!==void 0&&(i=CM(i),u=_M),OM(s,u,function(l,c){var d;switch(Ol(c,0)){case"$":return"$";case"&":return a;case"`":return _l(e,0,t);case"'":return _l(e,n);case"<":d=i[_l(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=VM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Ol(c,1):r[h-1]+Ol(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var jS=f(()=>{"use strict";var NM=le(),FM=Ve(),Fl=ce(),US=Lt(),qM=ae(),UM=$r(),HM=CS(),ti=ra(),jM=Ii(),QM=NS(),GM=qS(),WM=fe(),YM=Ke(),zM=WM("replace"),KM=TypeError,Nl=Fl("".indexOf),XM=Fl("".replace),HS=Fl("".slice),JM=Math.max;NM({target:"String",proto:!0},{replaceAll:function(e,t){var r=US(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!UM(e)){if(i=HM(e),i&&(s=ti(US(QM(e))),!~Nl(s,"g")))throw new KM("`.replaceAll` does not allow non-global regexes");if(n=jM(e,zM),n)return FM(n,e,r,t);if(YM&&i)return XM(ti(r),e,t)}for(o=ti(r),u=ti(e),l=qM(t),l||(t=ti(t)),c=u.length,d=JM(1,c),p=Nl(o,u);p!==-1;)h=l?ti(t(u,p,o)):GM(u,o,p,[],void 0,t),b+=HS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Nl(o,u,p+d);return m<o.length&&(b+=HS(o,m)),b}})});var GS=f((FH,QS)=>{"use strict";LS();MS();jS();var ZM=Mt();QS.exports=ZM("String","replaceAll")});var YS=f((qH,WS)=>{"use strict";var eD=GS();WS.exports=eD});var KS=f((UH,zS)=>{"use strict";var tD=YS();zS.exports=tD});var JS=f((HH,XS)=>{"use strict";var rD=wi(),iD=ra(),aD=Lt(),sD=RangeError;XS.exports=function(e){var t=iD(aD(this)),r="",i=rD(e);if(i<0||i===1/0)throw new sD("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var iy=f((jH,ry)=>{"use strict";var ty=ce(),nD=Bo(),ZS=ra(),oD=JS(),uD=Lt(),lD=ty(oD),cD=ty("".slice),dD=Math.ceil,ey=function(a){return function(e,t,r){var i=ZS(uD(e)),s=nD(t),n=i.length,o=r===void 0?" ":ZS(r),u,l;return s<=n||o===""?i:(u=s-n,l=lD(o,dD(u/o.length)),l.length>u&&(l=cD(l,0,u)),a?i+l:l+i)}};ry.exports={start:ey(!1),end:ey(!0)}});var sy=f((QH,ay)=>{"use strict";var pD=ir();ay.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(pD)});var ny=f(()=>{"use strict";var hD=le(),mD=iy().start,fD=sy();hD({target:"String",proto:!0,forced:fD},{padStart:function(e){return mD(this,e,arguments.length>1?arguments[1]:void 0)}})});var uy=f((YH,oy)=>{"use strict";ny();var bD=Mt();oy.exports=bD("String","padStart")});var cy=f((zH,ly)=>{"use strict";var gD=uy();ly.exports=gD});var py=f((KH,dy)=>{"use strict";var vD=cy();dy.exports=vD});var vd="2.0.129-dev.085da0ee.0";var De=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(De||{}),pt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(pt||{});var fs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(fs||{}),no=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(no||{});var oo=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(oo||{}),bs=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(bs||{});var GT=B(Fe(),1);import{assertNever as bh,assertNonNullable as $x,isNonNullable as Ts,ValueSubject as Fo,Subject as Rx,Subscription as Lx,merge as Mx,observableFrom as Dx,fromEvent as ph,map as hh,tap as mh,filterChanged as Cx,isNullable as qo,ErrorCategory as fh}from"@vkontakte/videoplayer-shared/es2015";var dh=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 Is=class{constructor(e){this.connection$=new Fo(void 0);this.castState$=new Fo("NOT_AVAILABLE");this.errorEvent$=new Rx;this.realCastState$=new Fo("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=Ts((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||dh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:fh.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var 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(){Ts(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();qo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();qo(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(ph(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 bh(i.sessionState)}})).add(Mx(ph(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(mh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),hh(i=>i.castState)),Dx([r.getCastState()])).pipe(Cx(),hh(Vx),mh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ts(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();$x(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(qo(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"?Ts(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:fh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Vx=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return bh(a)}};var Ec=B(Fe(),1),AT=B(Br(),1),$T=B(mu(),1);var yg=B(Ks(),1);import{assertNever as dg}from"@vkontakte/videoplayer-shared/es2015";var be=(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:dg(t)}return a},Xs=(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:dg(e)}};var k=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as H$,Subject as Js,merge as pg}from"@vkontakte/videoplayer-shared/es2015";var N=class{constructor(e){this.transitionStarted$=new Js;this.transitionEnded$=new Js;this.transitionUpdated$=new Js;this.forceChanged$=new Js;this.stateChangeStarted$=pg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=pg(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,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||H$(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 j$}from"@vkontakte/videoplayer-shared/es2015";var hg=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return j$(a)}};import{assertNever as Yr,assertNonNullable as cr,debounce as mg,ErrorCategory as fg,fromEvent as dr,isNonNullable as bg,map as gg,merge as vg,observableFrom as Q$,Subject as G$,Subscription as el,timeout as W$,getHighestQuality as Y$}from"@vkontakte/videoplayer-shared/es2015";var z$=5,K$=5,X$=500,Sg=7e3,Fi=class{constructor(e){this.subscription=new el;this.loadMediaTimeoutSubscription=new el;this.videoState=new N("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yr(e)}break}default:Yr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(hg(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new el;this.subscription.add(e),this.subscription.add(vg(this.videoState.stateChangeStarted$.pipe(gg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(gg(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 G$;e.add(i.pipe(mg(X$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>z$)&&i.next(o),s=o})),e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<K$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Yr(n)}}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=vg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Q$(["init"])).pipe(mg(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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];cr(c);let d=Y$(Object.keys(c));cr(d);let p=c[d];cr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];cr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];cr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];cr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];cr(c),r=be(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:fg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return bg(o)&&(n.metadata.title=o),bg(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let 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(W$(Sg).subscribe(()=>s(`timeout(${Sg})`)))});(0,yg.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:fg.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var El=B(Fe(),1);import{clearVideoElement as Ig}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as J$}from"@vkontakte/videoplayer-shared/es2015";var Tg=a=>{try{a.pause(),a.playbackRate=0,J$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as Z$,Subscription as eR}from"@vkontakte/videoplayer-shared/es2015";var tl=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)}},rl=window.WeakMap?new WeakMap:new tl,il=window.WeakMap?new WeakMap:new Map,tR=(a,e=20)=>{let t=0;return Z$(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},we=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?Ig(r):(r=document.createElement("video"),a.appendChild(r)),rl.set(r,i);let s=new eR;return s.add(tR(r,e)),il.set(r,s),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},ke=a=>{let e=il.get(a);e==null||e.unsubscribe(),il.delete(a);let t=rl.get(a);rl.delete(a),t?Ig(a):Tg(a)};var sl=B(zr(),1);import{assertNonNullable as qi,isNonNullable as ut,isNullable as lR,fromEvent as Kr,merge as $g,observableFrom as Rg,filterChanged as Lg,map as Ui,Subject as Mg,Subscription as cR,ValueSubject as dR,ErrorCategory as pR}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as al,isNullable as oR,Subscription as uR}from"@vkontakte/videoplayer-shared/es2015";var Zs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=oR(i),l=new uR;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>Zs(e,()=>a.loop,r=>{al(r)&&(a.loop=r)},{onError:t}),Ae=(a,e,t,r)=>Zs(e,()=>({muted:a.muted,volume:a.volume}),i=>{al(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}),qe=(a,e,t,r)=>Zs(e,()=>a.playbackRate,i=>{al(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ct=Zs;var hR=a=>["__",a.language,a.label].join("|"),mR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},nl=class a{constructor(e){this.available$=new Mg;this.current$=new dR(void 0);this.error$=new Mg;this.subscription=new cR;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:pR.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ct(t.internalTextTracks,()=>(0,sl.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ct(t.externalTextTracks,()=>(0,sl.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ct(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Ct(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qi(this.video);let{textTracks:e}=this.video;this.subscription.add(Kr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add($g(Kr(e,"addtrack"),Kr(e,"removetrack"),Rg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Lg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add($g(Kr(e,"change"),Rg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ui(r=>r&&this.htmlTextTrackToITextTrack(r).id),Lg()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(Kr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Kr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;ut(t.align)&&(i.align=t.align),ut(t.position)&&(i.position=t.position),ut(t.size)&&(i.size=t.size),ut(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){qi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:hR(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){qi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(lR(e)||!mR(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){qi(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){qi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ue=nl;var pr=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Dg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ol=a=>{let e=Dg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Cg=a=>{let e=Dg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as Vt,merge as ll,filterChanged as ER,isNonNullable as Hg,Subject as xR,filter as ji,mapTo as cl,combine as PR,once as wR,throttle as kR,ErrorCategory as AR,ValueSubject as jg}from"@vkontakte/videoplayer-shared/es2015";var fR=3,Vg=(a,e,t=fR)=>{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 en=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,r=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,i=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||r||n||u||l||i||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let r=t[1],i=parseInt(r,10);if(isNaN(i))return;this._safariVersion=i}catch(e){console.error(e)}}};var Og=B(Fe(),1);var Hi=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var tn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Og.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Hi()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return E(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,r=/iphone/i.test(e)?"iPhone":void 0,i=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||r||i||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let r=t[1].replace(/_/g,".");if(!r)return;let i=parseFloat(r);if(isNaN(i))return;this._iosVersion=i}catch(e){console.error(e)}}};var rn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(r){console.error(r)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(r){console.error(r)}}};var Ze=()=>window.ManagedMediaSource||window.MediaSource,an=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_g=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Bg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var bR=document.createElement("video"),gR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',vR='video/mp4; codecs="hev1.1.6.L93.B0"',Ng='video/webm; codecs="vp09.00.10.08"',Fg='video/webm; codecs="av01.0.00M.08"',SR='audio/mp4; codecs="mp4a.40.2"',yR='audio/webm; codecs="opus"',qg,TR=()=>E(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:Fg})})),window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:Ng})}))]);qg={DASH_WEBM_AV1:e,DASH_WEBM:t}});TR().catch(a=>{console.log(bR),console.error(a)});var sn=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return qg}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,r,i,s,n,o,u,l,c,d,p,h,m,b,g,v,S,T,I;this._video=document.createElement("video");try{this._protocols={mms:an(),mse:_g(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(i=(r=this._video).canPlayType)!=null&&i.call(r,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let y=!!((c=(l=Ze())==null?void 0:l.isTypeSupported)!=null&&c.call(l,gR)),$=!!((p=(d=Ze())==null?void 0:d.isTypeSupported)!=null&&p.call(d,vR)),C=!!((m=(h=Ze())==null?void 0:h.isTypeSupported)!=null&&m.call(h,SR));this._codecs={h264:y,h265:$,vp9:!!((g=(b=Ze())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Ng)),av1:!!((S=(v=Ze())==null?void 0:v.isTypeSupported)!=null&&S.call(v,Fg)),aac:C,opus:!!((I=(T=Ze())==null?void 0:T.isTypeSupported)!=null&&I.call(T,yR)),mpeg:(y||$)&&C},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(y){console.error(y)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Ug="audio/mpeg",nn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,r,i;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Ug))},this._codecs={mp3:!!((i=(r=Ze())==null?void 0:r.isTypeSupported)!=null&&i.call(r,Ug))}}catch(s){console.error(s)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as IR}from"@vkontakte/videoplayer-shared/es2015";var ul=class{constructor(){this.isInited$=new IR(!1);this._displayChecker=new rn,this._deviceChecker=new tn(this._displayChecker),this._browserChecker=new en,this._videoChecker=new sn(this._deviceChecker,this._browserChecker),this._audioChecker=new nn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return E(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},H=new ul;var Re=a=>{let e=L=>$e(a,L).pipe(cl(void 0)),r=ll(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(L=>$e(a,L))).pipe(Vt(L=>L.type==="ended"?a.readyState<2:a.readyState<3),ER()),i=ll($e(a,"progress"),$e(a,"timeupdate")).pipe(Vt(()=>Vg(a.buffered,a.currentTime))),s=H.browser.isSafari?PR({play:e("play").pipe(wR()),playing:e("playing")}).pipe(cl(void 0)):e("playing"),n=$e(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=$e(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=$e(a,"error").pipe(ji(()=>!!(a.error||a.played.length)),Vt(()=>{var O;let L=a.error;return{id:L?`MediaError#${L.code}`:"HtmlVideoError",category:AR.VIDEO_PIPELINE,message:L?L.message:"Error event from HTML video element",thrown:(O=a.error)!=null?O:void 0}})),l=$e(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new xR,d=.3,p;l.subscribe(L=>{a.loop&&Hg(p)&&Hg(L)&&p>=a.duration-d&&L<=d&&c.next(p),p=L});let h=e("pause").pipe(ji(()=>!a.error&&p!==a.duration)),m=$e(a,"enterpictureinpicture"),b=$e(a,"leavepictureinpicture"),g=new jg(Cg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new jg(ol(a));$e(a,"fullscreenchange").pipe(Vt(()=>ol(a))).subscribe(v);let T=.1,I=1e3,y=$e(a,"timeupdate").pipe(ji(L=>a.duration-a.currentTime<T)),$=ll(y.pipe(ji(L=>!a.loop)),$e(a,"ended")).pipe(kR(I),cl(void 0)),C=y.pipe(ji(L=>a.loop));return{playing$:s,pause$:h,canplay$:e("canplay"),ended$:$,looped$:c,loopExpected$:C,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:$e(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as Ot}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Ot.Q_144P;case"lowest":return Ot.Q_240P;case"low":return Ot.Q_360P;case"sd":case"medium":return Ot.Q_480P;case"hd":case"high":return Ot.Q_720P;case"fullhd":case"full":return Ot.Q_1080P;case"quadhd":case"quad":return Ot.Q_1440P;case"ultrahd":case"ultra":return Ot.Q_2160P}};var Nt=B(Bt(),1),nv=B(Fe(),1),ln=B(Br(),1);import{isNonNullable as Ee,isNullable as rv,now as ov,isHigher as iv,isHigherOrEqual as ml,isInvariantQuality as av,isLowerOrEqual as fl,videoSizeToQuality as NR,assertNotEmptyArray as uv,assertNonNullable as FR}from"@vkontakte/videoplayer-shared/es2015";var dl=!1,bt={},Xg=a=>{dl=a},Jg=()=>{bt={}},Zg=a=>{a(bt)},Qi=(a,e)=>{var t;dl&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var r,i;if(!dl)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};import{isHigher as _R,isHigherOrEqual as GN,isLower as ev,isLowerOrEqual as WN,isNonNullable as on,isNullable as BR,videoHeightToQuality as un}from"@vkontakte/videoplayer-shared/es2015";function pl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function hl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&pl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Gi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return BR(a)||on(a.min)&&on(a.max)&&ev(a.max,a.min)||on(a.min)&&e&&_R(a.min,e)||on(a.max)&&t&&ev(a.max,t)}function tv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Gi({limits:{max:a!=null&&a.max?un(a.max):void 0,min:a!=null&&a.min?un(a.min):void 0},highestAvailableQuality:e?un(e):void 0,lowestAvailableQuality:t?un(t):void 0})}var qR=new Ie("best_bitrate"),lv=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var bl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ov()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},cv='Assertion "ABR Tracks is empty array" failed',cn=(a,e,t,r)=>{var u;let i=[...e].sort(bl(1)),s=[...t].sort(bl(1)),n=s.filter(l=>Ee(l.bitrate)&&Ee(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,nv.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},sv=a=>"quality"in a,dv=(a,e,t,r)=>{var n;let i=Ee((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&Ee(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&ov()-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=sv(o)?"video":"audio",l=sv(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 eS=f((Uq,Zv)=>{"use strict";var HL=ce(),jL=Lt(),QL=ra(),$l=kl(),Jv=HL("".replace),GL=RegExp("^["+$l+"]+"),WL=RegExp("(^|[^"+$l+"])["+$l+"]+$"),Al=function(a){return function(e){var t=QL(jL(e));return a&1&&(t=Jv(t,GL,"")),a&2&&(t=Jv(t,WL,"$1")),t}};Zv.exports={start:Al(1),end:Al(2),trim:Al(3)}});var aS=f((Hq,iS)=>{"use strict";var YL=Zo().PROPER,zL=me(),tS=kl(),rS="\u200B\x85\u180E";iS.exports=function(a){return zL(function(){return!!tS[a]()||rS[a]()!==rS||YL&&tS[a].name!==a})}});var Rl=f((jq,sS)=>{"use strict";var KL=eS().start,XL=aS();sS.exports=XL("trimStart")?function(){return KL(this)}:"".trimStart});var oS=f(()=>{"use strict";var JL=le(),nS=Rl();JL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==nS},{trimLeft:nS})});var lS=f(()=>{"use strict";oS();var ZL=le(),uS=Rl();ZL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==uS},{trimStart:uS})});var dS=f((zq,cS)=>{"use strict";lS();var eM=Mt();cS.exports=eM("String","trimLeft")});var hS=f((Kq,pS)=>{"use strict";var tM=dS();pS.exports=tM});var fS=f((Xq,mS)=>{"use strict";var rM=hS();mS.exports=rM});var LS=f(()=>{"use strict"});var MS=f(()=>{"use strict"});var CS=f((CH,DS)=>{"use strict";var PM=Oe(),wM=tr(),kM=fe(),AM=kM("match");DS.exports=function(a){var e;return PM(a)&&((e=a[AM])!==void 0?!!e:wM(a)==="RegExp")}});var OS=f((VH,VS)=>{"use strict";var $M=nt();VS.exports=function(){var a=$M(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var NS=f((OH,BS)=>{"use strict";var RM=Ve(),LM=Xe(),MM=yi(),DM=OS(),_S=RegExp.prototype;BS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in _S)&&!LM(a,"flags")&&MM(_S,a)?RM(DM,a):e}});var qS=f((_H,FS)=>{"use strict";var Bl=ce(),CM=Lr(),VM=Math.floor,Ol=Bl("".charAt),OM=Bl("".replace),_l=Bl("".slice),_M=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,BM=/\$([$&'`]|\d{1,2})/g;FS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=BM;return i!==void 0&&(i=CM(i),u=_M),OM(s,u,function(l,c){var d;switch(Ol(c,0)){case"$":return"$";case"&":return a;case"`":return _l(e,0,t);case"'":return _l(e,n);case"<":d=i[_l(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=VM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Ol(c,1):r[h-1]+Ol(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var jS=f(()=>{"use strict";var NM=le(),FM=Ve(),Fl=ce(),US=Lt(),qM=ae(),UM=$r(),HM=CS(),ti=ra(),jM=Ii(),QM=NS(),GM=qS(),WM=fe(),YM=Ke(),zM=WM("replace"),KM=TypeError,Nl=Fl("".indexOf),XM=Fl("".replace),HS=Fl("".slice),JM=Math.max;NM({target:"String",proto:!0},{replaceAll:function(e,t){var r=US(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!UM(e)){if(i=HM(e),i&&(s=ti(US(QM(e))),!~Nl(s,"g")))throw new KM("`.replaceAll` does not allow non-global regexes");if(n=jM(e,zM),n)return FM(n,e,r,t);if(YM&&i)return XM(ti(r),e,t)}for(o=ti(r),u=ti(e),l=qM(t),l||(t=ti(t)),c=u.length,d=JM(1,c),p=Nl(o,u);p!==-1;)h=l?ti(t(u,p,o)):GM(u,o,p,[],void 0,t),b+=HS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Nl(o,u,p+d);return m<o.length&&(b+=HS(o,m)),b}})});var GS=f((FH,QS)=>{"use strict";LS();MS();jS();var ZM=Mt();QS.exports=ZM("String","replaceAll")});var YS=f((qH,WS)=>{"use strict";var eD=GS();WS.exports=eD});var KS=f((UH,zS)=>{"use strict";var tD=YS();zS.exports=tD});var JS=f((HH,XS)=>{"use strict";var rD=wi(),iD=ra(),aD=Lt(),sD=RangeError;XS.exports=function(e){var t=iD(aD(this)),r="",i=rD(e);if(i<0||i===1/0)throw new sD("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var iy=f((jH,ry)=>{"use strict";var ty=ce(),nD=Bo(),ZS=ra(),oD=JS(),uD=Lt(),lD=ty(oD),cD=ty("".slice),dD=Math.ceil,ey=function(a){return function(e,t,r){var i=ZS(uD(e)),s=nD(t),n=i.length,o=r===void 0?" ":ZS(r),u,l;return s<=n||o===""?i:(u=s-n,l=lD(o,dD(u/o.length)),l.length>u&&(l=cD(l,0,u)),a?i+l:l+i)}};ry.exports={start:ey(!1),end:ey(!0)}});var sy=f((QH,ay)=>{"use strict";var pD=ir();ay.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(pD)});var ny=f(()=>{"use strict";var hD=le(),mD=iy().start,fD=sy();hD({target:"String",proto:!0,forced:fD},{padStart:function(e){return mD(this,e,arguments.length>1?arguments[1]:void 0)}})});var uy=f((YH,oy)=>{"use strict";ny();var bD=Mt();oy.exports=bD("String","padStart")});var cy=f((zH,ly)=>{"use strict";var gD=uy();ly.exports=gD});var py=f((KH,dy)=>{"use strict";var vD=cy();dy.exports=vD});var vd="2.0.129-dev.107d6e94.0";var De=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(De||{}),pt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(pt||{});var fs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(fs||{}),no=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(no||{});var oo=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(oo||{}),bs=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(bs||{});var GT=B(Fe(),1);import{assertNever as bh,assertNonNullable as $x,isNonNullable as Ts,ValueSubject as Fo,Subject as Rx,Subscription as Lx,merge as Mx,observableFrom as Dx,fromEvent as ph,map as hh,tap as mh,filterChanged as Cx,isNullable as qo,ErrorCategory as fh}from"@vkontakte/videoplayer-shared/es2015";var dh=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 Is=class{constructor(e){this.connection$=new Fo(void 0);this.castState$=new Fo("NOT_AVAILABLE");this.errorEvent$=new Rx;this.realCastState$=new Fo("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=Ts((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||dh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:fh.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var 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(){Ts(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();qo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();qo(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(ph(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 bh(i.sessionState)}})).add(Mx(ph(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(mh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),hh(i=>i.castState)),Dx([r.getCastState()])).pipe(Cx(),hh(Vx),mh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ts(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();$x(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(qo(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"?Ts(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:fh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Vx=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return bh(a)}};var Ec=B(Fe(),1),AT=B(Br(),1),$T=B(mu(),1);var yg=B(Ks(),1);import{assertNever as dg}from"@vkontakte/videoplayer-shared/es2015";var be=(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:dg(t)}return a},Xs=(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:dg(e)}};var k=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as H$,Subject as Js,merge as pg}from"@vkontakte/videoplayer-shared/es2015";var N=class{constructor(e){this.transitionStarted$=new Js;this.transitionEnded$=new Js;this.transitionUpdated$=new Js;this.forceChanged$=new Js;this.stateChangeStarted$=pg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=pg(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,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||H$(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 j$}from"@vkontakte/videoplayer-shared/es2015";var hg=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return j$(a)}};import{assertNever as Yr,assertNonNullable as cr,debounce as mg,ErrorCategory as fg,fromEvent as dr,isNonNullable as bg,map as gg,merge as vg,observableFrom as Q$,Subject as G$,Subscription as el,timeout as W$,getHighestQuality as Y$}from"@vkontakte/videoplayer-shared/es2015";var z$=5,K$=5,X$=500,Sg=7e3,Fi=class{constructor(e){this.subscription=new el;this.loadMediaTimeoutSubscription=new el;this.videoState=new N("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yr(e)}break}default:Yr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(hg(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new el;this.subscription.add(e),this.subscription.add(vg(this.videoState.stateChangeStarted$.pipe(gg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(gg(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 G$;e.add(i.pipe(mg(X$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>z$)&&i.next(o),s=o})),e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<K$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Yr(n)}}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=vg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Q$(["init"])).pipe(mg(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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];cr(c);let d=Y$(Object.keys(c));cr(d);let p=c[d];cr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];cr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];cr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];cr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];cr(c),r=be(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:fg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return bg(o)&&(n.metadata.title=o),bg(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let 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(W$(Sg).subscribe(()=>s(`timeout(${Sg})`)))});(0,yg.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:fg.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var El=B(Fe(),1);import{clearVideoElement as Ig}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as J$}from"@vkontakte/videoplayer-shared/es2015";var Tg=a=>{try{a.pause(),a.playbackRate=0,J$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as Z$,Subscription as eR}from"@vkontakte/videoplayer-shared/es2015";var tl=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)}},rl=window.WeakMap?new WeakMap:new tl,il=window.WeakMap?new WeakMap:new Map,tR=(a,e=20)=>{let t=0;return Z$(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},we=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?Ig(r):(r=document.createElement("video"),a.appendChild(r)),rl.set(r,i);let s=new eR;return s.add(tR(r,e)),il.set(r,s),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},ke=a=>{let e=il.get(a);e==null||e.unsubscribe(),il.delete(a);let t=rl.get(a);rl.delete(a),t?Ig(a):Tg(a)};var sl=B(zr(),1);import{assertNonNullable as qi,isNonNullable as ut,isNullable as lR,fromEvent as Kr,merge as $g,observableFrom as Rg,filterChanged as Lg,map as Ui,Subject as Mg,Subscription as cR,ValueSubject as dR,ErrorCategory as pR}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as al,isNullable as oR,Subscription as uR}from"@vkontakte/videoplayer-shared/es2015";var Zs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=oR(i),l=new uR;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>Zs(e,()=>a.loop,r=>{al(r)&&(a.loop=r)},{onError:t}),Ae=(a,e,t,r)=>Zs(e,()=>({muted:a.muted,volume:a.volume}),i=>{al(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}),qe=(a,e,t,r)=>Zs(e,()=>a.playbackRate,i=>{al(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ct=Zs;var hR=a=>["__",a.language,a.label].join("|"),mR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},nl=class a{constructor(e){this.available$=new Mg;this.current$=new dR(void 0);this.error$=new Mg;this.subscription=new cR;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:pR.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ct(t.internalTextTracks,()=>(0,sl.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ct(t.externalTextTracks,()=>(0,sl.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ct(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Ct(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qi(this.video);let{textTracks:e}=this.video;this.subscription.add(Kr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add($g(Kr(e,"addtrack"),Kr(e,"removetrack"),Rg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Lg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add($g(Kr(e,"change"),Rg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ui(r=>r&&this.htmlTextTrackToITextTrack(r).id),Lg()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(Kr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Kr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;ut(t.align)&&(i.align=t.align),ut(t.position)&&(i.position=t.position),ut(t.size)&&(i.size=t.size),ut(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){qi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:hR(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){qi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(lR(e)||!mR(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){qi(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){qi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ue=nl;var pr=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Dg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ol=a=>{let e=Dg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Cg=a=>{let e=Dg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as Vt,merge as ll,filterChanged as ER,isNonNullable as Hg,Subject as xR,filter as ji,mapTo as cl,combine as PR,once as wR,throttle as kR,ErrorCategory as AR,ValueSubject as jg}from"@vkontakte/videoplayer-shared/es2015";var fR=3,Vg=(a,e,t=fR)=>{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 en=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,r=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,i=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||r||n||u||l||i||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let r=t[1],i=parseInt(r,10);if(isNaN(i))return;this._safariVersion=i}catch(e){console.error(e)}}};var Og=B(Fe(),1);var Hi=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var tn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Og.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Hi()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return E(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,r=/iphone/i.test(e)?"iPhone":void 0,i=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||r||i||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let r=t[1].replace(/_/g,".");if(!r)return;let i=parseFloat(r);if(isNaN(i))return;this._iosVersion=i}catch(e){console.error(e)}}};var rn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(r){console.error(r)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(r){console.error(r)}}};var Ze=()=>window.ManagedMediaSource||window.MediaSource,an=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_g=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Bg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var bR=document.createElement("video"),gR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',vR='video/mp4; codecs="hev1.1.6.L93.B0"',Ng='video/webm; codecs="vp09.00.10.08"',Fg='video/webm; codecs="av01.0.00M.08"',SR='audio/mp4; codecs="mp4a.40.2"',yR='audio/webm; codecs="opus"',qg,TR=()=>E(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:Fg})})),window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:Ng})}))]);qg={DASH_WEBM_AV1:e,DASH_WEBM:t}});TR().catch(a=>{console.log(bR),console.error(a)});var sn=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return qg}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,r,i,s,n,o,u,l,c,d,p,h,m,b,g,v,S,T,I;this._video=document.createElement("video");try{this._protocols={mms:an(),mse:_g(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(i=(r=this._video).canPlayType)!=null&&i.call(r,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let y=!!((c=(l=Ze())==null?void 0:l.isTypeSupported)!=null&&c.call(l,gR)),$=!!((p=(d=Ze())==null?void 0:d.isTypeSupported)!=null&&p.call(d,vR)),C=!!((m=(h=Ze())==null?void 0:h.isTypeSupported)!=null&&m.call(h,SR));this._codecs={h264:y,h265:$,vp9:!!((g=(b=Ze())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Ng)),av1:!!((S=(v=Ze())==null?void 0:v.isTypeSupported)!=null&&S.call(v,Fg)),aac:C,opus:!!((I=(T=Ze())==null?void 0:T.isTypeSupported)!=null&&I.call(T,yR)),mpeg:(y||$)&&C},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(y){console.error(y)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Ug="audio/mpeg",nn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,r,i;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Ug))},this._codecs={mp3:!!((i=(r=Ze())==null?void 0:r.isTypeSupported)!=null&&i.call(r,Ug))}}catch(s){console.error(s)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as IR}from"@vkontakte/videoplayer-shared/es2015";var ul=class{constructor(){this.isInited$=new IR(!1);this._displayChecker=new rn,this._deviceChecker=new tn(this._displayChecker),this._browserChecker=new en,this._videoChecker=new sn(this._deviceChecker,this._browserChecker),this._audioChecker=new nn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return E(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},H=new ul;var Re=a=>{let e=L=>$e(a,L).pipe(cl(void 0)),r=ll(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(L=>$e(a,L))).pipe(Vt(L=>L.type==="ended"?a.readyState<2:a.readyState<3),ER()),i=ll($e(a,"progress"),$e(a,"timeupdate")).pipe(Vt(()=>Vg(a.buffered,a.currentTime))),s=H.browser.isSafari?PR({play:e("play").pipe(wR()),playing:e("playing")}).pipe(cl(void 0)):e("playing"),n=$e(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=$e(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=$e(a,"error").pipe(ji(()=>!!(a.error||a.played.length)),Vt(()=>{var O;let L=a.error;return{id:L?`MediaError#${L.code}`:"HtmlVideoError",category:AR.VIDEO_PIPELINE,message:L?L.message:"Error event from HTML video element",thrown:(O=a.error)!=null?O:void 0}})),l=$e(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new xR,d=.3,p;l.subscribe(L=>{a.loop&&Hg(p)&&Hg(L)&&p>=a.duration-d&&L<=d&&c.next(p),p=L});let h=e("pause").pipe(ji(()=>!a.error&&p!==a.duration)),m=$e(a,"enterpictureinpicture"),b=$e(a,"leavepictureinpicture"),g=new jg(Cg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new jg(ol(a));$e(a,"fullscreenchange").pipe(Vt(()=>ol(a))).subscribe(v);let T=.1,I=1e3,y=$e(a,"timeupdate").pipe(ji(L=>a.duration-a.currentTime<T)),$=ll(y.pipe(ji(L=>!a.loop)),$e(a,"ended")).pipe(kR(I),cl(void 0)),C=y.pipe(ji(L=>a.loop));return{playing$:s,pause$:h,canplay$:e("canplay"),ended$:$,looped$:c,loopExpected$:C,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:$e(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as Ot}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Ot.Q_144P;case"lowest":return Ot.Q_240P;case"low":return Ot.Q_360P;case"sd":case"medium":return Ot.Q_480P;case"hd":case"high":return Ot.Q_720P;case"fullhd":case"full":return Ot.Q_1080P;case"quadhd":case"quad":return Ot.Q_1440P;case"ultrahd":case"ultra":return Ot.Q_2160P}};var Nt=B(Bt(),1),nv=B(Fe(),1),ln=B(Br(),1);import{isNonNullable as Ee,isNullable as rv,now as ov,isHigher as iv,isHigherOrEqual as ml,isInvariantQuality as av,isLowerOrEqual as fl,videoSizeToQuality as NR,assertNotEmptyArray as uv,assertNonNullable as FR}from"@vkontakte/videoplayer-shared/es2015";var dl=!1,bt={},Xg=a=>{dl=a},Jg=()=>{bt={}},Zg=a=>{a(bt)},Qi=(a,e)=>{var t;dl&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var r,i;if(!dl)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};import{isHigher as _R,isHigherOrEqual as GN,isLower as ev,isLowerOrEqual as WN,isNonNullable as on,isNullable as BR,videoHeightToQuality as un}from"@vkontakte/videoplayer-shared/es2015";function pl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function hl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&pl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Gi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return BR(a)||on(a.min)&&on(a.max)&&ev(a.max,a.min)||on(a.min)&&e&&_R(a.min,e)||on(a.max)&&t&&ev(a.max,t)}function tv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Gi({limits:{max:a!=null&&a.max?un(a.max):void 0,min:a!=null&&a.min?un(a.min):void 0},highestAvailableQuality:e?un(e):void 0,lowestAvailableQuality:t?un(t):void 0})}var qR=new Ie("best_bitrate"),lv=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var bl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ov()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},cv='Assertion "ABR Tracks is empty array" failed',cn=(a,e,t,r)=>{var u;let i=[...e].sort(bl(1)),s=[...t].sort(bl(1)),n=s.filter(l=>Ee(l.bitrate)&&Ee(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,nv.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},sv=a=>"quality"in a,dv=(a,e,t,r)=>{var n;let i=Ee((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&Ee(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&ov()-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=sv(o)?"video":"audio",l=sv(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
9
|
`}),o}return r==null||r.recordSwitch(t),t},UR=(a,e)=>Math.log(e)/Math.log(a),HR=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&H.display.pixelRatio){let i=H.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(i-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=UR(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return hl({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Ft=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{var z,q,Z,A,D;uv(a,cv);let{containerSizeFactor:b,containerSizeLimit:g}=HR({container:e,tuning:r,limits:i}),v=r.considerPlaybackRate&&Ee(o)?o:1,S=a.filter(x=>!av(x.quality)).sort((x,U)=>iv(x.quality,U.quality)?-1:1),T=(z=(0,Nt.default)(S,-1))==null?void 0:z.quality,I=(q=(0,Nt.default)(S,0))==null?void 0:q.quality,y=Gi({limits:i,lowestAvailableQuality:T,highestAvailableQuality:I}),$=v*lv(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),C={},O=S.filter(x=>{let U=!0;if(g)if(x.size)U=x.size.width<=g.width&&x.size.height<=g.height;else{let Qe=g&&NR(g);U=Qe?fl(x.quality,Qe):!0}if(!U)return C[x.quality]="FitsContainer",!1;let _=h||t,je=Ee(_)&&isFinite(_)&&Ee(x.bitrate)?_-s>=x.bitrate*$:!0,Et=hl({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:i})&&(i==null?void 0:i.min)===x.quality;if(!je&&!Et)return C[x.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&Ee(r.minBufferToSwitchUp)&&u&&!av(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&iv(x.quality,u.quality))return C[x.quality]="Buffer",!1;if(!!d&&ml(x.quality,d)&&!Et)return C[x.quality]="DroppedFramesLimit",!1;if(!!p&&ml(x.quality,p)&&!Et)return C[x.quality]="StallsLimit",!1;let ye=y||(rv(i==null?void 0:i.max)||fl(x.quality,i.max))&&(rv(i==null?void 0:i.min)||ml(x.quality,i.min)),Pe=Ee(c)&&!c?fl(x.quality,r.backgroundVideoQualityLimit):!0;return!ye||!Pe?(C[x.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&qR.next(O.bitrate);let Q=(Z=O!=null?O:(0,Nt.default)(S,-1))!=null?Z:a[0],G=l==null?void 0:l.last,R=dv(r,m,Q,l);return Ee(l)&&R.quality!==(G==null?void 0:G.quality)&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
@@ -123,4 +123,4 @@ void main(void) {
|
|
|
123
123
|
}
|
|
124
124
|
`;var Cn=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 Mn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Dn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),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(Hy,this.gl.VERTEX_SHADER),r=this.createShader(jy,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 UD,now as Qy,Subscription as HD,filter as jD,combine as Gy,ValueSubject as oc,isNonNullable as QD,debounce as GD}from"@vkontakte/videoplayer-shared/es2015";var uc=class{constructor(){this.isSeeked$=new oc(!1);this.isBuffering$=new oc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new HD;this.severeStallOccurred$=new oc(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(Gy({isBuffering:this.isBuffering$.pipe(GD(this.qualityLimitsOnStall.stallDurationToBeCount)),isSeeked:this.isSeeked$}).pipe(jD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(Gy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if(UD(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Qy(),d=i&&this.currentStallsCount>=i,p=r&&c-this.lastUniqueVideoTrackSelectedTimestamp>=r+o&&c-l>=r+o&&t>=r;(d||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,QD(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Qy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Wy=uc;import{combine as WD,map as YD,observeElementSize as zD,Subscription as KD,ValueSubject as lc,noop as XD}from"@vkontakte/videoplayer-shared/es2015";var Vn=class{constructor(){this.subscription=new KD;this.pipSize$=new lc(void 0);this.videoSize$=new lc(void 0);this.elementSize$=new lc(void 0);this.pictureInPictureWindowRemoveEventListener=XD}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(zD(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(WD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(YD(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Sr=class{constructor(e){this.subscription=new iC;this.videoState=new N("stopped");this.droppedFramesManager=new mn;this.stallsManager=new Wy;this.elementSizeManager=new Vn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Wi;this.audioTrackSwitchHistory=new Wi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(i.position,i.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return ZD(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Cn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((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 Ue(e.source.url),this.params=e,this.video=we(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ln({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Re(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Yy.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(zy(l=>!!l.length),Xy()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(cc(l=>l.to.state!=="none"),qa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(qa()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$,looped$:r.looped$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(zy(Ky),Xy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(cc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(r.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),i)),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Ae(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(eC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(jl(h));let m=[];for(let b of h.representations){let g=gy(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Ql(p));let h=[];for(let m of p.representations){let b=by(M(P({},m),{streamId:p.id}));b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=vy(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i)),this.subscription.add(On(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,rC(this.video,"progress")).subscribe(()=>E(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Jy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===p.id});Ky(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,g)}}),i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(qa()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Ql(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(jl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(cc(({to:l})=>l==="ready"),qa());this.subscription.add(On(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,dc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(On(o,this.player.state$.stateChangeEnded$,dc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=On(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dc(["init"])).pipe(tC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var C,L,O,Q,G,R,z,q,Z,A,D,x,U;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(C=e.videoTrack.getState())==null?void 0:C.id,n=[...this.videoTracksMap.keys()].find(({id:_})=>_===i),o=t.currentVideoTrack$.getValue(),u=((Q=(O=e.videoStream.getState())!=null?O:n&&((L=this.videoTracksMap.get(n))==null?void 0:L.stream))!=null?Q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:_})=>_===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Jr(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(p,h||1/0),1),b=(G=e.audioStream.getState())!=null?G:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(R=[...this.audioStreamsMap.keys()].find(({id:_})=>_===(b==null?void 0:b.id)))!=null?R:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let _=cn(n,c,(z=this.audioStreamsMap.get(g))!=null?z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(q=_==null?void 0:_.bitrate)!=null?q:-1/0)}if(o){let _=cn(o,c,(Z=this.audioStreamsMap.get(g))!=null?Z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(A=_==null?void 0:_.bitrate)!=null?A:-1/0)}}let S=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),T=r?S!=null?S:n:n!=null?n:S,I=g&&pv(T,c,(D=this.audioStreamsMap.get(g))!=null?D:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),y=(x=this.videoTracksMap.get(T))==null?void 0:x.representation,$=I&&((U=this.audioTracksMap.get(I))==null?void 0:U.representation);if(y&&$)return[y,$];if(y&&!$&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Yy.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),ke(this.video),this.tracer.end()}};var Ua=class extends Sr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as _n,merge as Zy,filter as aC,filterChanged as sC,isNullable as pc,map as eT,ValueSubject as hc}from"@vkontakte/videoplayer-shared/es2015";var Ha=class extends Sr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:r,desiredState:i,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(r.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new hc(1);s(r.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe(eT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(_n({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(eT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(_n({position:t.position$,liveStreamStatus:this.player.liveStreamStatus$}).subscribe(({position:o,liveStreamStatus:u})=>t.isLiveEnded$.next(u!=="active"&&o===0))).add(_n({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Zy(r.playbackRateState$,new hc(1))}).pipe(aC(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||pc(l)||(e=o-l)})).add(_n({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Zy(r.playbackRateState$,new hc(1))}).pipe(sC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||pc(o)||pc(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Sy(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(r).then(()=>{this.params.output.position$.next(e/1e3)})}};var rT=B(Ks(),1);import{assertNever as ja,assertNonNullable as tT,debounce as nC,ErrorCategory as Bn,filter as oC,isNonNullable as uC,isNullable as lC,map as Nn,merge as cC,Observable as dC,observableFrom as pC,Subscription as hC,videoSizeToQuality as mC}from"@vkontakte/videoplayer-shared/es2015";var tt={};var ui=(a,e)=>new dC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Qa=class{constructor(e){this.subscription=new hC;this.videoState=new N("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ja(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ja(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ja(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ja(e)}break;default:ja(t)}};this.textTracksManager=new Ue(e.source.url),this.video=we(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ke(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Bn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rT.default)(import("hls.js").then(i=>{e||(tt.Hls=i.default,tt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){tT(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){tT(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Bn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Re(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,r)),this.subscription.add(Ae(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,e.playbackRate,i.playbackRateState$,r)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Nn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ui(this.hls,tt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Bn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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(ui(this.hls,tt.Events.MANIFEST_PARSED).pipe(Nn(({levels:l})=>l.reduce((c,d)=>{var S,T;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(T=_t((S=d.attrs.QUALITY)!=null?S:""))!=null?T:mC({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(ui(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ui(this.hls,tt.Events.LEVEL_LOADING).pipe(Nn(({url:l})=>de(l))),t.hostname$),s(ui(this.hls,tt.Events.FRAG_CHANGED),l=>{var p,h,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Ct(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ui(this.hls,tt.Events.LEVEL_SWITCHED).pipe(Nn(({level:l})=>n(this.hls.levels[l])));o.pipe(oC(uC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ct(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(lC(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=cC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pC(["init"])).pipe(nC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return E(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bn.DOM,thrown:t})))||(this.videoState.setState("paused"),k(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"),k(this.params.desiredState.playbackState,"stopped",!0)}};var iT="X-Playback-Duration",mc=a=>E(void 0,null,function*(){var i;let e=yield lt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(iT)?parseInt(e.headers.get(iT),10):void 0});import{assertNever as PC,combine as wC,debounce as kC,ErrorCategory as Un,filter as AC,filterChanged as $C,isNonNullable as nT,isNullable as Hn,map as oT,merge as RC,observableFrom as LC,Subscription as MC,ValueSubject as gc,VideoQuality as DC}from"@vkontakte/videoplayer-shared/es2015";var bc=B(mu(),1);import{videoSizeToQuality as fC,getExponentialDelay as bC}from"@vkontakte/videoplayer-shared/es2015";var gC=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=fC({width:t,height:r})}return e!=null?e:null},vC=(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,bc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=gC(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,T]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));S&&T&&(g={width:S,height:T})}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,bc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),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}},SC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),fc=0,aT=(i,...s)=>E(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield lt(a,r)).text();fc+=1;try{let{qualityManifests:u,textTracks:l}=vC(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(fc<=t.manifestRetryMaxCount)return yield SC(bC(fc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),aT(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Fn=aT;import{isNonNullable as yC,Subscription as TC,throttle as IC,ValueSubject as sT,Subject as EC,ErrorCategory as xC}from"@vkontakte/videoplayer-shared/es2015";var qn=class{constructor(e,t,r,i,s){this.subscription=new TC;this.abortControllers={destroy:new ge,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new sT(null);this.getCurrentTime$=new sT(null);this.error$=new EC;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(IC(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return E(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return E(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return E(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield lt(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(yC(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([M(P({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return E(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ge;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return E(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:xC.WTF,thrown:t,message:e})}};var Ga=class{constructor(e){this.subscription=new MC;this.videoState=new N("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new gc([]);this.liveOffset=new pr;this.manifestStartTime$=new gc(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"),k(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"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(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"&&k(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"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return PC(t)}};var r;this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:DC.INVARIANT,url:this.params.source.url};let t=(i,s)=>Fn(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 qn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ue(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:Un.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:Un.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(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new gc((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:Un.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Re(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(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe($C(),oT(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&&nT(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(de(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(wC({startTime:this.manifestStartTime$.pipe(AC(nT)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(oT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=RC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,LC(["init"])).pipe(kC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Hn(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=be(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),mc(n).then(c=>{var d;if(!Hn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Hn(p)||!isFinite(p))&<(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();mc(g).then(v=>{Hn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Un.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=be(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 CC,debounce as VC,ErrorCategory as vc,fromEvent as Sc,isNonNullable as OC,isNullable as _C,map as uT,merge as lT,observableFrom as cT,Subscription as BC,ValueSubject as NC,VideoQuality as FC}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new BC;this.videoState=new N("stopped");this.manifests$=new NC([]);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"),k(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"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return CC(t)}};this.textTracksManager=new Ue(e.source.url),this.params=e,this.video=we(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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Fn(be(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:vc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&(!i||!i.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:vc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Re(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(uT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&OC(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(de(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(uT(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)),!H.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(lT(Sc(o,"addtrack"),Sc(o,"removetrack"),Sc(o,"change"),cT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=lT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,cT(["init"])).pipe(VC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var s,n;let e=this.selectManifest();if(_C(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var hT=B(Br(),1),yc=B(zr(),1),mT=B(Bt(),1);import{assertNever as qC,assertNonNullable as dT,debounce as UC,ErrorCategory as pT,isHigherOrEqual as HC,isLowerOrEqual as jC,isNonNullable as QC,merge as GC,observableFrom as WC,Subscription as YC,map as zC}from"@vkontakte/videoplayer-shared/es2015";var Ya=class{constructor(e){this.subscription=new YC;this.videoState=new N("stopped");this.trackUrls={};this.textTracksManager=new Ue;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return qC(e)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),(0,hT.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,yc.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:pT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Re(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(zC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&QC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=GC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,WC(["init"])).pipe(UC(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),ke(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;dT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];dT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Da(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(de(t))}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let p=Ft(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,yc.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Gi({limits:e,lowestAvailableQuality:(c=(0,mT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?jC(i,e.max):!0,u=e.min?HC(i,e.min):!0;o&&u||r(e)}};import{assertNever as bT,debounce as ZC,merge as gT,observableFrom as e0,Subscription as t0,map as vT,ValueSubject as r0,ErrorCategory as Ic,VideoQuality as i0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as KC}from"@vkontakte/videoplayer-shared/es2015";var fT=["stun:videostun.mycdn.me:80"],XC=1e3,JC=3,Tc=()=>null,jn=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}}handleUpdateMessage(e){return E(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return E(this,null,function*(){try{let e={iceServers:[{urls:fT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return E(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return E(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:KC.WTF,message:e.message})}onPeerConnectionStream(e){return E(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return E(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),XC)}normalizeOptions(e={}){let t={stunServerList:fT,maxRetryNumber:JC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var za=class{constructor(e){this.videoState=new N("stopped");this.maxSeekBackTime$=new r0(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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return bT(e)}};this.subscription=new t0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=we(e.container,e.tuning),this.liveStreamClient=new jn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ke(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ic.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};gT(this.videoState.stateChangeStarted$.pipe(vT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(vT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Re(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(He(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ae(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 bT(n.to)}},r)).add(gT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,e0(["init"])).pipe(ZC(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:i0.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ic.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ic.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ka=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ja,assertNonNullable as Qt,ErrorCategory as Qn,filter as xT,isNonNullable as PT,isNullable as c0,map as d0,merge as p0,once as h0,Subject as he,Subscription as wT,ValueSubject as F,flattenObject as kT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as a0,map as ST,Subscription as s0,Subject as n0}from"@vkontakte/videoplayer-shared/es2015";var yT=a=>new a0(e=>{let t=new s0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(ST(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(ST(({type:l})=>l!==void 0)),n=new n0,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 o0,Subscription as u0,combine as l0,filter as IT,once as ET}from"@vkontakte/videoplayer-shared/es2015";function TT(){return new(window.AudioContext||window.webkitAudioContext)}var Xa=class Xa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ge;this.subscriptions=new u0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(IT(s=>!!s.type),ET()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){H.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(l0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(IT(({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}initAudioContextOnce(e){return E(this,null,function*(){let{volumeMultiplier:t}=this,r=TT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Xa.errorId,category:o0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Xa.errorId} exception`,thrown:e})}};Xa.errorId="VolumeMultiplierManager";var li=Xa;var m0={chunkDuration:5e3,maxParallelRequests:5},Za=class{constructor(e){this.current$=new F({type:void 0});this.providerError$=new he;this.noAvailableProvidersError$=new he;this.volumeMultiplierError$=new he;this.providerOutput={position$:new F(0),duration$:new F(1/0),volume$:new F({muted:!1,volume:1}),availableVideoStreams$:new F([]),currentVideoStream$:new F(void 0),availableVideoTracks$:new F([]),currentVideoTrack$:new F(void 0),availableAudioStreams$:new F([]),currentAudioStream$:new F(void 0),availableAudioTracks$:new F([]),currentVideoSegmentLength$:new F(0),currentAudioSegmentLength$:new F(0),isAudioAvailable$:new F(!0),autoVideoTrackLimitingAvailable$:new F(!1),autoVideoTrackLimits$:new F(void 0),currentBuffer$:new F(void 0),isBuffering$:new F(!0),error$:new he,fetcherError$:new he,fetcherRecoverableError$:new he,warning$:new he,willSeekEvent$:new he,soundProhibitedEvent$:new he,seekedEvent$:new he,loopedEvent$:new he,endedEvent$:new he,firstBytesEvent$:new he,loadedMetadataEvent$:new he,firstFrameEvent$:new he,canplay$:new he,isLive$:new F(void 0),isLiveEnded$:new F(null),isLowLatency$:new F(!1),canChangePlaybackSpeed$:new F(!0),liveTime$:new F(void 0),liveBufferTime$:new F(void 0),liveLatency$:new F(void 0),severeStallOccurred$:new he,availableTextTracks$:new F([]),currentTextTrack$:new F(void 0),hostname$:new F(void 0),httpConnectionType$:new F(void 0),httpConnectionReused$:new F(void 0),inPiP$:new F(!1),inFullscreen$:new F(!1),element$:new F(void 0),elementVisible$:new F(!0),availableSources$:new F(void 0),is3DVideo$:new F(!1),playbackState$:new F(""),getCurrentTime$:new F(null)};this.subscription=new wT;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Oy([...By(this.params.tuning),..._y(this.params.tuning)],this.params.tuning).filter(l=>PT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Ec.default)(i,l)),...t.filter(l=>(0,Ec.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",kT(s)),this.screenFormatsIterator=new Ka(s);let n=[...tc(!0),...tc(!1)];this.chromecastFormatsIterator=new Ka(n.filter(l=>PT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&li.isSupported()&&(this.volumeMultiplierManager=new li(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(c0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Qn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ja(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Qt(o),new Ua(M(P({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ha(M(P({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Qt(o),H.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Wa(M(P({},n),{source:o})):new Qa(M(P({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ga(M(P({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ya(M(P({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new $v(M(P({},n),{source:o,config:M(P({},m0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new za({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ja(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Qt(o),new Fi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Ja(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ja(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Ja(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return M(P({},e),{url:r(e.url)})}return(0,$T.default)((0,AT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new wT,t=!1,r=0;return e.add(p0(this.providerOutput.error$.pipe(xT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),yT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(d0(i=>({id:`ProviderHangup:${i}`,category:Qn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(xT(({to:s})=>s==="playing"),h0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Qn.NETWORK,u=i.category===Qn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=M(P({},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",kT(n))})),e}};import{fromEvent as Gn,once as f0,combine as b0,Subscription as RT,ValueSubject as xc,map as g0,filter as v0,isNonNullable as Wn,now as Be,safeStorage as Pc}from"@vkontakte/videoplayer-shared/es2015";var S0=5e3,LT="one_video_throughput",MT="one_video_rtt",Tt=window.navigator.connection,DT=()=>{let a=Tt==null?void 0:Tt.downlink;if(Wn(a)&&a!==10)return a*1e3},CT=()=>{let a=Tt==null?void 0:Tt.rtt;if(Wn(a)&&a!==3e3)return a},VT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},wc=class a{constructor(e){this.subscription=new RT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(LT)||(e.useBrowserEstimation?DT():void 0)||S0,r=(s=(i=a.load(MT))!=null?i:e.useBrowserEstimation?CT():void 0)!=null?s:0;if(this.throughput$=new xc(t),this.rtt$=new xc(r),this.rttAdjustedThroughput$=new xc(VT(t,r,e.rttPenaltyRequestSize)),this.throughput=gr.getSmoothedValue(t,-1,e),this.rtt=gr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=DT();u&&this.throughput.next(u);let l=CT();Wn(l)&&this.rtt.next(l)};Tt&&"onchange"in Tt&&this.subscription.add(Gn(Tt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Pc.set(LT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Pc.set(MT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(b0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(g0(({throughput:n,rtt:o})=>VT(n,o,e.rttPenaltyRequestSize)),v0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Be(),i=new RT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Gn(e,"progress").pipe(f0()).subscribe(s=>{t=s.loaded,r=Be()}));break;case 1:case 0:i.add(Gn(e,"loadstart").subscribe(()=>{t=0,r=Be()}));break}i.add(Gn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Be(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Be(),n=0,o=Be(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>E(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Be()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Be();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Be()}else n+=d.byteLength;o=Be()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Be()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Be()-o,this.concurrentDownloads.size),n=0,o=Be());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Pc.get(e);if(Wn(t))return(r=parseInt(t,10))!=null?r:void 0}},OT=wc;import{fillWithDefault as y0,VideoQuality as Yn}from"@vkontakte/videoplayer-shared/es2015";var _T={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Yn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Yn.Q_720P,trafficSavingLimit:Yn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Yn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1},BT=a=>{var e;return M(P({},y0(a,_T)),{configName:[...(e=a.configName)!=null?e:[],..._T.configName]})};import{assertNonNullable as zn,combine as It,ErrorCategory as Kn,filter as V,filterChanged as X,fromEvent as Ac,isNonNullable as k0,isNullable as A0,Logger as $0,map as Y,mapTo as UT,merge as Gt,now as Xn,once as j,Subject as J,Subscription as HT,tap as $c,ValueSubject as w,isHigher as R0,isInvariantQuality as jT,flattenObject as Wt,throttle as Rc,getTraceSubscriptionMethod as QT,Tracer as L0,InternalsExposure as M0}from"@vkontakte/videoplayer-shared/es2015";import{merge as T0,map as I0,filter as NT,isNonNullable as E0}from"@vkontakte/videoplayer-shared/es2015";var kc=({seekState:a,position$:e})=>T0(a.stateChangeEnded$.pipe(I0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),NT(E0)),e.pipe(NT(()=>a.getState().state==="none")));import{assertNonNullable as x0}from"@vkontakte/videoplayer-shared/es2015";var FT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return x0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as P0,once as w0}from"@vkontakte/videoplayer-shared/es2015";var qT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(P0(i=>i.length>0),w0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Jn=class{constructor(e={configName:[]},t=L0.createRootTracer(!1)){this.subscription=new HT;this.logger=new $0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new w(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInited=new w(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new N("stopped"),seekState:new N({state:"none"}),volume:new N({volume:1,muted:!1}),videoTrack:new N(void 0),videoStream:new N(void 0),audioStream:new N(void 0),autoVideoTrackSwitching:new N(!0),autoVideoTrackLimits:new N({}),isLooped:new N(!1),isLowLatency:new N(!1),playbackRate:new N(1),externalTextTracks:new N([]),internalTextTracks:new N([]),currentTextTrack:new N(void 0),textTrackCuesSettings:new N({}),cameraOrientation:new N({x:0,y:0})};this.info={playbackState$:new w(void 0),position$:new w(0),duration$:new w(1/0),muted$:new w(!1),volume$:new w(1),availableVideoStreams$:new w([]),currentVideoStream$:new w(void 0),availableQualities$:new w([]),availableQualitiesFps$:new w({}),currentQuality$:new w(void 0),isAutoQualityEnabled$:new w(!0),autoQualityLimitingAvailable$:new w(!1),autoQualityLimits$:new w({}),predefinedQualityLimitType$:new w("unknown"),availableAudioStreams$:new w([]),currentAudioStream$:new w(void 0),availableAudioTracks$:new w([]),isAudioAvailable$:new w(!0),currentPlaybackRate$:new w(1),currentBuffer$:new w({start:0,end:0}),isBuffering$:new w(!0),isStalled$:new w(!1),isEnded$:new w(!1),isLooped$:new w(!1),isLive$:new w(void 0),isLiveEnded$:new w(null),canChangePlaybackSpeed$:new w(void 0),atLiveEdge$:new w(void 0),atLiveDurationEdge$:new w(void 0),liveTime$:new w(void 0),liveBufferTime$:new w(void 0),liveLatency$:new w(void 0),currentFormat$:new w(void 0),availableTextTracks$:new w([]),currentTextTrack$:new w(void 0),throughputEstimation$:new w(void 0),rttEstimation$:new w(void 0),videoBitrate$:new w(void 0),hostname$:new w(void 0),httpConnectionType$:new w(void 0),httpConnectionReused$:new w(void 0),surface$:new w("none"),chromecastState$:new w("NOT_AVAILABLE"),chromecastDeviceName$:new w(void 0),intrinsicVideoSize$:new w(void 0),availableSources$:new w(void 0),is3DVideo$:new w(!1),currentVideoSegmentLength$:new w(0),currentAudioSegmentLength$:new w(0)};this.events={inited$:new J,ready$:new J,started$:new J,playing$:new J,paused$:new J,stopped$:new J,willStart$:new J,willResume$:new J,willPause$:new J,willStop$:new J,willDestruct$:new J,watchCoverageRecord$:new J,watchCoverageLive$:new J,managedError$:new J,fatalError$:new J,fetcherRecoverableError$:new J,ended$:new J,looped$:new J,seeked$:new J,willSeek$:new J,autoplaySoundProhibited$:new J,firstBytes$:new J,loadedMetadata$:new J,firstFrame$:new J,canplay$:new J,log$:new J,fetcherError$:new J,severeStallOccured$:new J};this.experimental={element$:new w(void 0),tuningConfigName$:new w([]),enableDebugTelemetry$:new w(!1),dumpTelemetry:Zg,getCurrentTime$:new w(null)};if(this.initLogs(),this.tuning=BT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Is({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new OT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new M0("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,GT.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:Kn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i;this.config=e,(i=this.internalsExposure)==null||i.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u,l,c;let o=e,{container:s}=o,n=gd(o,["container"]);this.tracer.log("initVideo",Wt(n)),this.domContainer=FT(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Za({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],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(),this.playerInited.next(!0)},r=()=>{this.tuning.asyncResolveClientChecker?H.isInited$.pipe(V(s=>!!s),j()).subscribe(()=>{console.log("Core SDK async start"),t()}):t()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Ac(document,"visibilitychange").pipe(j()).subscribe(r)):r(),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(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;e>=r&&!i&&(s=r-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{let r=this.desiredState.volume,i=this.info.muted$.getValue(),s=t!=null?t:this.tuning.isAudioDisabled||i;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:s}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):r.startTransitionTo({volume:e,muted:s})}),this}setMuted(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let t=this.tuning.isAudioDisabled||e,r=this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:t,volume:r,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:r,muted:t})}),this}setVideoStream(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{zn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(V(r=>r.length>0),j()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Wt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}this.setAutoQualityLimits(i)}),this}setPlaybackRate(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{var r;zn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)}),this}setExternalTextTracks(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>P({type:"external"},t)))}),this}selectTextTrack(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{var t;qT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",P({},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.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{let r=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{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})}}),this}holdCamera(){return this.playerInited.pipe(V(e=>e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(A0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return k0(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Y(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(pl({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(V(({from:e})=>e==="stopped"),j()).subscribe(()=>{this.initedAt=Xn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Wt(n)),n.state==="requested"?this.desiredState.seekState.setState(M(P({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Kn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(j()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Wt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Y(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Y(n=>n.destination),X()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(It({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Y(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>jT(u)?1:jT(l)?-1:R0(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(X()).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(X((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(X((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(X()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(X()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(X()).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(Y(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe($c(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(It({hasLiveOffsetByPaused:Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Y(n=>n.to),X(),Y(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(It({atLiveEdge:It({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:kc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Y(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),X(),$c(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Y(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(It({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Y(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),X(),$c(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Y(n=>n.muted),X()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Y(n=>n.volume),X()).subscribe(this.info.volume$)).add(kc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Gt(e.providerOutput.endedEvent$.pipe(UT(!0)),e.providerOutput.seekedEvent$.pipe(UT(!1))).pipe(X()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(Y(n=>({id:n?`No${n}`:"NoProviders",category:Kn.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(j(),Y(n=>n!=null?n:Xn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(j(),Y(()=>Xn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(j(),Y(()=>Xn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new w(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new w(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(V(({to:n})=>n==="playing"),j()).subscribe(()=>r.next(!1)));let i=0,s=Gt(e.providerOutput.isBuffering$,t,r).pipe(Y(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),X());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Gt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Gt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Y(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 HT;this.subscription.add(t),this.subscription.add(e.current$.pipe(X((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(V(r=>r.length>0),j()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t;this.wasSetStartedQuality=!0;let r=(i=this.explicitInitialQuality)!=null?i:this.info.currentQuality$.getValue();r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Gt(this.desiredState.videoTrack.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Y(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;zn(this.providerContainer),zn(e),Jg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Xg(r)),this.providerContainer.current$.subscribe(({type:r})=>Qi("provider",r)),e.duration$.subscribe(r=>Qi("duration",r)),e.availableVideoTracks$.pipe(V(r=>!!r.length),j()).subscribe(r=>Qi("tracks",r)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe(Y(r=>r==null?void 0:r.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(r=>this.subscription.add(r)),Qi("codecs",H.video.supportedCodecs)}initTracerSubscription(){let e=QT(this.tracer.log.bind(this.tracer)),t=QT(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(X()).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(It({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(V(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),X((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(V(r=>r>0),X()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(V(r=>r>0),X()).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(It({currentBuffer:this.info.currentBuffer$.pipe(V(r=>r.end>0),X((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(X())}).pipe(Rc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(X()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(X()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(X()).subscribe(e("canChangePlaybackSpeed"))).add(It({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(V(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Rc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(X(),V(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(X(),V(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(X()).subscribe(e("muted"))).add(this.info.volume$.pipe(X()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(X(),V(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(It({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(V(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Rc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(X(),V(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=()=>E(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Kn.DOM,message:String(i)})})});this.subscription.add(Gt(Ac(document,"visibilitychange"),Ac(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Wt({quality:t,availableTracks:Wt(e),track:Wt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ji()}};import{Subscription as JK,Observable as ZK,Subject as e6,ValueSubject as t6,VideoQuality as r6}from"@vkontakte/videoplayer-shared/es2015";var i6=`@vkontakte/videoplayer-core@${vd}`;export{fs as ChromecastState,no as HttpConnectionType,ZK as Observable,De as PlaybackState,Jn as Player,bs as PredefinedQualityLimits,i6 as SDK_VERSION,e6 as Subject,JK as Subscription,oo as Surface,vd as VERSION,t6 as ValueSubject,pt as VideoFormat,r6 as VideoQuality,H as clientChecker,Hi as isMobile};
|
|
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(yC(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([M(P({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return E(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ge;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return E(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:xC.WTF,thrown:t,message:e})}};var Ga=class{constructor(e){this.subscription=new MC;this.videoState=new N("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new gc([]);this.liveOffset=new pr;this.manifestStartTime$=new gc(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"),k(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"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(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"&&k(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"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return PC(t)}};var r;this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:DC.INVARIANT,url:this.params.source.url};let t=(i,s)=>Fn(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 qn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ue(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:Un.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:Un.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(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new gc((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:Un.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Re(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(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe($C(),oT(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&&nT(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(de(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(wC({startTime:this.manifestStartTime$.pipe(AC(nT)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(oT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=RC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,LC(["init"])).pipe(kC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Hn(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=be(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),mc(n).then(c=>{var d;if(!Hn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Hn(p)||!isFinite(p))&<(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();mc(g).then(v=>{Hn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Un.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=be(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 CC,debounce as VC,ErrorCategory as vc,fromEvent as Sc,isNonNullable as OC,isNullable as _C,map as uT,merge as lT,observableFrom as cT,Subscription as BC,ValueSubject as NC,VideoQuality as FC}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new BC;this.videoState=new N("stopped");this.manifests$=new NC([]);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"),k(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"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return CC(t)}};this.textTracksManager=new Ue(e.source.url),this.params=e,this.video=we(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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Fn(be(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:vc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&(!i||!i.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:vc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Re(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(uT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&OC(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(de(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(uT(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)),!H.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(lT(Sc(o,"addtrack"),Sc(o,"removetrack"),Sc(o,"change"),cT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=lT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,cT(["init"])).pipe(VC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var s,n;let e=this.selectManifest();if(_C(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var hT=B(Br(),1),yc=B(zr(),1),mT=B(Bt(),1);import{assertNever as qC,assertNonNullable as dT,debounce as UC,ErrorCategory as pT,isHigherOrEqual as HC,isLowerOrEqual as jC,isNonNullable as QC,merge as GC,observableFrom as WC,Subscription as YC,map as zC}from"@vkontakte/videoplayer-shared/es2015";var Ya=class{constructor(e){this.subscription=new YC;this.videoState=new N("stopped");this.trackUrls={};this.textTracksManager=new Ue;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return qC(e)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),(0,hT.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,yc.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:pT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Re(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(zC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&QC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=GC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,WC(["init"])).pipe(UC(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),ke(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;dT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];dT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Da(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(de(t))}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let p=Ft(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,yc.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Gi({limits:e,lowestAvailableQuality:(c=(0,mT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?jC(i,e.max):!0,u=e.min?HC(i,e.min):!0;o&&u||r(e)}};import{assertNever as bT,debounce as ZC,merge as gT,observableFrom as e0,Subscription as t0,map as vT,ValueSubject as r0,ErrorCategory as Ic,VideoQuality as i0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as KC}from"@vkontakte/videoplayer-shared/es2015";var fT=["stun:videostun.mycdn.me:80"],XC=1e3,JC=3,Tc=()=>null,jn=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}}handleUpdateMessage(e){return E(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return E(this,null,function*(){try{let e={iceServers:[{urls:fT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return E(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return E(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:KC.WTF,message:e.message})}onPeerConnectionStream(e){return E(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return E(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),XC)}normalizeOptions(e={}){let t={stunServerList:fT,maxRetryNumber:JC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var za=class{constructor(e){this.videoState=new N("stopped");this.maxSeekBackTime$=new r0(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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return bT(e)}};this.subscription=new t0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=we(e.container,e.tuning),this.liveStreamClient=new jn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ke(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ic.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};gT(this.videoState.stateChangeStarted$.pipe(vT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(vT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Re(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(He(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ae(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 bT(n.to)}},r)).add(gT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,e0(["init"])).pipe(ZC(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:i0.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ic.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ic.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ka=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ja,assertNonNullable as Qt,ErrorCategory as Qn,filter as xT,isNonNullable as PT,isNullable as c0,map as d0,merge as p0,once as h0,Subject as he,Subscription as wT,ValueSubject as F,flattenObject as kT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as a0,map as ST,Subscription as s0,Subject as n0}from"@vkontakte/videoplayer-shared/es2015";var yT=a=>new a0(e=>{let t=new s0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(ST(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(ST(({type:l})=>l!==void 0)),n=new n0,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 o0,Subscription as u0,combine as l0,filter as IT,once as ET}from"@vkontakte/videoplayer-shared/es2015";function TT(){return new(window.AudioContext||window.webkitAudioContext)}var Xa=class Xa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ge;this.subscriptions=new u0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(IT(s=>!!s.type),ET()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){H.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(l0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(IT(({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}initAudioContextOnce(e){return E(this,null,function*(){let{volumeMultiplier:t}=this,r=TT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Xa.errorId,category:o0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Xa.errorId} exception`,thrown:e})}};Xa.errorId="VolumeMultiplierManager";var li=Xa;var m0={chunkDuration:5e3,maxParallelRequests:5},Za=class{constructor(e){this.current$=new F({type:void 0});this.providerError$=new he;this.noAvailableProvidersError$=new he;this.volumeMultiplierError$=new he;this.providerOutput={position$:new F(0),duration$:new F(1/0),volume$:new F({muted:!1,volume:1}),availableVideoStreams$:new F([]),currentVideoStream$:new F(void 0),availableVideoTracks$:new F([]),currentVideoTrack$:new F(void 0),availableAudioStreams$:new F([]),currentAudioStream$:new F(void 0),availableAudioTracks$:new F([]),currentVideoSegmentLength$:new F(0),currentAudioSegmentLength$:new F(0),isAudioAvailable$:new F(!0),autoVideoTrackLimitingAvailable$:new F(!1),autoVideoTrackLimits$:new F(void 0),currentBuffer$:new F(void 0),isBuffering$:new F(!0),error$:new he,fetcherError$:new he,fetcherRecoverableError$:new he,warning$:new he,willSeekEvent$:new he,soundProhibitedEvent$:new he,seekedEvent$:new he,loopedEvent$:new he,endedEvent$:new he,firstBytesEvent$:new he,loadedMetadataEvent$:new he,firstFrameEvent$:new he,canplay$:new he,isLive$:new F(void 0),isLiveEnded$:new F(null),isLowLatency$:new F(!1),canChangePlaybackSpeed$:new F(!0),liveTime$:new F(void 0),liveBufferTime$:new F(void 0),liveLatency$:new F(void 0),severeStallOccurred$:new he,availableTextTracks$:new F([]),currentTextTrack$:new F(void 0),hostname$:new F(void 0),httpConnectionType$:new F(void 0),httpConnectionReused$:new F(void 0),inPiP$:new F(!1),inFullscreen$:new F(!1),element$:new F(void 0),elementVisible$:new F(!0),availableSources$:new F(void 0),is3DVideo$:new F(!1),playbackState$:new F(""),getCurrentTime$:new F(null)};this.subscription=new wT;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Oy([...By(this.params.tuning),..._y(this.params.tuning)],this.params.tuning).filter(l=>PT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Ec.default)(i,l)),...t.filter(l=>(0,Ec.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",kT(s)),this.screenFormatsIterator=new Ka(s);let n=[...tc(!0),...tc(!1)];this.chromecastFormatsIterator=new Ka(n.filter(l=>PT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&li.isSupported()&&(this.volumeMultiplierManager=new li(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(c0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Qn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ja(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Qt(o),new Ua(M(P({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ha(M(P({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Qt(o),H.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Wa(M(P({},n),{source:o})):new Qa(M(P({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ga(M(P({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ya(M(P({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new $v(M(P({},n),{source:o,config:M(P({},m0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new za({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ja(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Qt(o),new Fi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Ja(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ja(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Ja(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return M(P({},e),{url:r(e.url)})}return(0,$T.default)((0,AT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new wT,t=!1,r=0;return e.add(p0(this.providerOutput.error$.pipe(xT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),yT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(d0(i=>({id:`ProviderHangup:${i}`,category:Qn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(xT(({to:s})=>s==="playing"),h0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Qn.NETWORK,u=i.category===Qn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=M(P({},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",kT(n))})),e}};import{fromEvent as Gn,once as f0,combine as b0,Subscription as RT,ValueSubject as xc,map as g0,filter as v0,isNonNullable as Wn,now as Be,safeStorage as Pc}from"@vkontakte/videoplayer-shared/es2015";var S0=5e3,LT="one_video_throughput",MT="one_video_rtt",Tt=window.navigator.connection,DT=()=>{let a=Tt==null?void 0:Tt.downlink;if(Wn(a)&&a!==10)return a*1e3},CT=()=>{let a=Tt==null?void 0:Tt.rtt;if(Wn(a)&&a!==3e3)return a},VT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},wc=class a{constructor(e){this.subscription=new RT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(LT)||(e.useBrowserEstimation?DT():void 0)||S0,r=(s=(i=a.load(MT))!=null?i:e.useBrowserEstimation?CT():void 0)!=null?s:0;if(this.throughput$=new xc(t),this.rtt$=new xc(r),this.rttAdjustedThroughput$=new xc(VT(t,r,e.rttPenaltyRequestSize)),this.throughput=gr.getSmoothedValue(t,-1,e),this.rtt=gr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=DT();u&&this.throughput.next(u);let l=CT();Wn(l)&&this.rtt.next(l)};Tt&&"onchange"in Tt&&this.subscription.add(Gn(Tt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Pc.set(LT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Pc.set(MT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(b0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(g0(({throughput:n,rtt:o})=>VT(n,o,e.rttPenaltyRequestSize)),v0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Be(),i=new RT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Gn(e,"progress").pipe(f0()).subscribe(s=>{t=s.loaded,r=Be()}));break;case 1:case 0:i.add(Gn(e,"loadstart").subscribe(()=>{t=0,r=Be()}));break}i.add(Gn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Be(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Be(),n=0,o=Be(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>E(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Be()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Be();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Be()}else n+=d.byteLength;o=Be()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Be()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Be()-o,this.concurrentDownloads.size),n=0,o=Be());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Pc.get(e);if(Wn(t))return(r=parseInt(t,10))!=null?r:void 0}},OT=wc;import{fillWithDefault as y0,VideoQuality as Yn}from"@vkontakte/videoplayer-shared/es2015";var _T={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Yn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Yn.Q_720P,trafficSavingLimit:Yn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Yn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1},BT=a=>{var e;return M(P({},y0(a,_T)),{configName:[...(e=a.configName)!=null?e:[],..._T.configName]})};import{assertNonNullable as zn,combine as It,ErrorCategory as Kn,filter as V,filterChanged as X,fromEvent as Ac,isNonNullable as k0,isNullable as A0,Logger as $0,map as Y,mapTo as UT,merge as Gt,now as Xn,once as j,Subject as J,Subscription as HT,tap as $c,ValueSubject as w,isHigher as R0,isInvariantQuality as jT,flattenObject as Wt,throttle as Rc,getTraceSubscriptionMethod as QT,Tracer as L0,InternalsExposure as M0}from"@vkontakte/videoplayer-shared/es2015";import{merge as T0,map as I0,filter as NT,isNonNullable as E0}from"@vkontakte/videoplayer-shared/es2015";var kc=({seekState:a,position$:e})=>T0(a.stateChangeEnded$.pipe(I0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),NT(E0)),e.pipe(NT(()=>a.getState().state==="none")));import{assertNonNullable as x0}from"@vkontakte/videoplayer-shared/es2015";var FT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return x0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as P0,once as w0}from"@vkontakte/videoplayer-shared/es2015";var qT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(P0(i=>i.length>0),w0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Jn=class{constructor(e={configName:[]},t=L0.createRootTracer(!1)){this.subscription=new HT;this.logger=new $0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new w(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInited=new w(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new N("stopped"),seekState:new N({state:"none"}),volume:new N({volume:1,muted:!1}),videoTrack:new N(void 0),videoStream:new N(void 0),audioStream:new N(void 0),autoVideoTrackSwitching:new N(!0),autoVideoTrackLimits:new N({}),isLooped:new N(!1),isLowLatency:new N(!1),playbackRate:new N(1),externalTextTracks:new N([]),internalTextTracks:new N([]),currentTextTrack:new N(void 0),textTrackCuesSettings:new N({}),cameraOrientation:new N({x:0,y:0})};this.info={playbackState$:new w(void 0),position$:new w(0),duration$:new w(1/0),muted$:new w(!1),volume$:new w(1),availableVideoStreams$:new w([]),currentVideoStream$:new w(void 0),availableQualities$:new w([]),availableQualitiesFps$:new w({}),currentQuality$:new w(void 0),isAutoQualityEnabled$:new w(!0),autoQualityLimitingAvailable$:new w(!1),autoQualityLimits$:new w({}),predefinedQualityLimitType$:new w("unknown"),availableAudioStreams$:new w([]),currentAudioStream$:new w(void 0),availableAudioTracks$:new w([]),isAudioAvailable$:new w(!0),currentPlaybackRate$:new w(1),currentBuffer$:new w({start:0,end:0}),isBuffering$:new w(!0),isStalled$:new w(!1),isEnded$:new w(!1),isLooped$:new w(!1),isLive$:new w(void 0),isLiveEnded$:new w(null),canChangePlaybackSpeed$:new w(void 0),atLiveEdge$:new w(void 0),atLiveDurationEdge$:new w(void 0),liveTime$:new w(void 0),liveBufferTime$:new w(void 0),liveLatency$:new w(void 0),currentFormat$:new w(void 0),availableTextTracks$:new w([]),currentTextTrack$:new w(void 0),throughputEstimation$:new w(void 0),rttEstimation$:new w(void 0),videoBitrate$:new w(void 0),hostname$:new w(void 0),httpConnectionType$:new w(void 0),httpConnectionReused$:new w(void 0),surface$:new w("none"),chromecastState$:new w("NOT_AVAILABLE"),chromecastDeviceName$:new w(void 0),intrinsicVideoSize$:new w(void 0),availableSources$:new w(void 0),is3DVideo$:new w(!1),currentVideoSegmentLength$:new w(0),currentAudioSegmentLength$:new w(0)};this.events={inited$:new J,ready$:new J,started$:new J,playing$:new J,paused$:new J,stopped$:new J,willStart$:new J,willResume$:new J,willPause$:new J,willStop$:new J,willDestruct$:new J,watchCoverageRecord$:new J,watchCoverageLive$:new J,managedError$:new J,fatalError$:new J,fetcherRecoverableError$:new J,ended$:new J,looped$:new J,seeked$:new J,willSeek$:new J,autoplaySoundProhibited$:new J,firstBytes$:new J,loadedMetadata$:new J,firstFrame$:new J,canplay$:new J,log$:new J,fetcherError$:new J,severeStallOccured$:new J};this.experimental={element$:new w(void 0),tuningConfigName$:new w([]),enableDebugTelemetry$:new w(!1),dumpTelemetry:Zg,getCurrentTime$:new w(null)};if(this.initLogs(),this.tuning=BT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Is({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new OT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new M0("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,GT.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:Kn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i;this.config=e,(i=this.internalsExposure)==null||i.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u,l,c;let o=e,{container:s}=o,n=gd(o,["container"]);this.tracer.log("initVideo",Wt(n)),this.domContainer=FT(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Za({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],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(),this.playerInited.next(!0)},r=()=>{this.tuning.asyncResolveClientChecker?H.isInited$.pipe(V(s=>!!s),j()).subscribe(()=>{console.log("Core SDK async start"),t()}):t()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Ac(document,"visibilitychange").pipe(j()).subscribe(r)):r(),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(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;e>=r&&!i&&(s=r-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{let r=this.desiredState.volume,i=this.info.muted$.getValue(),s=t!=null?t:this.tuning.isAudioDisabled||i;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:s}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):r.startTransitionTo({volume:e,muted:s})}),this}setMuted(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let t=this.tuning.isAudioDisabled||e,r=this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:t,volume:r,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:r,muted:t})}),this}setVideoStream(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{zn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(V(r=>r.length>0),j()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Wt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}this.setAutoQualityLimits(i)}),this}setPlaybackRate(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{var r;zn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)}),this}setExternalTextTracks(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>P({type:"external"},t)))}),this}selectTextTrack(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{var t;qT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",P({},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.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{let r=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.playerInited.pipe(V(t=>!!t),j()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.playerInited.pipe(V(r=>!!r),j()).subscribe(()=>{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})}}),this}holdCamera(){return this.playerInited.pipe(V(e=>e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.playerInited.pipe(V(e=>!!e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(A0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return k0(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Y(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Y(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(pl({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(V(({from:e})=>e==="stopped"),j()).subscribe(()=>{this.initedAt=Xn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Wt(n)),n.state==="requested"?this.desiredState.seekState.setState(M(P({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Kn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(j()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Wt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Y(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Y(n=>n.destination),X()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(It({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Y(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>jT(u)?1:jT(l)?-1:R0(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(X()).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(X((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(X((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(X()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(X()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(X()).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(Y(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe($c(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(It({hasLiveOffsetByPaused:Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Y(n=>n.to),X(),Y(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(It({atLiveEdge:It({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:kc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Y(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),X(),$c(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Y(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(It({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Y(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),X(),$c(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Y(n=>n.muted),X()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Y(n=>n.volume),X()).subscribe(this.info.volume$)).add(kc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Gt(e.providerOutput.endedEvent$.pipe(UT(!0)),e.providerOutput.seekedEvent$.pipe(UT(!1))).pipe(X()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(Y(n=>({id:n?`No${n}`:"NoProviders",category:Kn.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(j(),Y(n=>n!=null?n:Xn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(j(),Y(()=>Xn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(j(),Y(()=>Xn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new w(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new w(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(V(({to:n})=>n==="playing"),j()).subscribe(()=>r.next(!1)));let i=0,s=Gt(e.providerOutput.isBuffering$,t,r).pipe(Y(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),X());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Gt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Gt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Y(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 HT;this.subscription.add(t),this.subscription.add(e.current$.pipe(X((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(V(r=>r.length>0),j()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t;this.wasSetStartedQuality=!0;let r=(i=this.explicitInitialQuality)!=null?i:this.info.currentQuality$.getValue();r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Gt(this.desiredState.videoTrack.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Y(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Y(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Y(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;zn(this.providerContainer),zn(e),Jg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Xg(r)),this.providerContainer.current$.subscribe(({type:r})=>Qi("provider",r)),e.duration$.subscribe(r=>Qi("duration",r)),e.availableVideoTracks$.pipe(V(r=>!!r.length),j()).subscribe(r=>Qi("tracks",r)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe(Y(r=>r==null?void 0:r.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(r=>this.subscription.add(r)),Qi("codecs",H.video.supportedCodecs)}initTracerSubscription(){let e=QT(this.tracer.log.bind(this.tracer)),t=QT(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(X()).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(It({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(V(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),X((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(V(r=>r>0),X()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(V(r=>r>0),X()).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(It({currentBuffer:this.info.currentBuffer$.pipe(V(r=>r.end>0),X((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(X())}).pipe(Rc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(X()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(X()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(X()).subscribe(e("canChangePlaybackSpeed"))).add(It({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(V(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Rc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(X(),V(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(X(),V(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(X()).subscribe(e("muted"))).add(this.info.volume$.pipe(X()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(X(),V(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(It({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(V(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Rc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(X(),V(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=()=>E(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Kn.DOM,message:String(i)})})});this.subscription.add(Gt(Ac(document,"visibilitychange"),Ac(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Wt({quality:t,availableTracks:Wt(e),track:Wt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ji()}};import{Subscription as J6,Observable as Z6,Subject as e8,ValueSubject as t8,VideoQuality as r8}from"@vkontakte/videoplayer-shared/es2015";var i8=`@vkontakte/videoplayer-core@${vd}`;export{fs as ChromecastState,no as HttpConnectionType,Z6 as Observable,De as PlaybackState,Jn as Player,bs as PredefinedQualityLimits,i8 as SDK_VERSION,e8 as Subject,J6 as Subscription,oo as Surface,vd as VERSION,t8 as ValueSubject,pt as VideoFormat,r8 as VideoQuality,H as clientChecker,Hi as isMobile};
|