@vkontakte/videoplayer-core 2.0.150 → 2.0.151-dev.6dd94264.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 +16 -16
- package/es2015.esm.js +16 -16
- package/es2018.cjs +20 -20
- package/es2018.esm.js +16 -16
- package/es2024.cjs +20 -20
- package/es2024.esm.js +20 -20
- package/esnext.cjs +20 -20
- package/esnext.esm.js +20 -20
- package/evergreen.esm.js +19 -19
- package/package.json +2 -2
- package/types/index.d.ts +1 -0
- package/types/providers/utils/videoStreamRepresentaionsFilter.d.ts +4 -0
- package/types/utils/tuningConfig.d.ts +1 -0
package/es2015.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.151-dev.6dd94264.0
|
|
3
|
+
* Mon, 02 Feb 2026 12:05:46 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-151/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var IT=Object.create;var sa=Object.defineProperty,ET=Object.defineProperties,wT=Object.getOwnPropertyDescriptor,xT=Object.getOwnPropertyDescriptors,PT=Object.getOwnPropertyNames,Zs=Object.getOwnPropertySymbols,Od=Object.getPrototypeOf,Jo=Object.prototype.hasOwnProperty,Nd=Object.prototype.propertyIsEnumerable,kT=Reflect.get;var AT=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var Vt=Math.pow,_d=(a,e,t)=>e in a?sa(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,M=(a,e)=>{for(var t in e||(e={}))Jo.call(e,t)&&_d(a,t,e[t]);if(Zs)for(var t of Zs(e))Nd.call(e,t)&&_d(a,t,e[t]);return a},U=(a,e)=>ET(a,xT(e));var fi=(a,e)=>{var t={};for(var i in a)Jo.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&Zs)for(var i of Zs(a))e.indexOf(i)<0&&Nd.call(a,i)&&(t[i]=a[i]);return t};var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),RT=(a,e)=>{for(var t in e)sa(a,t,{get:e[t],enumerable:!0})},Fd=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of PT(e))!Jo.call(a,r)&&r!==t&&sa(a,r,{get:()=>e[r],enumerable:!(i=wT(e,r))||i.enumerable});return a};var Z=(a,e,t)=>(t=a!=null?IT(Od(a)):{},Fd(e||!a||!a.__esModule?sa(t,"default",{value:a,enumerable:!0}):t,a)),MT=a=>Fd(sa({},"__esModule",{value:!0}),a);var qd=(a,e,t)=>kT(Od(a),t,e);var I=(a,e,t)=>new Promise((i,r)=>{var s=u=>{try{o(t.next(u))}catch(c){r(c)}},n=u=>{try{o(t.throw(u))}catch(c){r(c)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),_t=function(a,e){this[0]=a,this[1]=e},he=(a,e,t)=>{var i=(n,o,u,c)=>{try{var d=t[n](o),l=(o=d.value)instanceof _t,p=d.done;Promise.resolve(l?o[0]:o).then(h=>l?i(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,c):u({value:h,done:p})).catch(h=>i("throw",h,u,c))}catch(h){c(h)}},r=n=>s[n]=o=>new Promise((u,c)=>i(n,o,u,c)),s={};return t=t.apply(a,e),s[AT("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var Ae=g((eu,Ud)=>{"use strict";var oa=function(a){return a&&a.Math===Math&&a};Ud.exports=oa(typeof globalThis=="object"&&globalThis)||oa(typeof window=="object"&&window)||oa(typeof self=="object"&&self)||oa(typeof global=="object"&&global)||oa(typeof eu=="object"&&eu)||function(){return this}()||Function("return this")()});var Le=g((xC,jd)=>{"use strict";jd.exports=function(a){try{return!!a()}catch(e){return!0}}});var ua=g((PC,Hd)=>{"use strict";var $T=Le();Hd.exports=!$T(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var tu=g((kC,Gd)=>{"use strict";var CT=ua(),zd=Function.prototype,Qd=zd.apply,Wd=zd.call;Gd.exports=typeof Reflect=="object"&&Reflect.apply||(CT?Wd.bind(Qd):function(){return Wd.apply(Qd,arguments)})});var Be=g((AC,Xd)=>{"use strict";var Yd=ua(),Kd=Function.prototype,iu=Kd.call,DT=Yd&&Kd.bind.bind(iu,iu);Xd.exports=Yd?DT:function(a){return function(){return iu.apply(a,arguments)}}});var qi=g((RC,Zd)=>{"use strict";var Jd=Be(),LT=Jd({}.toString),BT=Jd("".slice);Zd.exports=function(a){return BT(LT(a),8,-1)}});var ru=g((MC,ep)=>{"use strict";var VT=qi(),_T=Be();ep.exports=function(a){if(VT(a)==="Function")return _T(a)}});var Re=g(($C,tp)=>{"use strict";var au=typeof document=="object"&&document.all;tp.exports=typeof au=="undefined"&&au!==void 0?function(a){return typeof a=="function"||a===au}:function(a){return typeof a=="function"}});var ut=g((CC,ip)=>{"use strict";var OT=Le();ip.exports=!OT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ct=g((DC,rp)=>{"use strict";var NT=ua(),rn=Function.prototype.call;rp.exports=NT?rn.bind(rn):function(){return rn.apply(rn,arguments)}});var su=g(np=>{"use strict";var ap={}.propertyIsEnumerable,sp=Object.getOwnPropertyDescriptor,FT=sp&&!ap.call({1:2},1);np.f=FT?function(e){var t=sp(this,e);return!!t&&t.enumerable}:ap});var ca=g((BC,op)=>{"use strict";op.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var cp=g((VC,up)=>{"use strict";var qT=Be(),UT=Le(),jT=qi(),nu=Object,HT=qT("".split);up.exports=UT(function(){return!nu("z").propertyIsEnumerable(0)})?function(a){return jT(a)==="String"?HT(a,""):nu(a)}:nu});var la=g((_C,lp)=>{"use strict";lp.exports=function(a){return a==null}});var mi=g((OC,dp)=>{"use strict";var QT=la(),WT=TypeError;dp.exports=function(a){if(QT(a))throw new WT("Can't call method on "+a);return a}});var Ui=g((NC,pp)=>{"use strict";var zT=cp(),GT=mi();pp.exports=function(a){return zT(GT(a))}});var Je=g((FC,hp)=>{"use strict";var YT=Re();hp.exports=function(a){return typeof a=="object"?a!==null:YT(a)}});var ji=g((qC,fp)=>{"use strict";fp.exports={}});var Xt=g((UC,bp)=>{"use strict";var ou=ji(),uu=Ae(),KT=Re(),mp=function(a){return KT(a)?a:void 0};bp.exports=function(a,e){return arguments.length<2?mp(ou[a])||mp(uu[a]):ou[a]&&ou[a][e]||uu[a]&&uu[a][e]}});var da=g((jC,gp)=>{"use strict";var XT=Be();gp.exports=XT({}.isPrototypeOf)});var Hi=g((HC,yp)=>{"use strict";var JT=Ae(),vp=JT.navigator,Sp=vp&&vp.userAgent;yp.exports=Sp?String(Sp):""});var lu=g((QC,Pp)=>{"use strict";var xp=Ae(),cu=Hi(),Tp=xp.process,Ip=xp.Deno,Ep=Tp&&Tp.versions||Ip&&Ip.version,wp=Ep&&Ep.v8,xt,an;wp&&(xt=wp.split("."),an=xt[0]>0&&xt[0]<4?1:+(xt[0]+xt[1]));!an&&cu&&(xt=cu.match(/Edge\/(\d+)/),(!xt||xt[1]>=74)&&(xt=cu.match(/Chrome\/(\d+)/),xt&&(an=+xt[1])));Pp.exports=an});var du=g((WC,Ap)=>{"use strict";var kp=lu(),ZT=Le(),eI=Ae(),tI=eI.String;Ap.exports=!!Object.getOwnPropertySymbols&&!ZT(function(){var a=Symbol("symbol detection");return!tI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&kp&&kp<41})});var pu=g((zC,Rp)=>{"use strict";var iI=du();Rp.exports=iI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var hu=g((GC,Mp)=>{"use strict";var rI=Xt(),aI=Re(),sI=da(),nI=pu(),oI=Object;Mp.exports=nI?function(a){return typeof a=="symbol"}:function(a){var e=rI("Symbol");return aI(e)&&sI(e.prototype,oI(a))}});var pa=g((YC,$p)=>{"use strict";var uI=String;$p.exports=function(a){try{return uI(a)}catch(e){return"Object"}}});var Nt=g((KC,Cp)=>{"use strict";var cI=Re(),lI=pa(),dI=TypeError;Cp.exports=function(a){if(cI(a))return a;throw new dI(lI(a)+" is not a function")}});var ha=g((XC,Dp)=>{"use strict";var pI=Nt(),hI=la();Dp.exports=function(a,e){var t=a[e];return hI(t)?void 0:pI(t)}});var Bp=g((JC,Lp)=>{"use strict";var fu=ct(),mu=Re(),bu=Je(),fI=TypeError;Lp.exports=function(a,e){var t,i;if(e==="string"&&mu(t=a.toString)&&!bu(i=fu(t,a))||mu(t=a.valueOf)&&!bu(i=fu(t,a))||e!=="string"&&mu(t=a.toString)&&!bu(i=fu(t,a)))return i;throw new fI("Can't convert object to primitive value")}});var Pt=g((ZC,Vp)=>{"use strict";Vp.exports=!0});var Np=g((eD,Op)=>{"use strict";var _p=Ae(),mI=Object.defineProperty;Op.exports=function(a,e){try{mI(_p,a,{value:e,configurable:!0,writable:!0})}catch(t){_p[a]=e}return e}});var fa=g((tD,Up)=>{"use strict";var bI=Pt(),gI=Ae(),vI=Np(),Fp="__core-js_shared__",qp=Up.exports=gI[Fp]||vI(Fp,{});(qp.versions||(qp.versions=[])).push({version:"3.43.0",mode:bI?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var gu=g((iD,Hp)=>{"use strict";var jp=fa();Hp.exports=function(a,e){return jp[a]||(jp[a]=e||{})}});var yr=g((rD,Qp)=>{"use strict";var SI=mi(),yI=Object;Qp.exports=function(a){return yI(SI(a))}});var kt=g((aD,Wp)=>{"use strict";var TI=Be(),II=yr(),EI=TI({}.hasOwnProperty);Wp.exports=Object.hasOwn||function(e,t){return EI(II(e),t)}});var vu=g((sD,zp)=>{"use strict";var wI=Be(),xI=0,PI=Math.random(),kI=wI(1.1.toString);zp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+kI(++xI+PI,36)}});var je=g((nD,Yp)=>{"use strict";var AI=Ae(),RI=gu(),Gp=kt(),MI=vu(),$I=du(),CI=pu(),Tr=AI.Symbol,Su=RI("wks"),DI=CI?Tr.for||Tr:Tr&&Tr.withoutSetter||MI;Yp.exports=function(a){return Gp(Su,a)||(Su[a]=$I&&Gp(Tr,a)?Tr[a]:DI("Symbol."+a)),Su[a]}});var Zp=g((oD,Jp)=>{"use strict";var LI=ct(),Kp=Je(),Xp=hu(),BI=ha(),VI=Bp(),_I=je(),OI=TypeError,NI=_I("toPrimitive");Jp.exports=function(a,e){if(!Kp(a)||Xp(a))return a;var t=BI(a,NI),i;if(t){if(e===void 0&&(e="default"),i=LI(t,a,e),!Kp(i)||Xp(i))return i;throw new OI("Can't convert object to primitive value")}return e===void 0&&(e="number"),VI(a,e)}});var yu=g((uD,eh)=>{"use strict";var FI=Zp(),qI=hu();eh.exports=function(a){var e=FI(a,"string");return qI(e)?e:e+""}});var sn=g((cD,ih)=>{"use strict";var UI=Ae(),th=Je(),Tu=UI.document,jI=th(Tu)&&th(Tu.createElement);ih.exports=function(a){return jI?Tu.createElement(a):{}}});var Iu=g((lD,rh)=>{"use strict";var HI=ut(),QI=Le(),WI=sn();rh.exports=!HI&&!QI(function(){return Object.defineProperty(WI("div"),"a",{get:function(){return 7}}).a!==7})});var nh=g(sh=>{"use strict";var zI=ut(),GI=ct(),YI=su(),KI=ca(),XI=Ui(),JI=yu(),ZI=kt(),eE=Iu(),ah=Object.getOwnPropertyDescriptor;sh.f=zI?ah:function(e,t){if(e=XI(e),t=JI(t),eE)try{return ah(e,t)}catch(i){}if(ZI(e,t))return KI(!GI(YI.f,e,t),e[t])}});var Eu=g((pD,oh)=>{"use strict";var tE=Le(),iE=Re(),rE=/#|\.prototype\./,ma=function(a,e){var t=sE[aE(a)];return t===oE?!0:t===nE?!1:iE(e)?tE(e):!!e},aE=ma.normalize=function(a){return String(a).replace(rE,".").toLowerCase()},sE=ma.data={},nE=ma.NATIVE="N",oE=ma.POLYFILL="P";oh.exports=ma});var Ir=g((hD,ch)=>{"use strict";var uh=ru(),uE=Nt(),cE=ua(),lE=uh(uh.bind);ch.exports=function(a,e){return uE(a),e===void 0?a:cE?lE(a,e):function(){return a.apply(e,arguments)}}});var wu=g((fD,lh)=>{"use strict";var dE=ut(),pE=Le();lh.exports=dE&&pE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ft=g((mD,dh)=>{"use strict";var hE=Je(),fE=String,mE=TypeError;dh.exports=function(a){if(hE(a))return a;throw new mE(fE(a)+" is not an object")}});var Qi=g(hh=>{"use strict";var bE=ut(),gE=Iu(),vE=wu(),nn=Ft(),ph=yu(),SE=TypeError,xu=Object.defineProperty,yE=Object.getOwnPropertyDescriptor,Pu="enumerable",ku="configurable",Au="writable";hh.f=bE?vE?function(e,t,i){if(nn(e),t=ph(t),nn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Au in i&&!i[Au]){var r=yE(e,t);r&&r[Au]&&(e[t]=i.value,i={configurable:ku in i?i[ku]:r[ku],enumerable:Pu in i?i[Pu]:r[Pu],writable:!1})}return xu(e,t,i)}:xu:function(e,t,i){if(nn(e),t=ph(t),nn(i),gE)try{return xu(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new SE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Er=g((gD,fh)=>{"use strict";var TE=ut(),IE=Qi(),EE=ca();fh.exports=TE?function(a,e,t){return IE.f(a,e,EE(1,t))}:function(a,e,t){return a[e]=t,a}});var $e=g((vD,bh)=>{"use strict";var ba=Ae(),wE=tu(),xE=ru(),PE=Re(),kE=nh().f,AE=Eu(),wr=ji(),RE=Ir(),xr=Er(),mh=kt();fa();var ME=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return wE(a,this,arguments)};return e.prototype=a.prototype,e};bh.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ba:r?ba[t]:ba[t]&&ba[t].prototype,o=i?wr:wr[t]||xr(wr,t,{})[t],u=o.prototype,c,d,l,p,h,m,b,S,v;for(p in e)c=AE(i?p:t+(r?".":"#")+p,a.forced),d=!c&&n&&mh(n,p),m=o[p],d&&(a.dontCallGetSet?(v=kE(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!c&&!s&&typeof m==typeof h)&&(a.bind&&d?S=RE(h,ba):a.wrap&&d?S=ME(h):s&&PE(h)?S=xE(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&xr(S,"sham",!0),xr(o,p,S),s&&(l=t+"Prototype",mh(wr,l)||xr(wr,l,{}),xr(wr[l],p,h),a.real&&u&&(c||!u[p])&&xr(u,p,h)))}});var on=g((SD,vh)=>{"use strict";var $E=gu(),CE=vu(),gh=$E("keys");vh.exports=function(a){return gh[a]||(gh[a]=CE(a))}});var yh=g((yD,Sh)=>{"use strict";var DE=Le();Sh.exports=!DE(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var un=g((TD,Ih)=>{"use strict";var LE=kt(),BE=Re(),VE=yr(),_E=on(),OE=yh(),Th=_E("IE_PROTO"),Ru=Object,NE=Ru.prototype;Ih.exports=OE?Ru.getPrototypeOf:function(a){var e=VE(a);if(LE(e,Th))return e[Th];var t=e.constructor;return BE(t)&&e instanceof t?t.prototype:e instanceof Ru?NE:null}});var wh=g((ID,Eh)=>{"use strict";var FE=Math.ceil,qE=Math.floor;Eh.exports=Math.trunc||function(e){var t=+e;return(t>0?qE:FE)(t)}});var ga=g((ED,xh)=>{"use strict";var UE=wh();xh.exports=function(a){var e=+a;return e!==e||e===0?0:UE(e)}});var kh=g((wD,Ph)=>{"use strict";var jE=ga(),HE=Math.max,QE=Math.min;Ph.exports=function(a,e){var t=jE(a);return t<0?HE(t+e,0):QE(t,e)}});var Mu=g((xD,Ah)=>{"use strict";var WE=ga(),zE=Math.min;Ah.exports=function(a){var e=WE(a);return e>0?zE(e,9007199254740991):0}});var Pr=g((PD,Rh)=>{"use strict";var GE=Mu();Rh.exports=function(a){return GE(a.length)}});var $u=g((kD,$h)=>{"use strict";var YE=Ui(),KE=kh(),XE=Pr(),Mh=function(a){return function(e,t,i){var r=YE(e),s=XE(r);if(s===0)return!a&&-1;var n=KE(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};$h.exports={includes:Mh(!0),indexOf:Mh(!1)}});var cn=g((AD,Ch)=>{"use strict";Ch.exports={}});var Bh=g((RD,Lh)=>{"use strict";var JE=Be(),Cu=kt(),ZE=Ui(),ew=$u().indexOf,tw=cn(),Dh=JE([].push);Lh.exports=function(a,e){var t=ZE(a),i=0,r=[],s;for(s in t)!Cu(tw,s)&&Cu(t,s)&&Dh(r,s);for(;e.length>i;)Cu(t,s=e[i++])&&(~ew(r,s)||Dh(r,s));return r}});var Du=g((MD,Vh)=>{"use strict";Vh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Lu=g(($D,_h)=>{"use strict";var iw=Bh(),rw=Du();_h.exports=Object.keys||function(e){return iw(e,rw)}});var Bu=g((CD,Uh)=>{"use strict";var Nh=ut(),aw=Le(),Fh=Be(),sw=un(),nw=Lu(),ow=Ui(),uw=su().f,qh=Fh(uw),cw=Fh([].push),lw=Nh&&aw(function(){var a=Object.create(null);return a[2]=2,!qh(a,2)}),Oh=function(a){return function(e){for(var t=ow(e),i=nw(t),r=lw&&sw(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Nh||(r?u in t:qh(t,u)))&&cw(o,a?[u,t[u]]:t[u]);return o}};Uh.exports={entries:Oh(!0),values:Oh(!1)}});var jh=g(()=>{"use strict";var dw=$e(),pw=Bu().values;dw({target:"Object",stat:!0},{values:function(e){return pw(e)}})});var Qh=g((BD,Hh)=>{"use strict";jh();var hw=ji();Hh.exports=hw.Object.values});var zh=g((VD,Wh)=>{"use strict";var fw=Qh();Wh.exports=fw});var Wi=g((_D,Gh)=>{"use strict";var mw=zh();Gh.exports=mw});var va=g((OD,Yh)=>{"use strict";Yh.exports=function(){}});var Kh=g(()=>{"use strict";var bw=$e(),gw=$u().includes,vw=Le(),Sw=va(),yw=vw(function(){return!Array(1).includes()});bw({target:"Array",proto:!0,forced:yw},{includes:function(e){return gw(this,e,arguments.length>1?arguments[1]:void 0)}});Sw("includes")});var bi=g((qD,Xh)=>{"use strict";var Tw=Xt();Xh.exports=Tw});var Zh=g((UD,Jh)=>{"use strict";Kh();var Iw=bi();Jh.exports=Iw("Array","includes")});var tf=g((jD,ef)=>{"use strict";var Ew=Zh();ef.exports=Ew});var Ze=g((HD,rf)=>{"use strict";var ww=tf();rf.exports=ww});var vf=g(()=>{"use strict";var Lw=$e(),Bw=Bu().entries;Lw({target:"Object",stat:!0},{entries:function(e){return Bw(e)}})});var yf=g((VB,Sf)=>{"use strict";vf();var Vw=ji();Sf.exports=Vw.Object.entries});var If=g((_B,Tf)=>{"use strict";var _w=yf();Tf.exports=_w});var Si=g((OB,Ef)=>{"use strict";var Ow=If();Ef.exports=Ow});var Gi=g((NB,wf)=>{"use strict";wf.exports={}});var kf=g((FB,Pf)=>{"use strict";var Nw=Ae(),Fw=Re(),xf=Nw.WeakMap;Pf.exports=Fw(xf)&&/native code/.test(String(xf))});var ju=g((qB,Mf)=>{"use strict";var qw=kf(),Rf=Ae(),Uw=Je(),jw=Er(),Fu=kt(),qu=fa(),Hw=on(),Qw=cn(),Af="Object already initialized",Uu=Rf.TypeError,Ww=Rf.WeakMap,En,Ea,wn,zw=function(a){return wn(a)?Ea(a):En(a,{})},Gw=function(a){return function(e){var t;if(!Uw(e)||(t=Ea(e)).type!==a)throw new Uu("Incompatible receiver, "+a+" required");return t}};qw||qu.state?(At=qu.state||(qu.state=new Ww),At.get=At.get,At.has=At.has,At.set=At.set,En=function(a,e){if(At.has(a))throw new Uu(Af);return e.facade=a,At.set(a,e),e},Ea=function(a){return At.get(a)||{}},wn=function(a){return At.has(a)}):(Yi=Hw("state"),Qw[Yi]=!0,En=function(a,e){if(Fu(a,Yi))throw new Uu(Af);return e.facade=a,jw(a,Yi,e),e},Ea=function(a){return Fu(a,Yi)?a[Yi]:{}},wn=function(a){return Fu(a,Yi)});var At,Yi;Mf.exports={set:En,get:Ea,has:wn,enforce:zw,getterFor:Gw}});var Wu=g((UB,Cf)=>{"use strict";var Hu=ut(),Yw=kt(),$f=Function.prototype,Kw=Hu&&Object.getOwnPropertyDescriptor,Qu=Yw($f,"name"),Xw=Qu&&function(){}.name==="something",Jw=Qu&&(!Hu||Hu&&Kw($f,"name").configurable);Cf.exports={EXISTS:Qu,PROPER:Xw,CONFIGURABLE:Jw}});var Lf=g(Df=>{"use strict";var Zw=ut(),ex=wu(),tx=Qi(),ix=Ft(),rx=Ui(),ax=Lu();Df.f=Zw&&!ex?Object.defineProperties:function(e,t){ix(e);for(var i=rx(t),r=ax(t),s=r.length,n=0,o;s>n;)tx.f(e,o=r[n++],i[o]);return e}});var zu=g((HB,Bf)=>{"use strict";var sx=Xt();Bf.exports=sx("document","documentElement")});var Xu=g((QB,Uf)=>{"use strict";var nx=Ft(),ox=Lf(),Vf=Du(),ux=cn(),cx=zu(),lx=sn(),dx=on(),_f=">",Of="<",Yu="prototype",Ku="script",Ff=dx("IE_PROTO"),Gu=function(){},qf=function(a){return Of+Ku+_f+a+Of+"/"+Ku+_f},Nf=function(a){a.write(qf("")),a.close();var e=a.parentWindow.Object;return a=null,e},px=function(){var a=lx("iframe"),e="java"+Ku+":",t;return a.style.display="none",cx.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(qf("document.F=Object")),t.close(),t.F},xn,Pn=function(){try{xn=new ActiveXObject("htmlfile")}catch(e){}Pn=typeof document!="undefined"?document.domain&&xn?Nf(xn):px():Nf(xn);for(var a=Vf.length;a--;)delete Pn[Yu][Vf[a]];return Pn()};ux[Ff]=!0;Uf.exports=Object.create||function(e,t){var i;return e!==null?(Gu[Yu]=nx(e),i=new Gu,Gu[Yu]=null,i[Ff]=e):i=Pn(),t===void 0?i:ox.f(i,t)}});var Ar=g((WB,jf)=>{"use strict";var hx=Er();jf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:hx(a,e,t),a}});var tc=g((zB,Wf)=>{"use strict";var fx=Le(),mx=Re(),bx=Je(),gx=Xu(),Hf=un(),vx=Ar(),Sx=je(),yx=Pt(),ec=Sx("iterator"),Qf=!1,Zt,Ju,Zu;[].keys&&(Zu=[].keys(),"next"in Zu?(Ju=Hf(Hf(Zu)),Ju!==Object.prototype&&(Zt=Ju)):Qf=!0);var Tx=!bx(Zt)||fx(function(){var a={};return Zt[ec].call(a)!==a});Tx?Zt={}:yx&&(Zt=gx(Zt));mx(Zt[ec])||vx(Zt,ec,function(){return this});Wf.exports={IteratorPrototype:Zt,BUGGY_SAFARI_ITERATORS:Qf}});var kn=g((GB,Gf)=>{"use strict";var Ix=je(),Ex=Ix("toStringTag"),zf={};zf[Ex]="z";Gf.exports=String(zf)==="[object z]"});var wa=g((YB,Yf)=>{"use strict";var wx=kn(),xx=Re(),An=qi(),Px=je(),kx=Px("toStringTag"),Ax=Object,Rx=An(function(){return arguments}())==="Arguments",Mx=function(a,e){try{return a[e]}catch(t){}};Yf.exports=wx?An:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=Mx(e=Ax(a),kx))=="string"?t:Rx?An(e):(i=An(e))==="Object"&&xx(e.callee)?"Arguments":i}});var Xf=g((KB,Kf)=>{"use strict";var $x=kn(),Cx=wa();Kf.exports=$x?{}.toString:function(){return"[object "+Cx(this)+"]"}});var xa=g((XB,Zf)=>{"use strict";var Dx=kn(),Lx=Qi().f,Bx=Er(),Vx=kt(),_x=Xf(),Ox=je(),Jf=Ox("toStringTag");Zf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(Vx(r,Jf)||Lx(r,Jf,{configurable:!0,value:e}),i&&!Dx&&Bx(r,"toString",_x))}});var tm=g((JB,em)=>{"use strict";var Nx=tc().IteratorPrototype,Fx=Xu(),qx=ca(),Ux=xa(),jx=Gi(),Hx=function(){return this};em.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=Fx(Nx,{next:qx(+!i,t)}),Ux(a,r,!1,!0),jx[r]=Hx,a}});var rm=g((ZB,im)=>{"use strict";var Qx=Be(),Wx=Nt();im.exports=function(a,e,t){try{return Qx(Wx(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var sm=g((e0,am)=>{"use strict";var zx=Je();am.exports=function(a){return zx(a)||a===null}});var om=g((t0,nm)=>{"use strict";var Gx=sm(),Yx=String,Kx=TypeError;nm.exports=function(a){if(Gx(a))return a;throw new Kx("Can't set "+Yx(a)+" as a prototype")}});var ic=g((i0,um)=>{"use strict";var Xx=rm(),Jx=Je(),Zx=mi(),eP=om();um.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Xx(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return Zx(r),eP(s),Jx(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Sm=g((r0,vm)=>{"use strict";var tP=$e(),iP=ct(),Rn=Pt(),bm=Wu(),rP=Re(),aP=tm(),cm=un(),lm=ic(),sP=xa(),nP=Er(),rc=Ar(),oP=je(),dm=Gi(),gm=tc(),uP=bm.PROPER,cP=bm.CONFIGURABLE,pm=gm.IteratorPrototype,Mn=gm.BUGGY_SAFARI_ITERATORS,Pa=oP("iterator"),hm="keys",ka="values",fm="entries",mm=function(){return this};vm.exports=function(a,e,t,i,r,s,n){aP(t,e,i);var o=function(v){if(v===r&&p)return p;if(!Mn&&v&&v in d)return d[v];switch(v){case hm:return function(){return new t(this,v)};case ka:return function(){return new t(this,v)};case fm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,d=a.prototype,l=d[Pa]||d["@@iterator"]||r&&d[r],p=!Mn&&l||o(r),h=e==="Array"&&d.entries||l,m,b,S;if(h&&(m=cm(h.call(new a)),m!==Object.prototype&&m.next&&(!Rn&&cm(m)!==pm&&(lm?lm(m,pm):rP(m[Pa])||rc(m,Pa,mm)),sP(m,u,!0,!0),Rn&&(dm[u]=mm))),uP&&r===ka&&l&&l.name!==ka&&(!Rn&&cP?nP(d,"name",ka):(c=!0,p=function(){return iP(l,this)})),r)if(b={values:o(ka),keys:s?p:o(hm),entries:o(fm)},n)for(S in b)(Mn||c||!(S in d))&&rc(d,S,b[S]);else tP({target:e,proto:!0,forced:Mn||c},b);return(!Rn||n)&&d[Pa]!==p&&rc(d,Pa,p,{name:r}),dm[e]=p,b}});var Tm=g((a0,ym)=>{"use strict";ym.exports=function(a,e){return{value:a,done:e}}});var sc=g((s0,Pm)=>{"use strict";var lP=Ui(),ac=va(),Im=Gi(),wm=ju(),dP=Qi().f,pP=Sm(),$n=Tm(),hP=Pt(),fP=ut(),xm="Array Iterator",mP=wm.set,bP=wm.getterFor(xm);Pm.exports=pP(Array,"Array",function(a,e){mP(this,{type:xm,target:lP(a),index:0,kind:e})},function(){var a=bP(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,$n(void 0,!0);switch(a.kind){case"keys":return $n(t,!1);case"values":return $n(e[t],!1)}return $n([t,e[t]],!1)},"values");var Em=Im.Arguments=Im.Array;ac("keys");ac("values");ac("entries");if(!hP&&fP&&Em.name!=="values")try{dP(Em,"name",{value:"values"})}catch(a){}});var Am=g((n0,km)=>{"use strict";var gP=je(),vP=Gi(),SP=gP("iterator"),yP=Array.prototype;km.exports=function(a){return a!==void 0&&(vP.Array===a||yP[SP]===a)}});var nc=g((o0,Mm)=>{"use strict";var TP=wa(),Rm=ha(),IP=la(),EP=Gi(),wP=je(),xP=wP("iterator");Mm.exports=function(a){if(!IP(a))return Rm(a,xP)||Rm(a,"@@iterator")||EP[TP(a)]}});var Cm=g((u0,$m)=>{"use strict";var PP=ct(),kP=Nt(),AP=Ft(),RP=pa(),MP=nc(),$P=TypeError;$m.exports=function(a,e){var t=arguments.length<2?MP(a):e;if(kP(t))return AP(PP(t,a));throw new $P(RP(a)+" is not iterable")}});var Bm=g((c0,Lm)=>{"use strict";var CP=ct(),Dm=Ft(),DP=ha();Lm.exports=function(a,e,t){var i,r;Dm(a);try{if(i=DP(a,"return"),!i){if(e==="throw")throw t;return t}i=CP(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Dm(i),t}});var Dn=g((l0,Nm)=>{"use strict";var LP=Ir(),BP=ct(),VP=Ft(),_P=pa(),OP=Am(),NP=Pr(),Vm=da(),FP=Cm(),qP=nc(),_m=Bm(),UP=TypeError,Cn=function(a,e){this.stopped=a,this.result=e},Om=Cn.prototype;Nm.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=LP(e,i),c,d,l,p,h,m,b,S=function(y){return c&&_m(c,"normal"),new Cn(!0,y)},v=function(y){return r?(VP(y),o?u(y[0],y[1],S):u(y[0],y[1])):o?u(y,S):u(y)};if(s)c=a.iterator;else if(n)c=a;else{if(d=qP(a),!d)throw new UP(_P(a)+" is not iterable");if(OP(d)){for(l=0,p=NP(a);p>l;l++)if(h=v(a[l]),h&&Vm(Om,h))return h;return new Cn(!1)}c=FP(a,d)}for(m=s?a.next:c.next;!(b=BP(m,c)).done;){try{h=v(b.value)}catch(y){_m(c,"throw",y)}if(typeof h=="object"&&h&&Vm(Om,h))return h}return new Cn(!1)}});var qm=g((d0,Fm)=>{"use strict";var jP=ut(),HP=Qi(),QP=ca();Fm.exports=function(a,e,t){jP?HP.f(a,e,QP(0,t)):a[e]=t}});var Um=g(()=>{"use strict";var WP=$e(),zP=Dn(),GP=qm();WP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return zP(e,function(i,r){GP(t,i,r)},{AS_ENTRIES:!0}),t}})});var Hm=g((f0,jm)=>{"use strict";sc();Um();var YP=ji();jm.exports=YP.Object.fromEntries});var Wm=g((m0,Qm)=>{"use strict";Qm.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 Gm=g(()=>{"use strict";sc();var KP=Wm(),XP=Ae(),JP=xa(),zm=Gi();for(Ln in KP)JP(XP[Ln],Ln),zm[Ln]=zm.Array;var Ln});var Km=g((v0,Ym)=>{"use strict";var ZP=Hm();Gm();Ym.exports=ZP});var oc=g((S0,Xm)=>{"use strict";var ek=Km();Xm.exports=ek});var Jm=g(()=>{"use strict"});var uc=g((I0,Zm)=>{"use strict";var Aa=Ae(),tk=Hi(),ik=qi(),Bn=function(a){return tk.slice(0,a.length)===a};Zm.exports=function(){return Bn("Bun/")?"BUN":Bn("Cloudflare-Workers")?"CLOUDFLARE":Bn("Deno/")?"DENO":Bn("Node.js/")?"NODE":Aa.Bun&&typeof Bun.version=="string"?"BUN":Aa.Deno&&typeof Deno.version=="object"?"DENO":ik(Aa.process)==="process"?"NODE":Aa.window&&Aa.document?"BROWSER":"REST"}()});var Vn=g((E0,eb)=>{"use strict";var rk=uc();eb.exports=rk==="NODE"});var ib=g((w0,tb)=>{"use strict";var ak=Qi();tb.exports=function(a,e,t){return ak.f(a,e,t)}});var sb=g((x0,ab)=>{"use strict";var sk=Xt(),nk=ib(),ok=je(),uk=ut(),rb=ok("species");ab.exports=function(a){var e=sk(a);uk&&e&&!e[rb]&&nk(e,rb,{configurable:!0,get:function(){return this}})}});var ob=g((P0,nb)=>{"use strict";var ck=da(),lk=TypeError;nb.exports=function(a,e){if(ck(e,a))return a;throw new lk("Incorrect invocation")}});var lc=g((k0,ub)=>{"use strict";var dk=Be(),pk=Re(),cc=fa(),hk=dk(Function.toString);pk(cc.inspectSource)||(cc.inspectSource=function(a){return hk(a)});ub.exports=cc.inspectSource});var pc=g((A0,hb)=>{"use strict";var fk=Be(),mk=Le(),cb=Re(),bk=wa(),gk=Xt(),vk=lc(),lb=function(){},db=gk("Reflect","construct"),dc=/^\s*(?:class|function)\b/,Sk=fk(dc.exec),yk=!dc.test(lb),Ra=function(e){if(!cb(e))return!1;try{return db(lb,[],e),!0}catch(t){return!1}},pb=function(e){if(!cb(e))return!1;switch(bk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return yk||!!Sk(dc,vk(e))}catch(t){return!0}};pb.sham=!0;hb.exports=!db||mk(function(){var a;return Ra(Ra.call)||!Ra(Object)||!Ra(function(){a=!0})||a})?pb:Ra});var mb=g((R0,fb)=>{"use strict";var Tk=pc(),Ik=pa(),Ek=TypeError;fb.exports=function(a){if(Tk(a))return a;throw new Ek(Ik(a)+" is not a constructor")}});var hc=g((M0,gb)=>{"use strict";var bb=Ft(),wk=mb(),xk=la(),Pk=je(),kk=Pk("species");gb.exports=function(a,e){var t=bb(a).constructor,i;return t===void 0||xk(i=bb(t)[kk])?e:wk(i)}});var Sb=g(($0,vb)=>{"use strict";var Ak=Be();vb.exports=Ak([].slice)});var Tb=g((C0,yb)=>{"use strict";var Rk=TypeError;yb.exports=function(a,e){if(a<e)throw new Rk("Not enough arguments");return a}});var fc=g((D0,Ib)=>{"use strict";var Mk=Hi();Ib.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Mk)});var Ec=g((L0,$b)=>{"use strict";var dt=Ae(),$k=tu(),Ck=Ir(),Eb=Re(),Dk=kt(),Mb=Le(),wb=zu(),Lk=Sb(),xb=sn(),Bk=Tb(),Vk=fc(),_k=Vn(),yc=dt.setImmediate,Tc=dt.clearImmediate,Ok=dt.process,mc=dt.Dispatch,Nk=dt.Function,Pb=dt.MessageChannel,Fk=dt.String,bc=0,Ma={},kb="onreadystatechange",$a,Ki,gc,vc;Mb(function(){$a=dt.location});var Ic=function(a){if(Dk(Ma,a)){var e=Ma[a];delete Ma[a],e()}},Sc=function(a){return function(){Ic(a)}},Ab=function(a){Ic(a.data)},Rb=function(a){dt.postMessage(Fk(a),$a.protocol+"//"+$a.host)};(!yc||!Tc)&&(yc=function(e){Bk(arguments.length,1);var t=Eb(e)?e:Nk(e),i=Lk(arguments,1);return Ma[++bc]=function(){$k(t,void 0,i)},Ki(bc),bc},Tc=function(e){delete Ma[e]},_k?Ki=function(a){Ok.nextTick(Sc(a))}:mc&&mc.now?Ki=function(a){mc.now(Sc(a))}:Pb&&!Vk?(gc=new Pb,vc=gc.port2,gc.port1.onmessage=Ab,Ki=Ck(vc.postMessage,vc)):dt.addEventListener&&Eb(dt.postMessage)&&!dt.importScripts&&$a&&$a.protocol!=="file:"&&!Mb(Rb)?(Ki=Rb,dt.addEventListener("message",Ab,!1)):kb in xb("script")?Ki=function(a){wb.appendChild(xb("script"))[kb]=function(){wb.removeChild(this),Ic(a)}}:Ki=function(a){setTimeout(Sc(a),0)});$b.exports={set:yc,clear:Tc}});var Lb=g((B0,Db)=>{"use strict";var Cb=Ae(),qk=ut(),Uk=Object.getOwnPropertyDescriptor;Db.exports=function(a){if(!qk)return Cb[a];var e=Uk(Cb,a);return e&&e.value}});var wc=g((V0,Vb)=>{"use strict";var Bb=function(){this.head=null,this.tail=null};Bb.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}}};Vb.exports=Bb});var Ob=g((_0,_b)=>{"use strict";var jk=Hi();_b.exports=/ipad|iphone|ipod/i.test(jk)&&typeof Pebble!="undefined"});var Fb=g((O0,Nb)=>{"use strict";var Hk=Hi();Nb.exports=/web0s(?!.*chrome)/i.test(Hk)});var zb=g((N0,Wb)=>{"use strict";var Mr=Ae(),Qk=Lb(),qb=Ir(),xc=Ec().set,Wk=wc(),zk=fc(),Gk=Ob(),Yk=Fb(),Pc=Vn(),Ub=Mr.MutationObserver||Mr.WebKitMutationObserver,jb=Mr.document,Hb=Mr.process,_n=Mr.Promise,Rc=Qk("queueMicrotask"),Rr,kc,Ac,On,Qb;Rc||(Ca=new Wk,Da=function(){var a,e;for(Pc&&(a=Hb.domain)&&a.exit();e=Ca.get();)try{e()}catch(t){throw Ca.head&&Rr(),t}a&&a.enter()},!zk&&!Pc&&!Yk&&Ub&&jb?(kc=!0,Ac=jb.createTextNode(""),new Ub(Da).observe(Ac,{characterData:!0}),Rr=function(){Ac.data=kc=!kc}):!Gk&&_n&&_n.resolve?(On=_n.resolve(void 0),On.constructor=_n,Qb=qb(On.then,On),Rr=function(){Qb(Da)}):Pc?Rr=function(){Hb.nextTick(Da)}:(xc=qb(xc,Mr),Rr=function(){xc(Da)}),Rc=function(a){Ca.head||Rr(),Ca.add(a)});var Ca,Da;Wb.exports=Rc});var Yb=g((F0,Gb)=>{"use strict";Gb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Nn=g((q0,Kb)=>{"use strict";Kb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Xi=g((U0,Xb)=>{"use strict";var Kk=Ae();Xb.exports=Kk.Promise});var $r=g((j0,tg)=>{"use strict";var Xk=Ae(),La=Xi(),Jk=Re(),Zk=Eu(),eA=lc(),tA=je(),Jb=uc(),iA=Pt(),Mc=lu(),Zb=La&&La.prototype,rA=tA("species"),$c=!1,eg=Jk(Xk.PromiseRejectionEvent),aA=Zk("Promise",function(){var a=eA(La),e=a!==String(La);if(!e&&Mc===66||iA&&!(Zb.catch&&Zb.finally))return!0;if(!Mc||Mc<51||!/native code/.test(a)){var t=new La(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[rA]=i,$c=t.then(function(){})instanceof i,!$c)return!0}return!e&&(Jb==="BROWSER"||Jb==="DENO")&&!eg});tg.exports={CONSTRUCTOR:aA,REJECTION_EVENT:eg,SUBCLASSING:$c}});var Cr=g((H0,rg)=>{"use strict";var ig=Nt(),sA=TypeError,nA=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new sA("Bad Promise constructor");e=i,t=r}),this.resolve=ig(e),this.reject=ig(t)};rg.exports.f=function(a){return new nA(a)}});var Eg=g(()=>{"use strict";var oA=$e(),uA=Pt(),jn=Vn(),yi=Ae(),cA=ji(),Vr=ct(),ag=Ar(),sg=ic(),lA=xa(),dA=sb(),pA=Nt(),Un=Re(),hA=Je(),fA=ob(),mA=hc(),lg=Ec().set,Vc=zb(),bA=Yb(),gA=Nn(),vA=wc(),dg=ju(),Hn=Xi(),_c=$r(),pg=Cr(),Qn="Promise",hg=_c.CONSTRUCTOR,SA=_c.REJECTION_EVENT,yA=_c.SUBCLASSING,Cc=dg.getterFor(Qn),TA=dg.set,Dr=Hn&&Hn.prototype,Ji=Hn,Fn=Dr,fg=yi.TypeError,Dc=yi.document,Oc=yi.process,Lc=pg.f,IA=Lc,EA=!!(Dc&&Dc.createEvent&&yi.dispatchEvent),mg="unhandledrejection",wA="rejectionhandled",ng=0,bg=1,xA=2,Nc=1,gg=2,qn,og,vg,ug,Sg=function(a){var e;return hA(a)&&Un(e=a.then)?e:!1},yg=function(a,e){var t=e.value,i=e.state===bg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,d;try{r?(i||(e.rejection===gg&&kA(e),e.rejection=Nc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new fg("Promise-chain cycle")):(c=Sg(u))?Vr(c,u,s,n):s(u)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},Tg=function(a,e){a.notified||(a.notified=!0,Vc(function(){for(var t=a.reactions,i;i=t.get();)yg(i,a);a.notified=!1,e&&!a.rejection&&PA(a)}))},Ig=function(a,e,t){var i,r;EA?(i=Dc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),yi.dispatchEvent(i)):i={promise:e,reason:t},!SA&&(r=yi["on"+a])?r(i):a===mg&&bA("Unhandled promise rejection",t)},PA=function(a){Vr(lg,yi,function(){var e=a.facade,t=a.value,i=cg(a),r;if(i&&(r=gA(function(){jn?Oc.emit("unhandledRejection",t,e):Ig(mg,e,t)}),a.rejection=jn||cg(a)?gg:Nc,r.error))throw r.value})},cg=function(a){return a.rejection!==Nc&&!a.parent},kA=function(a){Vr(lg,yi,function(){var e=a.facade;jn?Oc.emit("rejectionHandled",e):Ig(wA,e,a.value)})},Lr=function(a,e,t){return function(i){a(e,i,t)}},Br=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=xA,Tg(a,!0))},Bc=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new fg("Promise can't be resolved itself");var i=Sg(e);i?Vc(function(){var r={done:!1};try{Vr(i,e,Lr(Bc,r,a),Lr(Br,r,a))}catch(s){Br(r,s,a)}}):(a.value=e,a.state=bg,Tg(a,!1))}catch(r){Br({done:!1},r,a)}}};if(hg&&(Ji=function(e){fA(this,Fn),pA(e),Vr(qn,this);var t=Cc(this);try{e(Lr(Bc,t),Lr(Br,t))}catch(i){Br(t,i)}},Fn=Ji.prototype,qn=function(e){TA(this,{type:Qn,done:!1,notified:!1,parent:!1,reactions:new vA,rejection:!1,state:ng,value:null})},qn.prototype=ag(Fn,"then",function(e,t){var i=Cc(this),r=Lc(mA(this,Ji));return i.parent=!0,r.ok=Un(e)?e:!0,r.fail=Un(t)&&t,r.domain=jn?Oc.domain:void 0,i.state===ng?i.reactions.add(r):Vc(function(){yg(r,i)}),r.promise}),og=function(){var a=new qn,e=Cc(a);this.promise=a,this.resolve=Lr(Bc,e),this.reject=Lr(Br,e)},pg.f=Lc=function(a){return a===Ji||a===vg?new og(a):IA(a)},!uA&&Un(Hn)&&Dr!==Object.prototype)){ug=Dr.then,yA||ag(Dr,"then",function(e,t){var i=this;return new Ji(function(r,s){Vr(ug,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Dr.constructor}catch(a){}sg&&sg(Dr,Fn)}oA({global:!0,constructor:!0,wrap:!0,forced:hg},{Promise:Ji});vg=cA.Promise;lA(Ji,Qn,!1,!0);dA(Qn)});var Ag=g((z0,kg)=>{"use strict";var AA=je(),xg=AA("iterator"),Pg=!1;try{wg=0,Fc={next:function(){return{done:!!wg++}},return:function(){Pg=!0}},Fc[xg]=function(){return this},Array.from(Fc,function(){throw 2})}catch(a){}var wg,Fc;kg.exports=function(a,e){try{if(!e&&!Pg)return!1}catch(r){return!1}var t=!1;try{var i={};i[xg]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var qc=g((G0,Rg)=>{"use strict";var RA=Xi(),MA=Ag(),$A=$r().CONSTRUCTOR;Rg.exports=$A||!MA(function(a){RA.all(a).then(void 0,function(){})})});var Mg=g(()=>{"use strict";var CA=$e(),DA=ct(),LA=Nt(),BA=Cr(),VA=Nn(),_A=Dn(),OA=qc();CA({target:"Promise",stat:!0,forced:OA},{all:function(e){var t=this,i=BA.f(t),r=i.resolve,s=i.reject,n=VA(function(){var o=LA(t.resolve),u=[],c=0,d=1;_A(e,function(l){var p=c++,h=!1;d++,DA(o,t,l).then(function(m){h||(h=!0,u[p]=m,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var Cg=g(()=>{"use strict";var NA=$e(),FA=Pt(),qA=$r().CONSTRUCTOR,jc=Xi(),UA=Xt(),jA=Re(),HA=Ar(),$g=jc&&jc.prototype;NA({target:"Promise",proto:!0,forced:qA,real:!0},{catch:function(a){return this.then(void 0,a)}});!FA&&jA(jc)&&(Uc=UA("Promise").prototype.catch,$g.catch!==Uc&&HA($g,"catch",Uc,{unsafe:!0}));var Uc});var Dg=g(()=>{"use strict";var QA=$e(),WA=ct(),zA=Nt(),GA=Cr(),YA=Nn(),KA=Dn(),XA=qc();QA({target:"Promise",stat:!0,forced:XA},{race:function(e){var t=this,i=GA.f(t),r=i.reject,s=YA(function(){var n=zA(t.resolve);KA(e,function(o){WA(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Lg=g(()=>{"use strict";var JA=$e(),ZA=Cr(),eR=$r().CONSTRUCTOR;JA({target:"Promise",stat:!0,forced:eR},{reject:function(e){var t=ZA.f(this),i=t.reject;return i(e),t.promise}})});var Hc=g((rV,Bg)=>{"use strict";var tR=Ft(),iR=Je(),rR=Cr();Bg.exports=function(a,e){if(tR(a),iR(e)&&e.constructor===a)return e;var t=rR.f(a),i=t.resolve;return i(e),t.promise}});var Og=g(()=>{"use strict";var aR=$e(),sR=Xt(),Vg=Pt(),nR=Xi(),_g=$r().CONSTRUCTOR,oR=Hc(),uR=sR("Promise"),cR=Vg&&!_g;aR({target:"Promise",stat:!0,forced:Vg||_g},{resolve:function(e){return oR(cR&&this===uR?nR:this,e)}})});var Ng=g(()=>{"use strict";Eg();Mg();Cg();Dg();Lg();Og()});var jg=g(()=>{"use strict";var lR=$e(),dR=Pt(),Wn=Xi(),pR=Le(),qg=Xt(),Ug=Re(),hR=hc(),Fg=Hc(),fR=Ar(),Wc=Wn&&Wn.prototype,mR=!!Wn&&pR(function(){Wc.finally.call({then:function(){}},function(){})});lR({target:"Promise",proto:!0,real:!0,forced:mR},{finally:function(a){var e=hR(this,qg("Promise")),t=Ug(a);return this.then(t?function(i){return Fg(e,a()).then(function(){return i})}:a,t?function(i){return Fg(e,a()).then(function(){throw i})}:a)}});!dR&&Ug(Wn)&&(Qc=qg("Promise").prototype.finally,Wc.finally!==Qc&&fR(Wc,"finally",Qc,{unsafe:!0}));var Qc});var Qg=g((lV,Hg)=>{"use strict";Jm();Ng();jg();var bR=bi();Hg.exports=bR("Promise","finally")});var zg=g((dV,Wg)=>{"use strict";var gR=Qg();Wg.exports=gR});var zc=g((pV,Gg)=>{"use strict";var vR=zg();Gg.exports=vR});var iv=g(()=>{"use strict";var PR=$e(),kR=yr(),AR=Pr(),RR=ga(),MR=va();PR({target:"Array",proto:!0},{at:function(e){var t=kR(this),i=AR(t),r=RR(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});MR("at")});var av=g((a_,rv)=>{"use strict";iv();var $R=bi();rv.exports=$R("Array","at")});var nv=g((s_,sv)=>{"use strict";var CR=av();sv.exports=CR});var vt=g((n_,ov)=>{"use strict";var DR=nv();ov.exports=DR});var fl=g((cF,Nv)=>{"use strict";var GR=qi();Nv.exports=Array.isArray||function(e){return GR(e)==="Array"}});var qv=g((lF,Fv)=>{"use strict";var YR=TypeError,KR=9007199254740991;Fv.exports=function(a){if(a>KR)throw YR("Maximum allowed index exceeded");return a}});var Hv=g((dF,jv)=>{"use strict";var XR=fl(),JR=Pr(),ZR=qv(),eM=Ir(),Uv=function(a,e,t,i,r,s,n,o){for(var u=r,c=0,d=n?eM(n,o):!1,l,p;c<i;)c in t&&(l=d?d(t[c],c,e):t[c],s>0&&XR(l)?(p=JR(l),u=Uv(a,e,l,p,u,s-1)-1):(ZR(u+1),a[u]=l),u++),c++;return u};jv.exports=Uv});var Gv=g((pF,zv)=>{"use strict";var Qv=fl(),tM=pc(),iM=Je(),rM=je(),aM=rM("species"),Wv=Array;zv.exports=function(a){var e;return Qv(a)&&(e=a.constructor,tM(e)&&(e===Wv||Qv(e.prototype))?e=void 0:iM(e)&&(e=e[aM],e===null&&(e=void 0))),e===void 0?Wv:e}});var Kv=g((hF,Yv)=>{"use strict";var sM=Gv();Yv.exports=function(a,e){return new(sM(a))(e===0?0:e)}});var Xv=g(()=>{"use strict";var nM=$e(),oM=Hv(),uM=Nt(),cM=yr(),lM=Pr(),dM=Kv();nM({target:"Array",proto:!0},{flatMap:function(e){var t=cM(this),i=lM(t),r;return uM(e),r=dM(t,0),r.length=oM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Jv=g(()=>{"use strict";var pM=va();pM("flatMap")});var eS=g((vF,Zv)=>{"use strict";Xv();Jv();var hM=bi();Zv.exports=hM("Array","flatMap")});var iS=g((SF,tS)=>{"use strict";var fM=eS();tS.exports=fM});var Ga=g((yF,rS)=>{"use strict";var mM=iS();rS.exports=mM});var Ka=g((_F,oS)=>{"use strict";var gM=wa(),vM=String;oS.exports=function(a){if(gM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return vM(a)}});var bl=g((OF,uS)=>{"use strict";uS.exports=`
|
|
7
|
-
\v\f\r \u2028\u2029\uFEFF`});var dS=g((NF,lS)=>{"use strict";var SM=Be(),yM=mi(),TM=Ka(),vl=bl(),cS=SM("".replace),IM=RegExp("^["+vl+"]+"),EM=RegExp("(^|[^"+vl+"])["+vl+"]+$"),gl=function(a){return function(e){var t=TM(yM(e));return a&1&&(t=cS(t,IM,"")),a&2&&(t=cS(t,EM,"$1")),t}};lS.exports={start:gl(1),end:gl(2),trim:gl(3)}});var mS=g((FF,fS)=>{"use strict";var wM=Wu().PROPER,xM=Le(),pS=bl(),hS="
";fS.exports=function(a){return xM(function(){return!!pS[a]()||hS[a]()!==hS||wM&&pS[a].name!==a})}});var Sl=g((qF,bS)=>{"use strict";var PM=dS().start,kM=mS();bS.exports=kM("trimStart")?function(){return PM(this)}:"".trimStart});var vS=g(()=>{"use strict";var AM=$e(),gS=Sl();AM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==gS},{trimLeft:gS})});var yS=g(()=>{"use strict";vS();var RM=$e(),SS=Sl();RM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==SS},{trimStart:SS})});var IS=g((WF,TS)=>{"use strict";yS();var MM=bi();TS.exports=MM("String","trimLeft")});var wS=g((zF,ES)=>{"use strict";var $M=IS();ES.exports=$M});var PS=g((GF,xS)=>{"use strict";var CM=wS();xS.exports=CM});var AS=g(()=>{"use strict"});var RS=g(()=>{"use strict"});var $S=g((Mq,MS)=>{"use strict";var DM=Je(),LM=qi(),BM=je(),VM=BM("match");MS.exports=function(a){var e;return DM(a)&&((e=a[VM])!==void 0?!!e:LM(a)==="RegExp")}});var LS=g(($q,DS)=>{"use strict";var _M=Ae(),OM=Le(),CS=_M.RegExp,NM=!OM(function(){var a=!0;try{CS(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(CS.prototype,"flags").get.call(e);return o!==i||t!==i});DS.exports={correct:NM}});var VS=g((Cq,BS)=>{"use strict";var FM=Ft();BS.exports=function(){var a=FM(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=g((Dq,OS)=>{"use strict";var qM=ct(),UM=kt(),jM=da(),_S=LS(),HM=VS(),QM=RegExp.prototype;OS.exports=_S.correct?function(a){return a.flags}:function(a){return!_S.correct&&jM(QM,a)&&!UM(a,"flags")?qM(HM,a):a.flags}});var qS=g((Lq,FS)=>{"use strict";var El=Be(),WM=yr(),zM=Math.floor,Tl=El("".charAt),GM=El("".replace),Il=El("".slice),YM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,KM=/\$([$&'`]|\d{1,2})/g;FS.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=KM;return r!==void 0&&(r=WM(r),u=YM),GM(s,u,function(c,d){var l;switch(Tl(d,0)){case"$":return"$";case"&":return a;case"`":return Il(e,0,t);case"'":return Il(e,n);case"<":l=r[Il(d,1,-1)];break;default:var p=+d;if(p===0)return c;if(p>o){var h=zM(p/10);return h===0?c:h<=o?i[h-1]===void 0?Tl(d,1):i[h-1]+Tl(d,1):c}l=i[p-1]}return l===void 0?"":l})}});var HS=g(()=>{"use strict";var XM=$e(),JM=ct(),xl=Be(),US=mi(),ZM=Re(),e$=Je(),t$=$S(),Qr=Ka(),i$=ha(),r$=NS(),a$=qS(),s$=je(),n$=Pt(),o$=s$("replace"),u$=TypeError,wl=xl("".indexOf),c$=xl("".replace),jS=xl("".slice),l$=Math.max;XM({target:"String",proto:!0},{replaceAll:function(e,t){var i=US(this),r,s,n,o,u,c,d,l,p,h,m=0,b="";if(e$(e)){if(r=t$(e),r&&(s=Qr(US(r$(e))),!~wl(s,"g")))throw new u$("`.replaceAll` does not allow non-global regexes");if(n=i$(e,o$),n)return JM(n,e,i,t);if(n$&&r)return c$(Qr(i),e,t)}for(o=Qr(i),u=Qr(e),c=ZM(t),c||(t=Qr(t)),d=u.length,l=l$(1,d),p=wl(o,u);p!==-1;)h=c?Qr(t(u,p,o)):a$(u,o,p,[],void 0,t),b+=jS(o,m,p)+h,m=p+d,p=p+l>o.length?-1:wl(o,u,p+l);return m<o.length&&(b+=jS(o,m)),b}})});var WS=g((_q,QS)=>{"use strict";AS();RS();HS();var d$=bi();QS.exports=d$("String","replaceAll")});var GS=g((Oq,zS)=>{"use strict";var p$=WS();zS.exports=p$});var KS=g((Nq,YS)=>{"use strict";var h$=GS();YS.exports=h$});var JS=g((Fq,XS)=>{"use strict";var f$=ga(),m$=Ka(),b$=mi(),g$=RangeError;XS.exports=function(e){var t=m$(b$(this)),i="",r=f$(e);if(r<0||r===1/0)throw new g$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var ry=g((qq,iy)=>{"use strict";var ty=Be(),v$=Mu(),ZS=Ka(),S$=JS(),y$=mi(),T$=ty(S$),I$=ty("".slice),E$=Math.ceil,ey=function(a){return function(e,t,i){var r=ZS(y$(e)),s=v$(t),n=r.length,o=i===void 0?" ":ZS(i),u,c;return s<=n||o===""?r:(u=s-n,c=T$(o,E$(u/o.length)),c.length>u&&(c=I$(c,0,u)),a?r+c:c+r)}};iy.exports={start:ey(!1),end:ey(!0)}});var sy=g((Uq,ay)=>{"use strict";var w$=Hi();ay.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(w$)});var ny=g(()=>{"use strict";var x$=$e(),P$=ry().start,k$=sy();x$({target:"String",proto:!0,forced:k$},{padStart:function(e){return P$(this,e,arguments.length>1?arguments[1]:void 0)}})});var uy=g((Qq,oy)=>{"use strict";ny();var A$=bi();oy.exports=A$("String","padStart")});var ly=g((Wq,cy)=>{"use strict";var R$=uy();cy.exports=R$});var py=g((zq,dy)=>{"use strict";var M$=ly();dy.exports=M$});var TC={};RT(TC,{ChromecastState:()=>Sr,HttpConnectionType:()=>en,Observable:()=>zt.Observable,PlaybackState:()=>Ue,Player:()=>Os,PredefinedQualityLimits:()=>na,SDK_VERSION:()=>yC,Subject:()=>zt.Subject,Subscription:()=>zt.Subscription,Surface:()=>tn,VERSION:()=>Zo,ValueSubject:()=>zt.ValueSubject,VideoFormat:()=>Ot,VideoQuality:()=>zt.VideoQuality,areValidLiveRecordSources:()=>mf,clientChecker:()=>G,isMobile:()=>gi});module.exports=MT(TC);var Zo="2.0.150";var Ue=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ue||{}),Ot=(P=>(P.MPEG="MPEG",P.DASH="DASH",P.DASH_SEP="DASH_SEP",P.DASH_SEP_VK="DASH_SEP",P.DASH_WEBM="DASH_WEBM",P.DASH_WEBM_AV1="DASH_WEBM_AV1",P.DASH_STREAMS="DASH_STREAMS",P.DASH_WEBM_VK="DASH_WEBM",P.DASH_ONDEMAND="DASH_ONDEMAND",P.DASH_ONDEMAND_VK="DASH_ONDEMAND",P.DASH_LIVE="DASH_LIVE",P.DASH_LIVE_CMAF="DASH_LIVE_CMAF",P.DASH_LIVE_WEBM="DASH_LIVE_WEBM",P.HLS="HLS",P.HLS_ONDEMAND="HLS_ONDEMAND",P.HLS_JS="HLS",P.HLS_FMP4="HLS_FMP4",P.HLS_LIVE="HLS_LIVE",P.HLS_LIVE_CMAF="HLS_LIVE_CMAF",P.WEB_RTC_LIVE="WEB_RTC_LIVE",P))(Ot||{});var Sr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Sr||{}),en=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(en||{});var tn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(tn||{}),na=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(na||{});var Jl=Z(Wi(),1),fT=Z(Ze(),1);var se=require("@vkontakte/videoplayer-shared/es2015");var af=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var ln=class{constructor(e){this.connection$=new se.ValueSubject(void 0);this.castState$=new se.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new se.Subject;this.realCastState$=new se.ValueSubject("NOT_AVAILABLE");this.subscription=new se.Subscription;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,se.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||af("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:se.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,se.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,se.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,se.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,se.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,se.assertNever)(r.sessionState)}})).add((0,se.merge)((0,se.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,se.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,se.map)(r=>r.castState)),(0,se.observableFrom)([i.getCastState()])).pipe((0,se.filterChanged)(),(0,se.map)(xw),(0,se.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=(0,se.isNonNullable)(this.connection$.getValue());if(s&&!n){let c=i.getCurrentSession();(0,se.assertNonNullable)(c);let d=c.getCastDevice(),l=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,se.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,se.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:se.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},xw=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(0,se.assertNever)(a)}};var oe=require("@vkontakte/videoplayer-shared/es2015");var Ve=require("@vkontakte/videoplayer-shared/es2015");var Vu=require("@vkontakte/videoplayer-shared/es2015");var He=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Vu.assertNever)(t)}return a},dn=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Vu.assertNever)(e)}};var hn=a=>{var l;let{source:e,format:t,meta:i,output:r}=a,s,n,o;switch(t){case"MPEG":{let p=e[t];(0,Ve.assertNonNullable)(p);let h=(0,Ve.getHighestQuality)(Object.keys(p));(0,Ve.assertNonNullable)(h);let m=p[h];(0,Ve.assertNonNullable)(m),s=m,n="video/mp4",o=pn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];(0,Ve.assertNonNullable)(p),s=p.url,n="application/x-mpegurl",o=pn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];(0,Ve.assertNonNullable)(p),s=p.url,n="application/dash+xml",o=pn();break}case"DASH_LIVE_CMAF":{let p=e[t];(0,Ve.assertNonNullable)(p),s=p.url,n="application/dash+xml",o=sf();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];(0,Ve.assertNonNullable)(p),s=He(p.url),n="application/x-mpegurl",o=sf();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let p="Unsupported format for Chromecast",h=new Error(p);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ve.ErrorCategory.VIDEO_PIPELINE,message:p,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return(0,Ve.assertNever)(t)}let u=Pw((l=i.videoId)!=null?l:s,n);u.contentUrl=s,u.streamType=o,u.metadata=kw();let{title:c,subtitle:d}=i;return(0,Ve.isNonNullable)(c)&&(u.metadata.title=c),(0,Ve.isNonNullable)(d)&&(u.metadata.subtitle=d),u};function pn(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function sf(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function Pw(a,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(a,e):{contentId:a,contentType:e,metadata:{title:"",subtitle:""},streamType:pn()}}function kw(){var a,e;return(e=(a=chrome.cast)==null?void 0:a.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var B=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var fn=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};var Ou=require("@vkontakte/videoplayer-shared/es2015");var In=require("@vkontakte/videoplayer-shared/es2015");var nf=Z(Ze(),1),of=require("@vkontakte/videoplayer-shared/es2015");var mn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,nf.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||c||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=(0,of.getWindow)().navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var uf=Z(Ze(),1),vi=require("@vkontakte/videoplayer-shared/es2015");var gi=()=>{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 bn=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,uf.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||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.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=(0,vi.getWindow)();if(!(0,vi.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=gi()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return I(this,null,function*(){let e=(0,vi.getWindow)();if(!(0,vi.isBrowserWindow)(e))return;let{userAgentData:t}=e.navigator;if(t!=null&&t.getHighEntropyValues){let i=yield t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r.length>0,o=r.length>1,u="Unknown",c="Unknown";if(n){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(u=s[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(c=s[d]):d!==void 0&&(c=d)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&n&&typeof r[0]=="string"&&(c=s[1]);u=this.normalizeOSName(u),c=this.normalizeOSVersion(c,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:c||"Unknown",full:c&&c!=="Unknown"?`${u} ${c}`:u};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r[0],o=r[1],u=typeof n=="number"?s[n]!==void 0?this.normalizeVendorName(s[n]):"Unknown":this.normalizeVendorName(n),c="Unknown";typeof o=="number"?c=s[o]!==void 0?s[o]:"Unknown":o!==void 0?c=o:s[1]!==void 0?c=s[1]:s[0]!==void 0&&(c=s[0]),c=this.normalizeModelName(c,u),this.details.vendor=u,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=(0,vi.getWindow)();if(!(0,vi.isBrowserWindow)(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t!=null&&t[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var Sa=require("@vkontakte/videoplayer-shared/es2015"),gn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,Sa.getWindow)()}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 s;let e=(0,Sa.getWindow)();if(!(0,Sa.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((s=e.matchMedia("(dynamic-range: high)"))!=null&&s.matches),this._colorDepth=i.colorDepth}catch(n){console.error(n)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(n){console.error(n)}}};var zi=require("@vkontakte/videoplayer-shared/es2015");var lt=()=>window.ManagedMediaSource||window.MediaSource,kr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},cf=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},vn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var lf,Aw=(lf=(0,zi.getWindow)().document)==null?void 0:lf.createElement("video"),Rw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Mw='video/mp4; codecs="hev1.1.6.L93.B0"',df='video/webm; codecs="vp09.00.10.08"',pf='video/webm; codecs="av01.0.00M.08"',$w='audio/mp4; codecs="mp4a.40.2"',Cw='audio/webm; codecs="opus"',hf,Dw=()=>I(null,null,function*(){let a=(0,zi.getWindow)();if(!(0,zi.isBrowserWindow)(a))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=yield Promise.all([a.navigator.mediaCapabilities.decodingInfo(U(M({},e),{video:U(M({},e.video),{contentType:pf})})),a.navigator.mediaCapabilities.decodingInfo(U(M({},e),{video:U(M({},e.video),{contentType:df})}))]);hf={DASH_WEBM_AV1:t,DASH_WEBM:i}});Dw().catch(a=>{console.log(Aw),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 hf}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,s,n,o,u,c,d,l,p,h,m,b,S,v,y,x,P,D,V;let e=(0,zi.getWindow)();if(!(0,zi.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:kr(),mse:cf(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(s=this._video).canPlayType)!=null&&n.call(s,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((d=(c=this._video).canPlayType)!=null&&d.call(c,"video/webm")),cmaf:!0};let Q=!!((p=(l=lt())==null?void 0:l.isTypeSupported)!=null&&p.call(l,Rw)),W=!!((m=(h=lt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,Mw)),F=!!((S=(b=lt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,$w));this._codecs={h264:Q,h265:W,vp9:!!((y=(v=lt())==null?void 0:v.isTypeSupported)!=null&&y.call(v,df)),av1:!!((P=(x=lt())==null?void 0:x.isTypeSupported)!=null&&P.call(x,pf)),aac:F,opus:!!((V=(D=lt())==null?void 0:D.isTypeSupported)!=null&&V.call(D,Cw)),mpeg:(Q||W)&&F},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(Q){console.error(Q)}try{this.destroyVideoElement()}catch(Q){console.error("Error destroying video element:",Q)}}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 Tn=require("@vkontakte/videoplayer-shared/es2015");var ff="audio/mpeg",yn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,s,n;let e=(0,Tn.getWindow)();if(!(0,Tn.isBrowserWindow)(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!((r=(i=this._audio).canPlayType)!=null&&r.call(i,ff))},this._codecs={mp3:!!((n=(s=lt())==null?void 0:s.isTypeSupported)!=null&&n.call(s,ff))}}catch(o){console.error(o)}try{this.destroyAudioElement()}catch(o){console.error("Error destroying audio element:",o)}}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}};var _u=class{constructor(){this.isInited$=new In.ValueSubject(!1);this._displayChecker=new gn,this._deviceChecker=new bn(this._displayChecker),this._browserChecker=new mn,this._videoChecker=new Sn(this._deviceChecker,this._browserChecker),this._audioChecker=new yn,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 I(this,null,function*(){(0,In.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))})}},G=new _u;var Nu=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=G.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return(0,Ou.assertNever)(o)}})},ya=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_FMP4":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(0,Ou.assertNever)(a)}},mf=a=>{let t=Object.keys(a).filter(i=>!ya(i));return Nu(t).length>0};var Ta=class{constructor(e){this.subscription=new oe.Subscription;this.sessionId$=new oe.ValueSubject(null);this.mediaSessionId$=new oe.ValueSubject(null);this.contentId$=new oe.ValueSubject(null);this.isMobile=gi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var s,n,o;if((0,oe.isNullable)(e))return;this.media=e,this.mediaSessionId$.next((s=e.mediaSessionId)!=null?s:null);let t=(n=e.media)==null?void 0:n.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=(o=e.media)==null?void 0:o.duration;(0,oe.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,oe.isNonNullable)(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let c=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!c?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new fn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ya(e.format)),this.subscribe()}subscribe(){let e=r=>{var s;this.params.output.error$.next({category:oe.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:(s=r==null?void 0:r.message)!=null?s:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,oe.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,oe.filter)(oe.isNonNullable),(0,oe.filterChanged)(),(0,oe.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,oe.filterChanged)(),(0,oe.map)(Boolean));this.subscription.add((0,oe.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,oe.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,oe.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,oe.filter)(({mediaLoaded:r})=>r),(0,oe.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,oe.filter)(({mediaLoaded:r,playbackState:{from:s,to:n}})=>!r&&s==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,oe.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,oe.debounce)(30)),mediaLoaded:t}).pipe((0,oe.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:n}=r.to;this.setVolume(n,s)},e))}handleMessage(e){var t,i,r,s,n,o;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let u=(i=(t=e.message)==null?void 0:t.media)==null?void 0:i[0];this.syncMediaState(u);let c=(r=e.message)==null?void 0:r.receiver.volume;this.syncVolumeState(c)}break;case"v2_message":{switch((s=e.message)==null?void 0:s.type){case"MEDIA_STATUS":{let u=(o=(n=e.message)==null?void 0:n.status)==null?void 0:o[0];this.syncMediaState(u);break}}break}}}loadMedia(){var o;let e=hn(this.params),t=(o=this.media)==null?void 0:o.currentTime,i=this.params.desiredState.seekState.getState(),r=t!=null?t:i.state!=="none"?i.position/1e3:0,n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();(0,oe.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,oe.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,oe.assertNonNullable)(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":B(this.params.desiredState.playbackState,"paused");break;case"PLAYING":B(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),B(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):B(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if((0,oe.isNullable)(e))return;let{level:t,muted:i}=e,r={muted:i!=null?i:!1,volume:t!=null?t:0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let s=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,s+=`, volume passed to state machine: ${r.volume}`),this.log({message:s}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};var be=require("@vkontakte/videoplayer-shared/es2015");var bf=a=>({castDevice:{friendlyName:a},remotePlayer:{},remotePlayerController:{},session:{}}),gf=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Ia=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new be.ValueSubject(null);this.sessionId$=new be.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new be.Subscription;this.subscriptionEvents=new be.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new be.ValueSubject(!1);this.presentationConnection$=new be.ValueSubject(null);this.message$=new be.ValueSubject(null);this.friendlyName$=new be.ValueSubject(null);this.errorEvent$=new be.Subject;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add((0,be.fromEvent)(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}connect(){return I(this,null,function*(){var e;this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let t=this.presentationRequest$.getValue();(0,be.assertNonNullable)(t,"connect with null presentationRequest");let i=yield t.start();this.handleConnection(i)}catch(t){switch(t==null?void 0:t.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:be.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}})}subscribe(){this.subscription.add((0,be.fromEvent)(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe((0,be.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,be.filter)(e=>!!e)).subscribe(e=>{let t=(0,be.fromEvent)(e,"message").subscribe(s=>{let n=JSON.parse(s.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(n),this.message$.next(n))}),i=(0,be.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,be.fromEvent)(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:be.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:s});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:U(M({},e),{sessionId:t})};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();(t==null?void 0:t.state)==="connected"&&(t==null||t.send(e))}catch(t){this.errorEvent$.next({category:be.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){var t;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":((t=e.message)==null?void 0:t.action)==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||gf()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new be.Subscription}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};var Qe=require("@vkontakte/videoplayer-shared/es2015");var Jt=class a{constructor(e){this.subscription=new Qe.Subscription;this.connection$=new Qe.ValueSubject(void 0);this.castState$=new Qe.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new Qe.Subject;let t=a.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Ia({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,Qe.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,Qe.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,Qe.filterChanged)())});this.subscription.add(e.pipe((0,Qe.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,Qe.filterChanged)()).subscribe(t=>{var r,s;let i=(s=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?s:"";this.connection$.next(t?bf(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){var e;this.log({message:"connect"}),(e=this.chromecastConnector)==null||e.connect()}disconnect(){var e;this.log({message:"disconnect"}),(e=this.chromecastConnector)==null||e.disconnect()}stopMedia(){return I(this,null,function*(){var e;this.log({message:"stopMedia"}),(e=this.chromecastConnector)==null||e.stopMedia()})}toggleConnection(){var t;let e=!!((t=this.chromecastConnector)!=null&&t.presentationConnection$.getValue());this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){var e;this.log({message:"destroy"}),(e=this.chromecastConnector)==null||e.destroy(),this.subscription.unsubscribe()}};var zl=Z(Ze(),1),Gl=Z(Si(),1),tT=Z(oc(),1);var Kg=Z(zc(),1);var Ut=require("@vkontakte/videoplayer-shared/es2015"),ne=class{constructor(e){this.transitionStarted$=new Ut.Subject;this.transitionEnded$=new Ut.Subject;this.transitionUpdated$=new Ut.Subject;this.forceChanged$=new Ut.Subject;this.stateChangeStarted$=(0,Ut.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Ut.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,Ut.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var le=require("@vkontakte/videoplayer-shared/es2015");var SR=5,yR=5,TR=500,Yg=7e3,Ba=class{constructor(e){this.subscription=new le.Subscription;this.loadMediaTimeoutSubscription=new le.Subscription;this.videoState=new ne("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,le.assertNever)(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:(0,le.assertNever)(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:(0,le.assertNever)(e)}break}default:(0,le.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ya(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 le.Subscription;this.subscription.add(e),this.subscription.add((0,le.merge)(this.videoState.stateChangeStarted$.pipe((0,le.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,le.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new le.Subject;e.add(r.pipe((0,le.debounce)(TR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,le.fromEvent)(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)>SR)&&r.next(o),s=o})),e.add((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<yR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),B(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:(0,le.assertNever)(n)}}),t((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,le.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,le.observableFrom)(["init"])).pipe((0,le.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=hn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),B(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"),B(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"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,le.timeout)(Yg).subscribe(()=>s(`timeout(${Yg})`)))});(0,Kg.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:le.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ul=Z(Ze(),1);var Va=require("@vkontakte/videoplayer-shared/es2015");var Xg=require("@vkontakte/videoplayer-shared/es2015"),Jg=a=>{try{a.pause(),a.playbackRate=0,(0,Xg.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Gn=require("@vkontakte/videoplayer-shared/es2015"),Gc=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)}},zn=(0,Va.getWindow)(),Yc=zn.WeakMap?new zn.WeakMap:new Gc,Kc=zn.WeakMap?new zn.WeakMap:new Map,IR=(a,e=20)=>{let t=0;return(0,Gn.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},et=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,Va.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),Yc.set(i,r);let s=new Gn.Subscription;return s.add(IR(i,e)),Kc.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},tt=a=>{let e=Kc.get(a);e==null||e.unsubscribe(),Kc.delete(a);let t=Yc.get(a);Yc.delete(a),t?(0,Va.clearVideoElement)(a):Jg(a)};var Xc=Z(Wi(),1),J=require("@vkontakte/videoplayer-shared/es2015");var Ti=require("@vkontakte/videoplayer-shared/es2015"),Yn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Ti.isNullable)(r),c=new Ti.Subscription;return r&&c.add(r.subscribe(d=>{let l=a.getState();i(d,l)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),c},jt=(a,e,t)=>Yn(e,()=>a.loop,i=>{(0,Ti.isNonNullable)(i)&&(a.loop=i)},{onError:t}),it=(a,e,t,i)=>Yn(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,Ti.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),bt=(a,e,t,i)=>Yn(e,()=>a.playbackRate,r=>{(0,Ti.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),_a=Yn;var ER=a=>["__",a.language,a.label].join("|"),wR=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Jc=class a{constructor(e){this.available$=new J.Subject;this.current$=new J.ValueSubject(void 0);this.error$=new J.Subject;this.subscription=new J.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:J.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(_a(t.internalTextTracks,()=>(0,Xc.default)(this.internalTracks),s=>{(0,J.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,J.isNonNullable)(s)&&(0,J.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,J.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(_a(t.externalTextTracks,()=>(0,Xc.default)(this.externalTracks),s=>{(0,J.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,J.isNonNullable)(s)&&(0,J.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,J.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(_a(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(_a(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,J.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,J.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,J.merge)((0,J.fromEvent)(e,"addtrack"),(0,J.fromEvent)(e,"removetrack"),(0,J.observableFrom)(["init"])).pipe((0,J.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,J.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,J.merge)((0,J.fromEvent)(e,"change"),(0,J.observableFrom)(["init"])).pipe((0,J.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,J.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,J.filterChanged)()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,J.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var c,d,l,p,h;let u=(d=(c=o.target)==null?void 0:c.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(l=o.target)==null?void 0:l.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,J.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,J.isNonNullable)(t.align)&&(r.align=t.align),(0,J.isNonNullable)(t.position)&&(r.position=t.position),(0,J.isNonNullable)(t.size)&&(r.size=t.size),(0,J.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,J.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,c,d,l;let{language:t,label:i}=e,r=e.id?e.id:ER(e),s=this.externalTracks.has(r),n=(c=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?c:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(l=this.internalTracks.get(r))==null?void 0:l.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,J.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,J.isNullable)(e)||!wR(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){(0,J.assertNonNullable)(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){(0,J.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},gt=Jc;var Zi=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 Zg=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},Zc=a=>{let e=Zg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ev=a=>{let e=Zg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var $=require("@vkontakte/videoplayer-shared/es2015");var xR=3,tv=(a,e,t=xR)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var rt=a=>{let e=_=>(0,$.fromEvent)(a,_).pipe((0,$.mapTo)(void 0),(0,$.shareReplay)(1)),t=new $.Subscription,i=()=>t.unsubscribe(),r=(0,$.merge)((0,$.fromEvent)(a,"progress"),(0,$.fromEvent)(a,"timeupdate")).pipe((0,$.map)(()=>tv(a.buffered,a.currentTime)),(0,$.shareReplay)(1)),s=G.browser.isSafari?(0,$.combine)({play:e("play").pipe((0,$.once)()),playing:e("playing")}).pipe((0,$.mapTo)(void 0),(0,$.shareReplay)(1)):e("playing"),n=(0,$.fromEvent)(a,"volumechange").pipe((0,$.map)(()=>({muted:a.muted,volume:a.volume})),(0,$.shareReplay)(1)),o=(0,$.fromEvent)(a,"ratechange").pipe((0,$.map)(()=>a.playbackRate),(0,$.shareReplay)(1)),u=(0,$.fromEvent)(a,"error").pipe((0,$.filter)(()=>!!(a.error||a.played.length)),(0,$.map)(()=>{var K;let _=a.error;return{id:_?`MediaError#${_.code}`:"HtmlVideoError",category:$.ErrorCategory.VIDEO_PIPELINE,message:_?_.message:"Error event from HTML video element",thrown:(K=a.error)!=null?K:void 0}}),(0,$.shareReplay)(1)),c=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(()=>a.currentTime),(0,$.shareReplay)(1)),d=["waiting","seeking","seeked","timeupdate"],l=new $.Subject,p=.3,h;t.add((0,$.merge)(...d.map(_=>(0,$.fromEvent)(a,_))).subscribe(_=>{let K=a.currentTime;a.loop&&(0,$.isNonNullable)(h)&&(0,$.isNonNullable)(K)&&h>=a.duration-p&&K<=p&&l.next(h),h=K}));let m=e("pause").pipe((0,$.filter)(()=>!a.error&&h!==a.duration),(0,$.shareReplay)(1)),b=(0,$.fromEvent)(a,"enterpictureinpicture").pipe((0,$.shareReplay)(1)),S=(0,$.fromEvent)(a,"leavepictureinpicture").pipe((0,$.shareReplay)(1)),v=new $.ValueSubject(ev(a));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let y=new $.ValueSubject(Zc(a)),x=(0,$.fromEvent)(a,"fullscreenchange").pipe((0,$.shareReplay)(1));t.add(x.pipe((0,$.map)(()=>Zc(a))).subscribe(y));let P=.1,D=1e3,V=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(_=>a.duration-a.currentTime<P),(0,$.filterChanged)(),(0,$.shareReplay)(1)),Q=(0,$.merge)(V.pipe((0,$.filter)(_=>!a.loop&&_)),(0,$.fromEvent)(a,"ended")).pipe((0,$.throttle)(D),(0,$.mapTo)(void 0),(0,$.shareReplay)(1)),F=(0,$.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(_=>(0,$.fromEvent)(a,_)),V.pipe((0,$.map)(_=>({type:_?"ended":"unknown"})))).pipe((0,$.map)(_=>G.browser.isFirefox&&_.type==="ended"?a.readyState<2:a.readyState<3),(0,$.filterChanged)(),(0,$.shareReplay)(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:Q,looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,$.fromEvent)(a,"durationchange").pipe((0,$.map)(()=>a.duration),(0,$.shareReplay)(1)),isBuffering$:F,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:y,enterPip$:b,leavePip$:S,destroy:i}};var ei=require("@vkontakte/videoplayer-shared/es2015"),Ii=a=>{switch(a){case"mobile":return ei.VideoQuality.Q_144P;case"lowest":return ei.VideoQuality.Q_240P;case"low":return ei.VideoQuality.Q_360P;case"sd":case"medium":return ei.VideoQuality.Q_480P;case"hd":case"high":return ei.VideoQuality.Q_720P;case"fullhd":case"full":return ei.VideoQuality.Q_1080P;case"quadhd":case"quad":return ei.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ei.VideoQuality.Q_2160P}};var Ye=Z(vt(),1),tl=Z(Ze(),1),er=Z(Si(),1),L=require("@vkontakte/videoplayer-shared/es2015");var el=!1,ti={},uv=a=>{el=a},cv=()=>{ti={}},lv=a=>{a(ti)},Oa=(a,e)=>{var t;el&&(ti.meta=(t=ti.meta)!=null?t:{},ti.meta[a]=e)},Ge=class{constructor(e){this.name=e}next(e){var i,r;if(!el)return;ti.series=(i=ti.series)!=null?i:{};let t=(r=ti.series[this.name])!=null?r:[];t.push([Date.now(),e]),ti.series[this.name]=t}};var Ce=require("@vkontakte/videoplayer-shared/es2015");function dv(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function _r(a,e,t){return(0,Ce.isNullable)(a)||(0,Ce.isNonNullable)(a.min)&&(0,Ce.isNonNullable)(a.max)&&(0,Ce.isLower)(a.max,a.min)||(0,Ce.isNonNullable)(a.min)&&e&&(0,Ce.isHigher)(a.min,e)||(0,Ce.isNonNullable)(a.max)&&t&&(0,Ce.isLower)(a.max,t)}function pv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return _r({max:a!=null&&a.max?(0,Ce.videoHeightToQuality)(a.max):void 0,min:a!=null&&a.min?(0,Ce.videoHeightToQuality)(a.min):void 0},e?(0,Ce.videoHeightToQuality)(e):void 0,t?(0,Ce.videoHeightToQuality)(t):void 0)}var gv=new Ge("best_bitrate"),Xn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Or=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ei=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,L.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Jn='Assertion "ABR Tracks is empty array" failed',Kn=new WeakMap,hv=new WeakMap,fv=new WeakMap,Na=(a,e,t,i)=>{var u;let r=[...e].sort(Or(1)),s=[...t].sort(Or(1)),n=s.filter(c=>(0,L.isNonNullable)(c.bitrate)&&(0,L.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>i:!0),o=(u=(0,Ye.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Ye.default)(s,-1);return o&&(0,tl.default)(n,o)?o:n.length?(0,Ye.default)(n,-1):(0,Ye.default)(s,0)},Fa=(a,e,t,i)=>{var u;let r=Kn.get(e);r||(r=[...e].sort(Or(1)),Kn.set(e,r));let s=Kn.get(t);s||(s=[...t].sort(Or(1)),Kn.set(t,s));let n=fv.get(a);n||(n=s.filter(c=>(0,L.isNonNullable)(c.bitrate)&&(0,L.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>i:!0),fv.set(a,n));let o=(u=(0,Ye.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Ye.default)(s,-1);return o&&(0,tl.default)(n,o)?o:n.length?(0,Ye.default)(n,-1):(0,Ye.default)(s,0)},mv=a=>"quality"in a,Zn=(a,e,t,i)=>{var n;let r=(0,L.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,L.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,L.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=mv(o)?"video":"audio",c=mv(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
"use strict";var wT=Object.create;var sa=Object.defineProperty,xT=Object.defineProperties,PT=Object.getOwnPropertyDescriptor,kT=Object.getOwnPropertyDescriptors,AT=Object.getOwnPropertyNames,en=Object.getOwnPropertySymbols,Fd=Object.getPrototypeOf,eu=Object.prototype.hasOwnProperty,qd=Object.prototype.propertyIsEnumerable,RT=Reflect.get;var MT=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var Vt=Math.pow,Nd=(a,e,t)=>e in a?sa(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,M=(a,e)=>{for(var t in e||(e={}))eu.call(e,t)&&Nd(a,t,e[t]);if(en)for(var t of en(e))qd.call(e,t)&&Nd(a,t,e[t]);return a},U=(a,e)=>xT(a,kT(e));var fi=(a,e)=>{var t={};for(var i in a)eu.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&en)for(var i of en(a))e.indexOf(i)<0&&qd.call(a,i)&&(t[i]=a[i]);return t};var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),$T=(a,e)=>{for(var t in e)sa(a,t,{get:e[t],enumerable:!0})},Ud=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of AT(e))!eu.call(a,r)&&r!==t&&sa(a,r,{get:()=>e[r],enumerable:!(i=PT(e,r))||i.enumerable});return a};var Z=(a,e,t)=>(t=a!=null?wT(Fd(a)):{},Ud(e||!a||!a.__esModule?sa(t,"default",{value:a,enumerable:!0}):t,a)),CT=a=>Ud(sa({},"__esModule",{value:!0}),a);var jd=(a,e,t)=>RT(Fd(a),t,e);var I=(a,e,t)=>new Promise((i,r)=>{var s=u=>{try{o(t.next(u))}catch(c){r(c)}},n=u=>{try{o(t.throw(u))}catch(c){r(c)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),_t=function(a,e){this[0]=a,this[1]=e},he=(a,e,t)=>{var i=(n,o,u,c)=>{try{var d=t[n](o),l=(o=d.value)instanceof _t,p=d.done;Promise.resolve(l?o[0]:o).then(h=>l?i(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,c):u({value:h,done:p})).catch(h=>i("throw",h,u,c))}catch(h){c(h)}},r=n=>s[n]=o=>new Promise((u,c)=>i(n,o,u,c)),s={};return t=t.apply(a,e),s[MT("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var Ae=g((iu,Hd)=>{"use strict";var oa=function(a){return a&&a.Math===Math&&a};Hd.exports=oa(typeof globalThis=="object"&&globalThis)||oa(typeof window=="object"&&window)||oa(typeof self=="object"&&self)||oa(typeof global=="object"&&global)||oa(typeof iu=="object"&&iu)||function(){return this}()||Function("return this")()});var Le=g((PC,Qd)=>{"use strict";Qd.exports=function(a){try{return!!a()}catch(e){return!0}}});var ua=g((kC,Wd)=>{"use strict";var DT=Le();Wd.exports=!DT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ru=g((AC,Kd)=>{"use strict";var LT=ua(),Yd=Function.prototype,zd=Yd.apply,Gd=Yd.call;Kd.exports=typeof Reflect=="object"&&Reflect.apply||(LT?Gd.bind(zd):function(){return Gd.apply(zd,arguments)})});var Be=g((RC,Zd)=>{"use strict";var Xd=ua(),Jd=Function.prototype,au=Jd.call,BT=Xd&&Jd.bind.bind(au,au);Zd.exports=Xd?BT:function(a){return function(){return au.apply(a,arguments)}}});var qi=g((MC,tp)=>{"use strict";var ep=Be(),VT=ep({}.toString),_T=ep("".slice);tp.exports=function(a){return _T(VT(a),8,-1)}});var su=g(($C,ip)=>{"use strict";var OT=qi(),NT=Be();ip.exports=function(a){if(OT(a)==="Function")return NT(a)}});var Re=g((CC,rp)=>{"use strict";var nu=typeof document=="object"&&document.all;rp.exports=typeof nu=="undefined"&&nu!==void 0?function(a){return typeof a=="function"||a===nu}:function(a){return typeof a=="function"}});var ut=g((DC,ap)=>{"use strict";var FT=Le();ap.exports=!FT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ct=g((LC,sp)=>{"use strict";var qT=ua(),an=Function.prototype.call;sp.exports=qT?an.bind(an):function(){return an.apply(an,arguments)}});var ou=g(up=>{"use strict";var np={}.propertyIsEnumerable,op=Object.getOwnPropertyDescriptor,UT=op&&!np.call({1:2},1);up.f=UT?function(e){var t=op(this,e);return!!t&&t.enumerable}:np});var ca=g((VC,cp)=>{"use strict";cp.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var dp=g((_C,lp)=>{"use strict";var jT=Be(),HT=Le(),QT=qi(),uu=Object,WT=jT("".split);lp.exports=HT(function(){return!uu("z").propertyIsEnumerable(0)})?function(a){return QT(a)==="String"?WT(a,""):uu(a)}:uu});var la=g((OC,pp)=>{"use strict";pp.exports=function(a){return a==null}});var mi=g((NC,hp)=>{"use strict";var zT=la(),GT=TypeError;hp.exports=function(a){if(zT(a))throw new GT("Can't call method on "+a);return a}});var Ui=g((FC,fp)=>{"use strict";var YT=dp(),KT=mi();fp.exports=function(a){return YT(KT(a))}});var Je=g((qC,mp)=>{"use strict";var XT=Re();mp.exports=function(a){return typeof a=="object"?a!==null:XT(a)}});var ji=g((UC,bp)=>{"use strict";bp.exports={}});var Xt=g((jC,vp)=>{"use strict";var cu=ji(),lu=Ae(),JT=Re(),gp=function(a){return JT(a)?a:void 0};vp.exports=function(a,e){return arguments.length<2?gp(cu[a])||gp(lu[a]):cu[a]&&cu[a][e]||lu[a]&&lu[a][e]}});var da=g((HC,Sp)=>{"use strict";var ZT=Be();Sp.exports=ZT({}.isPrototypeOf)});var Hi=g((QC,Ip)=>{"use strict";var eI=Ae(),yp=eI.navigator,Tp=yp&&yp.userAgent;Ip.exports=Tp?String(Tp):""});var pu=g((WC,Ap)=>{"use strict";var kp=Ae(),du=Hi(),Ep=kp.process,wp=kp.Deno,xp=Ep&&Ep.versions||wp&&wp.version,Pp=xp&&xp.v8,xt,sn;Pp&&(xt=Pp.split("."),sn=xt[0]>0&&xt[0]<4?1:+(xt[0]+xt[1]));!sn&&du&&(xt=du.match(/Edge\/(\d+)/),(!xt||xt[1]>=74)&&(xt=du.match(/Chrome\/(\d+)/),xt&&(sn=+xt[1])));Ap.exports=sn});var hu=g((zC,Mp)=>{"use strict";var Rp=pu(),tI=Le(),iI=Ae(),rI=iI.String;Mp.exports=!!Object.getOwnPropertySymbols&&!tI(function(){var a=Symbol("symbol detection");return!rI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Rp&&Rp<41})});var fu=g((GC,$p)=>{"use strict";var aI=hu();$p.exports=aI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mu=g((YC,Cp)=>{"use strict";var sI=Xt(),nI=Re(),oI=da(),uI=fu(),cI=Object;Cp.exports=uI?function(a){return typeof a=="symbol"}:function(a){var e=sI("Symbol");return nI(e)&&oI(e.prototype,cI(a))}});var pa=g((KC,Dp)=>{"use strict";var lI=String;Dp.exports=function(a){try{return lI(a)}catch(e){return"Object"}}});var Nt=g((XC,Lp)=>{"use strict";var dI=Re(),pI=pa(),hI=TypeError;Lp.exports=function(a){if(dI(a))return a;throw new hI(pI(a)+" is not a function")}});var ha=g((JC,Bp)=>{"use strict";var fI=Nt(),mI=la();Bp.exports=function(a,e){var t=a[e];return mI(t)?void 0:fI(t)}});var _p=g((ZC,Vp)=>{"use strict";var bu=ct(),gu=Re(),vu=Je(),bI=TypeError;Vp.exports=function(a,e){var t,i;if(e==="string"&&gu(t=a.toString)&&!vu(i=bu(t,a))||gu(t=a.valueOf)&&!vu(i=bu(t,a))||e!=="string"&&gu(t=a.toString)&&!vu(i=bu(t,a)))return i;throw new bI("Can't convert object to primitive value")}});var Pt=g((eD,Op)=>{"use strict";Op.exports=!0});var qp=g((tD,Fp)=>{"use strict";var Np=Ae(),gI=Object.defineProperty;Fp.exports=function(a,e){try{gI(Np,a,{value:e,configurable:!0,writable:!0})}catch(t){Np[a]=e}return e}});var fa=g((iD,Hp)=>{"use strict";var vI=Pt(),SI=Ae(),yI=qp(),Up="__core-js_shared__",jp=Hp.exports=SI[Up]||yI(Up,{});(jp.versions||(jp.versions=[])).push({version:"3.43.0",mode:vI?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Su=g((rD,Wp)=>{"use strict";var Qp=fa();Wp.exports=function(a,e){return Qp[a]||(Qp[a]=e||{})}});var yr=g((aD,zp)=>{"use strict";var TI=mi(),II=Object;zp.exports=function(a){return II(TI(a))}});var kt=g((sD,Gp)=>{"use strict";var EI=Be(),wI=yr(),xI=EI({}.hasOwnProperty);Gp.exports=Object.hasOwn||function(e,t){return xI(wI(e),t)}});var yu=g((nD,Yp)=>{"use strict";var PI=Be(),kI=0,AI=Math.random(),RI=PI(1.1.toString);Yp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+RI(++kI+AI,36)}});var je=g((oD,Xp)=>{"use strict";var MI=Ae(),$I=Su(),Kp=kt(),CI=yu(),DI=hu(),LI=fu(),Tr=MI.Symbol,Tu=$I("wks"),BI=LI?Tr.for||Tr:Tr&&Tr.withoutSetter||CI;Xp.exports=function(a){return Kp(Tu,a)||(Tu[a]=DI&&Kp(Tr,a)?Tr[a]:BI("Symbol."+a)),Tu[a]}});var th=g((uD,eh)=>{"use strict";var VI=ct(),Jp=Je(),Zp=mu(),_I=ha(),OI=_p(),NI=je(),FI=TypeError,qI=NI("toPrimitive");eh.exports=function(a,e){if(!Jp(a)||Zp(a))return a;var t=_I(a,qI),i;if(t){if(e===void 0&&(e="default"),i=VI(t,a,e),!Jp(i)||Zp(i))return i;throw new FI("Can't convert object to primitive value")}return e===void 0&&(e="number"),OI(a,e)}});var Iu=g((cD,ih)=>{"use strict";var UI=th(),jI=mu();ih.exports=function(a){var e=UI(a,"string");return jI(e)?e:e+""}});var nn=g((lD,ah)=>{"use strict";var HI=Ae(),rh=Je(),Eu=HI.document,QI=rh(Eu)&&rh(Eu.createElement);ah.exports=function(a){return QI?Eu.createElement(a):{}}});var wu=g((dD,sh)=>{"use strict";var WI=ut(),zI=Le(),GI=nn();sh.exports=!WI&&!zI(function(){return Object.defineProperty(GI("div"),"a",{get:function(){return 7}}).a!==7})});var uh=g(oh=>{"use strict";var YI=ut(),KI=ct(),XI=ou(),JI=ca(),ZI=Ui(),eE=Iu(),tE=kt(),iE=wu(),nh=Object.getOwnPropertyDescriptor;oh.f=YI?nh:function(e,t){if(e=ZI(e),t=eE(t),iE)try{return nh(e,t)}catch(i){}if(tE(e,t))return JI(!KI(XI.f,e,t),e[t])}});var xu=g((hD,ch)=>{"use strict";var rE=Le(),aE=Re(),sE=/#|\.prototype\./,ma=function(a,e){var t=oE[nE(a)];return t===cE?!0:t===uE?!1:aE(e)?rE(e):!!e},nE=ma.normalize=function(a){return String(a).replace(sE,".").toLowerCase()},oE=ma.data={},uE=ma.NATIVE="N",cE=ma.POLYFILL="P";ch.exports=ma});var Ir=g((fD,dh)=>{"use strict";var lh=su(),lE=Nt(),dE=ua(),pE=lh(lh.bind);dh.exports=function(a,e){return lE(a),e===void 0?a:dE?pE(a,e):function(){return a.apply(e,arguments)}}});var Pu=g((mD,ph)=>{"use strict";var hE=ut(),fE=Le();ph.exports=hE&&fE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ft=g((bD,hh)=>{"use strict";var mE=Je(),bE=String,gE=TypeError;hh.exports=function(a){if(mE(a))return a;throw new gE(bE(a)+" is not an object")}});var Qi=g(mh=>{"use strict";var vE=ut(),SE=wu(),yE=Pu(),on=Ft(),fh=Iu(),TE=TypeError,ku=Object.defineProperty,IE=Object.getOwnPropertyDescriptor,Au="enumerable",Ru="configurable",Mu="writable";mh.f=vE?yE?function(e,t,i){if(on(e),t=fh(t),on(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Mu in i&&!i[Mu]){var r=IE(e,t);r&&r[Mu]&&(e[t]=i.value,i={configurable:Ru in i?i[Ru]:r[Ru],enumerable:Au in i?i[Au]:r[Au],writable:!1})}return ku(e,t,i)}:ku:function(e,t,i){if(on(e),t=fh(t),on(i),SE)try{return ku(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new TE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Er=g((vD,bh)=>{"use strict";var EE=ut(),wE=Qi(),xE=ca();bh.exports=EE?function(a,e,t){return wE.f(a,e,xE(1,t))}:function(a,e,t){return a[e]=t,a}});var $e=g((SD,vh)=>{"use strict";var ba=Ae(),PE=ru(),kE=su(),AE=Re(),RE=uh().f,ME=xu(),wr=ji(),$E=Ir(),xr=Er(),gh=kt();fa();var CE=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return PE(a,this,arguments)};return e.prototype=a.prototype,e};vh.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ba:r?ba[t]:ba[t]&&ba[t].prototype,o=i?wr:wr[t]||xr(wr,t,{})[t],u=o.prototype,c,d,l,p,h,m,b,S,v;for(p in e)c=ME(i?p:t+(r?".":"#")+p,a.forced),d=!c&&n&&gh(n,p),m=o[p],d&&(a.dontCallGetSet?(v=RE(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!c&&!s&&typeof m==typeof h)&&(a.bind&&d?S=$E(h,ba):a.wrap&&d?S=CE(h):s&&AE(h)?S=kE(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&xr(S,"sham",!0),xr(o,p,S),s&&(l=t+"Prototype",gh(wr,l)||xr(wr,l,{}),xr(wr[l],p,h),a.real&&u&&(c||!u[p])&&xr(u,p,h)))}});var un=g((yD,yh)=>{"use strict";var DE=Su(),LE=yu(),Sh=DE("keys");yh.exports=function(a){return Sh[a]||(Sh[a]=LE(a))}});var Ih=g((TD,Th)=>{"use strict";var BE=Le();Th.exports=!BE(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var cn=g((ID,wh)=>{"use strict";var VE=kt(),_E=Re(),OE=yr(),NE=un(),FE=Ih(),Eh=NE("IE_PROTO"),$u=Object,qE=$u.prototype;wh.exports=FE?$u.getPrototypeOf:function(a){var e=OE(a);if(VE(e,Eh))return e[Eh];var t=e.constructor;return _E(t)&&e instanceof t?t.prototype:e instanceof $u?qE:null}});var Ph=g((ED,xh)=>{"use strict";var UE=Math.ceil,jE=Math.floor;xh.exports=Math.trunc||function(e){var t=+e;return(t>0?jE:UE)(t)}});var ga=g((wD,kh)=>{"use strict";var HE=Ph();kh.exports=function(a){var e=+a;return e!==e||e===0?0:HE(e)}});var Rh=g((xD,Ah)=>{"use strict";var QE=ga(),WE=Math.max,zE=Math.min;Ah.exports=function(a,e){var t=QE(a);return t<0?WE(t+e,0):zE(t,e)}});var Cu=g((PD,Mh)=>{"use strict";var GE=ga(),YE=Math.min;Mh.exports=function(a){var e=GE(a);return e>0?YE(e,9007199254740991):0}});var Pr=g((kD,$h)=>{"use strict";var KE=Cu();$h.exports=function(a){return KE(a.length)}});var Du=g((AD,Dh)=>{"use strict";var XE=Ui(),JE=Rh(),ZE=Pr(),Ch=function(a){return function(e,t,i){var r=XE(e),s=ZE(r);if(s===0)return!a&&-1;var n=JE(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Dh.exports={includes:Ch(!0),indexOf:Ch(!1)}});var ln=g((RD,Lh)=>{"use strict";Lh.exports={}});var _h=g((MD,Vh)=>{"use strict";var ew=Be(),Lu=kt(),tw=Ui(),iw=Du().indexOf,rw=ln(),Bh=ew([].push);Vh.exports=function(a,e){var t=tw(a),i=0,r=[],s;for(s in t)!Lu(rw,s)&&Lu(t,s)&&Bh(r,s);for(;e.length>i;)Lu(t,s=e[i++])&&(~iw(r,s)||Bh(r,s));return r}});var Bu=g(($D,Oh)=>{"use strict";Oh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Vu=g((CD,Nh)=>{"use strict";var aw=_h(),sw=Bu();Nh.exports=Object.keys||function(e){return aw(e,sw)}});var _u=g((DD,Hh)=>{"use strict";var qh=ut(),nw=Le(),Uh=Be(),ow=cn(),uw=Vu(),cw=Ui(),lw=ou().f,jh=Uh(lw),dw=Uh([].push),pw=qh&&nw(function(){var a=Object.create(null);return a[2]=2,!jh(a,2)}),Fh=function(a){return function(e){for(var t=cw(e),i=uw(t),r=pw&&ow(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!qh||(r?u in t:jh(t,u)))&&dw(o,a?[u,t[u]]:t[u]);return o}};Hh.exports={entries:Fh(!0),values:Fh(!1)}});var Qh=g(()=>{"use strict";var hw=$e(),fw=_u().values;hw({target:"Object",stat:!0},{values:function(e){return fw(e)}})});var zh=g((VD,Wh)=>{"use strict";Qh();var mw=ji();Wh.exports=mw.Object.values});var Yh=g((_D,Gh)=>{"use strict";var bw=zh();Gh.exports=bw});var Wi=g((OD,Kh)=>{"use strict";var gw=Yh();Kh.exports=gw});var va=g((ND,Xh)=>{"use strict";Xh.exports=function(){}});var Jh=g(()=>{"use strict";var vw=$e(),Sw=Du().includes,yw=Le(),Tw=va(),Iw=yw(function(){return!Array(1).includes()});vw({target:"Array",proto:!0,forced:Iw},{includes:function(e){return Sw(this,e,arguments.length>1?arguments[1]:void 0)}});Tw("includes")});var bi=g((UD,Zh)=>{"use strict";var Ew=Xt();Zh.exports=Ew});var tf=g((jD,ef)=>{"use strict";Jh();var ww=bi();ef.exports=ww("Array","includes")});var af=g((HD,rf)=>{"use strict";var xw=tf();rf.exports=xw});var Ze=g((QD,sf)=>{"use strict";var Pw=af();sf.exports=Pw});var yf=g(()=>{"use strict";var Vw=$e(),_w=_u().entries;Vw({target:"Object",stat:!0},{entries:function(e){return _w(e)}})});var If=g((_0,Tf)=>{"use strict";yf();var Ow=ji();Tf.exports=Ow.Object.entries});var wf=g((O0,Ef)=>{"use strict";var Nw=If();Ef.exports=Nw});var Si=g((N0,xf)=>{"use strict";var Fw=wf();xf.exports=Fw});var Gi=g((F0,Pf)=>{"use strict";Pf.exports={}});var Rf=g((q0,Af)=>{"use strict";var qw=Ae(),Uw=Re(),kf=qw.WeakMap;Af.exports=Uw(kf)&&/native code/.test(String(kf))});var Qu=g((U0,Cf)=>{"use strict";var jw=Rf(),$f=Ae(),Hw=Je(),Qw=Er(),Uu=kt(),ju=fa(),Ww=un(),zw=ln(),Mf="Object already initialized",Hu=$f.TypeError,Gw=$f.WeakMap,wn,Ea,xn,Yw=function(a){return xn(a)?Ea(a):wn(a,{})},Kw=function(a){return function(e){var t;if(!Hw(e)||(t=Ea(e)).type!==a)throw new Hu("Incompatible receiver, "+a+" required");return t}};jw||ju.state?(At=ju.state||(ju.state=new Gw),At.get=At.get,At.has=At.has,At.set=At.set,wn=function(a,e){if(At.has(a))throw new Hu(Mf);return e.facade=a,At.set(a,e),e},Ea=function(a){return At.get(a)||{}},xn=function(a){return At.has(a)}):(Yi=Ww("state"),zw[Yi]=!0,wn=function(a,e){if(Uu(a,Yi))throw new Hu(Mf);return e.facade=a,Qw(a,Yi,e),e},Ea=function(a){return Uu(a,Yi)?a[Yi]:{}},xn=function(a){return Uu(a,Yi)});var At,Yi;Cf.exports={set:wn,get:Ea,has:xn,enforce:Yw,getterFor:Kw}});var Gu=g((j0,Lf)=>{"use strict";var Wu=ut(),Xw=kt(),Df=Function.prototype,Jw=Wu&&Object.getOwnPropertyDescriptor,zu=Xw(Df,"name"),Zw=zu&&function(){}.name==="something",ex=zu&&(!Wu||Wu&&Jw(Df,"name").configurable);Lf.exports={EXISTS:zu,PROPER:Zw,CONFIGURABLE:ex}});var Vf=g(Bf=>{"use strict";var tx=ut(),ix=Pu(),rx=Qi(),ax=Ft(),sx=Ui(),nx=Vu();Bf.f=tx&&!ix?Object.defineProperties:function(e,t){ax(e);for(var i=sx(t),r=nx(t),s=r.length,n=0,o;s>n;)rx.f(e,o=r[n++],i[o]);return e}});var Yu=g((Q0,_f)=>{"use strict";var ox=Xt();_f.exports=ox("document","documentElement")});var Zu=g((W0,Hf)=>{"use strict";var ux=Ft(),cx=Vf(),Of=Bu(),lx=ln(),dx=Yu(),px=nn(),hx=un(),Nf=">",Ff="<",Xu="prototype",Ju="script",Uf=hx("IE_PROTO"),Ku=function(){},jf=function(a){return Ff+Ju+Nf+a+Ff+"/"+Ju+Nf},qf=function(a){a.write(jf("")),a.close();var e=a.parentWindow.Object;return a=null,e},fx=function(){var a=px("iframe"),e="java"+Ju+":",t;return a.style.display="none",dx.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(jf("document.F=Object")),t.close(),t.F},Pn,kn=function(){try{Pn=new ActiveXObject("htmlfile")}catch(e){}kn=typeof document!="undefined"?document.domain&&Pn?qf(Pn):fx():qf(Pn);for(var a=Of.length;a--;)delete kn[Xu][Of[a]];return kn()};lx[Uf]=!0;Hf.exports=Object.create||function(e,t){var i;return e!==null?(Ku[Xu]=ux(e),i=new Ku,Ku[Xu]=null,i[Uf]=e):i=kn(),t===void 0?i:cx.f(i,t)}});var Ar=g((z0,Qf)=>{"use strict";var mx=Er();Qf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:mx(a,e,t),a}});var rc=g((G0,Gf)=>{"use strict";var bx=Le(),gx=Re(),vx=Je(),Sx=Zu(),Wf=cn(),yx=Ar(),Tx=je(),Ix=Pt(),ic=Tx("iterator"),zf=!1,Zt,ec,tc;[].keys&&(tc=[].keys(),"next"in tc?(ec=Wf(Wf(tc)),ec!==Object.prototype&&(Zt=ec)):zf=!0);var Ex=!vx(Zt)||bx(function(){var a={};return Zt[ic].call(a)!==a});Ex?Zt={}:Ix&&(Zt=Sx(Zt));gx(Zt[ic])||yx(Zt,ic,function(){return this});Gf.exports={IteratorPrototype:Zt,BUGGY_SAFARI_ITERATORS:zf}});var An=g((Y0,Kf)=>{"use strict";var wx=je(),xx=wx("toStringTag"),Yf={};Yf[xx]="z";Kf.exports=String(Yf)==="[object z]"});var wa=g((K0,Xf)=>{"use strict";var Px=An(),kx=Re(),Rn=qi(),Ax=je(),Rx=Ax("toStringTag"),Mx=Object,$x=Rn(function(){return arguments}())==="Arguments",Cx=function(a,e){try{return a[e]}catch(t){}};Xf.exports=Px?Rn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=Cx(e=Mx(a),Rx))=="string"?t:$x?Rn(e):(i=Rn(e))==="Object"&&kx(e.callee)?"Arguments":i}});var Zf=g((X0,Jf)=>{"use strict";var Dx=An(),Lx=wa();Jf.exports=Dx?{}.toString:function(){return"[object "+Lx(this)+"]"}});var xa=g((J0,tm)=>{"use strict";var Bx=An(),Vx=Qi().f,_x=Er(),Ox=kt(),Nx=Zf(),Fx=je(),em=Fx("toStringTag");tm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(Ox(r,em)||Vx(r,em,{configurable:!0,value:e}),i&&!Bx&&_x(r,"toString",Nx))}});var rm=g((Z0,im)=>{"use strict";var qx=rc().IteratorPrototype,Ux=Zu(),jx=ca(),Hx=xa(),Qx=Gi(),Wx=function(){return this};im.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=Ux(qx,{next:jx(+!i,t)}),Hx(a,r,!1,!0),Qx[r]=Wx,a}});var sm=g((eB,am)=>{"use strict";var zx=Be(),Gx=Nt();am.exports=function(a,e,t){try{return zx(Gx(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var om=g((tB,nm)=>{"use strict";var Yx=Je();nm.exports=function(a){return Yx(a)||a===null}});var cm=g((iB,um)=>{"use strict";var Kx=om(),Xx=String,Jx=TypeError;um.exports=function(a){if(Kx(a))return a;throw new Jx("Can't set "+Xx(a)+" as a prototype")}});var ac=g((rB,lm)=>{"use strict";var Zx=sm(),eP=Je(),tP=mi(),iP=cm();lm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Zx(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return tP(r),iP(s),eP(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Tm=g((aB,ym)=>{"use strict";var rP=$e(),aP=ct(),Mn=Pt(),vm=Gu(),sP=Re(),nP=rm(),dm=cn(),pm=ac(),oP=xa(),uP=Er(),sc=Ar(),cP=je(),hm=Gi(),Sm=rc(),lP=vm.PROPER,dP=vm.CONFIGURABLE,fm=Sm.IteratorPrototype,$n=Sm.BUGGY_SAFARI_ITERATORS,Pa=cP("iterator"),mm="keys",ka="values",bm="entries",gm=function(){return this};ym.exports=function(a,e,t,i,r,s,n){nP(t,e,i);var o=function(v){if(v===r&&p)return p;if(!$n&&v&&v in d)return d[v];switch(v){case mm:return function(){return new t(this,v)};case ka:return function(){return new t(this,v)};case bm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,d=a.prototype,l=d[Pa]||d["@@iterator"]||r&&d[r],p=!$n&&l||o(r),h=e==="Array"&&d.entries||l,m,b,S;if(h&&(m=dm(h.call(new a)),m!==Object.prototype&&m.next&&(!Mn&&dm(m)!==fm&&(pm?pm(m,fm):sP(m[Pa])||sc(m,Pa,gm)),oP(m,u,!0,!0),Mn&&(hm[u]=gm))),lP&&r===ka&&l&&l.name!==ka&&(!Mn&&dP?uP(d,"name",ka):(c=!0,p=function(){return aP(l,this)})),r)if(b={values:o(ka),keys:s?p:o(mm),entries:o(bm)},n)for(S in b)($n||c||!(S in d))&&sc(d,S,b[S]);else rP({target:e,proto:!0,forced:$n||c},b);return(!Mn||n)&&d[Pa]!==p&&sc(d,Pa,p,{name:r}),hm[e]=p,b}});var Em=g((sB,Im)=>{"use strict";Im.exports=function(a,e){return{value:a,done:e}}});var oc=g((nB,Am)=>{"use strict";var pP=Ui(),nc=va(),wm=Gi(),Pm=Qu(),hP=Qi().f,fP=Tm(),Cn=Em(),mP=Pt(),bP=ut(),km="Array Iterator",gP=Pm.set,vP=Pm.getterFor(km);Am.exports=fP(Array,"Array",function(a,e){gP(this,{type:km,target:pP(a),index:0,kind:e})},function(){var a=vP(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,Cn(void 0,!0);switch(a.kind){case"keys":return Cn(t,!1);case"values":return Cn(e[t],!1)}return Cn([t,e[t]],!1)},"values");var xm=wm.Arguments=wm.Array;nc("keys");nc("values");nc("entries");if(!mP&&bP&&xm.name!=="values")try{hP(xm,"name",{value:"values"})}catch(a){}});var Mm=g((oB,Rm)=>{"use strict";var SP=je(),yP=Gi(),TP=SP("iterator"),IP=Array.prototype;Rm.exports=function(a){return a!==void 0&&(yP.Array===a||IP[TP]===a)}});var uc=g((uB,Cm)=>{"use strict";var EP=wa(),$m=ha(),wP=la(),xP=Gi(),PP=je(),kP=PP("iterator");Cm.exports=function(a){if(!wP(a))return $m(a,kP)||$m(a,"@@iterator")||xP[EP(a)]}});var Lm=g((cB,Dm)=>{"use strict";var AP=ct(),RP=Nt(),MP=Ft(),$P=pa(),CP=uc(),DP=TypeError;Dm.exports=function(a,e){var t=arguments.length<2?CP(a):e;if(RP(t))return MP(AP(t,a));throw new DP($P(a)+" is not iterable")}});var _m=g((lB,Vm)=>{"use strict";var LP=ct(),Bm=Ft(),BP=ha();Vm.exports=function(a,e,t){var i,r;Bm(a);try{if(i=BP(a,"return"),!i){if(e==="throw")throw t;return t}i=LP(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Bm(i),t}});var Ln=g((dB,qm)=>{"use strict";var VP=Ir(),_P=ct(),OP=Ft(),NP=pa(),FP=Mm(),qP=Pr(),Om=da(),UP=Lm(),jP=uc(),Nm=_m(),HP=TypeError,Dn=function(a,e){this.stopped=a,this.result=e},Fm=Dn.prototype;qm.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=VP(e,i),c,d,l,p,h,m,b,S=function(y){return c&&Nm(c,"normal"),new Dn(!0,y)},v=function(y){return r?(OP(y),o?u(y[0],y[1],S):u(y[0],y[1])):o?u(y,S):u(y)};if(s)c=a.iterator;else if(n)c=a;else{if(d=jP(a),!d)throw new HP(NP(a)+" is not iterable");if(FP(d)){for(l=0,p=qP(a);p>l;l++)if(h=v(a[l]),h&&Om(Fm,h))return h;return new Dn(!1)}c=UP(a,d)}for(m=s?a.next:c.next;!(b=_P(m,c)).done;){try{h=v(b.value)}catch(y){Nm(c,"throw",y)}if(typeof h=="object"&&h&&Om(Fm,h))return h}return new Dn(!1)}});var jm=g((pB,Um)=>{"use strict";var QP=ut(),WP=Qi(),zP=ca();Um.exports=function(a,e,t){QP?WP.f(a,e,zP(0,t)):a[e]=t}});var Hm=g(()=>{"use strict";var GP=$e(),YP=Ln(),KP=jm();GP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return YP(e,function(i,r){KP(t,i,r)},{AS_ENTRIES:!0}),t}})});var Wm=g((mB,Qm)=>{"use strict";oc();Hm();var XP=ji();Qm.exports=XP.Object.fromEntries});var Gm=g((bB,zm)=>{"use strict";zm.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Km=g(()=>{"use strict";oc();var JP=Gm(),ZP=Ae(),ek=xa(),Ym=Gi();for(Bn in JP)ek(ZP[Bn],Bn),Ym[Bn]=Ym.Array;var Bn});var Jm=g((SB,Xm)=>{"use strict";var tk=Wm();Km();Xm.exports=tk});var cc=g((yB,Zm)=>{"use strict";var ik=Jm();Zm.exports=ik});var eb=g(()=>{"use strict"});var lc=g((EB,tb)=>{"use strict";var Aa=Ae(),rk=Hi(),ak=qi(),Vn=function(a){return rk.slice(0,a.length)===a};tb.exports=function(){return Vn("Bun/")?"BUN":Vn("Cloudflare-Workers")?"CLOUDFLARE":Vn("Deno/")?"DENO":Vn("Node.js/")?"NODE":Aa.Bun&&typeof Bun.version=="string"?"BUN":Aa.Deno&&typeof Deno.version=="object"?"DENO":ak(Aa.process)==="process"?"NODE":Aa.window&&Aa.document?"BROWSER":"REST"}()});var _n=g((wB,ib)=>{"use strict";var sk=lc();ib.exports=sk==="NODE"});var ab=g((xB,rb)=>{"use strict";var nk=Qi();rb.exports=function(a,e,t){return nk.f(a,e,t)}});var ob=g((PB,nb)=>{"use strict";var ok=Xt(),uk=ab(),ck=je(),lk=ut(),sb=ck("species");nb.exports=function(a){var e=ok(a);lk&&e&&!e[sb]&&uk(e,sb,{configurable:!0,get:function(){return this}})}});var cb=g((kB,ub)=>{"use strict";var dk=da(),pk=TypeError;ub.exports=function(a,e){if(dk(e,a))return a;throw new pk("Incorrect invocation")}});var pc=g((AB,lb)=>{"use strict";var hk=Be(),fk=Re(),dc=fa(),mk=hk(Function.toString);fk(dc.inspectSource)||(dc.inspectSource=function(a){return mk(a)});lb.exports=dc.inspectSource});var fc=g((RB,mb)=>{"use strict";var bk=Be(),gk=Le(),db=Re(),vk=wa(),Sk=Xt(),yk=pc(),pb=function(){},hb=Sk("Reflect","construct"),hc=/^\s*(?:class|function)\b/,Tk=bk(hc.exec),Ik=!hc.test(pb),Ra=function(e){if(!db(e))return!1;try{return hb(pb,[],e),!0}catch(t){return!1}},fb=function(e){if(!db(e))return!1;switch(vk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ik||!!Tk(hc,yk(e))}catch(t){return!0}};fb.sham=!0;mb.exports=!hb||gk(function(){var a;return Ra(Ra.call)||!Ra(Object)||!Ra(function(){a=!0})||a})?fb:Ra});var gb=g((MB,bb)=>{"use strict";var Ek=fc(),wk=pa(),xk=TypeError;bb.exports=function(a){if(Ek(a))return a;throw new xk(wk(a)+" is not a constructor")}});var mc=g(($B,Sb)=>{"use strict";var vb=Ft(),Pk=gb(),kk=la(),Ak=je(),Rk=Ak("species");Sb.exports=function(a,e){var t=vb(a).constructor,i;return t===void 0||kk(i=vb(t)[Rk])?e:Pk(i)}});var Tb=g((CB,yb)=>{"use strict";var Mk=Be();yb.exports=Mk([].slice)});var Eb=g((DB,Ib)=>{"use strict";var $k=TypeError;Ib.exports=function(a,e){if(a<e)throw new $k("Not enough arguments");return a}});var bc=g((LB,wb)=>{"use strict";var Ck=Hi();wb.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Ck)});var xc=g((BB,Db)=>{"use strict";var dt=Ae(),Dk=ru(),Lk=Ir(),xb=Re(),Bk=kt(),Cb=Le(),Pb=Yu(),Vk=Tb(),kb=nn(),_k=Eb(),Ok=bc(),Nk=_n(),Ic=dt.setImmediate,Ec=dt.clearImmediate,Fk=dt.process,gc=dt.Dispatch,qk=dt.Function,Ab=dt.MessageChannel,Uk=dt.String,vc=0,Ma={},Rb="onreadystatechange",$a,Ki,Sc,yc;Cb(function(){$a=dt.location});var wc=function(a){if(Bk(Ma,a)){var e=Ma[a];delete Ma[a],e()}},Tc=function(a){return function(){wc(a)}},Mb=function(a){wc(a.data)},$b=function(a){dt.postMessage(Uk(a),$a.protocol+"//"+$a.host)};(!Ic||!Ec)&&(Ic=function(e){_k(arguments.length,1);var t=xb(e)?e:qk(e),i=Vk(arguments,1);return Ma[++vc]=function(){Dk(t,void 0,i)},Ki(vc),vc},Ec=function(e){delete Ma[e]},Nk?Ki=function(a){Fk.nextTick(Tc(a))}:gc&&gc.now?Ki=function(a){gc.now(Tc(a))}:Ab&&!Ok?(Sc=new Ab,yc=Sc.port2,Sc.port1.onmessage=Mb,Ki=Lk(yc.postMessage,yc)):dt.addEventListener&&xb(dt.postMessage)&&!dt.importScripts&&$a&&$a.protocol!=="file:"&&!Cb($b)?(Ki=$b,dt.addEventListener("message",Mb,!1)):Rb in kb("script")?Ki=function(a){Pb.appendChild(kb("script"))[Rb]=function(){Pb.removeChild(this),wc(a)}}:Ki=function(a){setTimeout(Tc(a),0)});Db.exports={set:Ic,clear:Ec}});var Vb=g((VB,Bb)=>{"use strict";var Lb=Ae(),jk=ut(),Hk=Object.getOwnPropertyDescriptor;Bb.exports=function(a){if(!jk)return Lb[a];var e=Hk(Lb,a);return e&&e.value}});var Pc=g((_B,Ob)=>{"use strict";var _b=function(){this.head=null,this.tail=null};_b.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}}};Ob.exports=_b});var Fb=g((OB,Nb)=>{"use strict";var Qk=Hi();Nb.exports=/ipad|iphone|ipod/i.test(Qk)&&typeof Pebble!="undefined"});var Ub=g((NB,qb)=>{"use strict";var Wk=Hi();qb.exports=/web0s(?!.*chrome)/i.test(Wk)});var Yb=g((FB,Gb)=>{"use strict";var Mr=Ae(),zk=Vb(),jb=Ir(),kc=xc().set,Gk=Pc(),Yk=bc(),Kk=Fb(),Xk=Ub(),Ac=_n(),Hb=Mr.MutationObserver||Mr.WebKitMutationObserver,Qb=Mr.document,Wb=Mr.process,On=Mr.Promise,$c=zk("queueMicrotask"),Rr,Rc,Mc,Nn,zb;$c||(Ca=new Gk,Da=function(){var a,e;for(Ac&&(a=Wb.domain)&&a.exit();e=Ca.get();)try{e()}catch(t){throw Ca.head&&Rr(),t}a&&a.enter()},!Yk&&!Ac&&!Xk&&Hb&&Qb?(Rc=!0,Mc=Qb.createTextNode(""),new Hb(Da).observe(Mc,{characterData:!0}),Rr=function(){Mc.data=Rc=!Rc}):!Kk&&On&&On.resolve?(Nn=On.resolve(void 0),Nn.constructor=On,zb=jb(Nn.then,Nn),Rr=function(){zb(Da)}):Ac?Rr=function(){Wb.nextTick(Da)}:(kc=jb(kc,Mr),Rr=function(){kc(Da)}),$c=function(a){Ca.head||Rr(),Ca.add(a)});var Ca,Da;Gb.exports=$c});var Xb=g((qB,Kb)=>{"use strict";Kb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Fn=g((UB,Jb)=>{"use strict";Jb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Xi=g((jB,Zb)=>{"use strict";var Jk=Ae();Zb.exports=Jk.Promise});var $r=g((HB,rg)=>{"use strict";var Zk=Ae(),La=Xi(),eA=Re(),tA=xu(),iA=pc(),rA=je(),eg=lc(),aA=Pt(),Cc=pu(),tg=La&&La.prototype,sA=rA("species"),Dc=!1,ig=eA(Zk.PromiseRejectionEvent),nA=tA("Promise",function(){var a=iA(La),e=a!==String(La);if(!e&&Cc===66||aA&&!(tg.catch&&tg.finally))return!0;if(!Cc||Cc<51||!/native code/.test(a)){var t=new La(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[sA]=i,Dc=t.then(function(){})instanceof i,!Dc)return!0}return!e&&(eg==="BROWSER"||eg==="DENO")&&!ig});rg.exports={CONSTRUCTOR:nA,REJECTION_EVENT:ig,SUBCLASSING:Dc}});var Cr=g((QB,sg)=>{"use strict";var ag=Nt(),oA=TypeError,uA=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new oA("Bad Promise constructor");e=i,t=r}),this.resolve=ag(e),this.reject=ag(t)};sg.exports.f=function(a){return new uA(a)}});var xg=g(()=>{"use strict";var cA=$e(),lA=Pt(),Hn=_n(),yi=Ae(),dA=ji(),Vr=ct(),ng=Ar(),og=ac(),pA=xa(),hA=ob(),fA=Nt(),jn=Re(),mA=Je(),bA=cb(),gA=mc(),pg=xc().set,Oc=Yb(),vA=Xb(),SA=Fn(),yA=Pc(),hg=Qu(),Qn=Xi(),Nc=$r(),fg=Cr(),Wn="Promise",mg=Nc.CONSTRUCTOR,TA=Nc.REJECTION_EVENT,IA=Nc.SUBCLASSING,Lc=hg.getterFor(Wn),EA=hg.set,Dr=Qn&&Qn.prototype,Ji=Qn,qn=Dr,bg=yi.TypeError,Bc=yi.document,Fc=yi.process,Vc=fg.f,wA=Vc,xA=!!(Bc&&Bc.createEvent&&yi.dispatchEvent),gg="unhandledrejection",PA="rejectionhandled",ug=0,vg=1,kA=2,qc=1,Sg=2,Un,cg,yg,lg,Tg=function(a){var e;return mA(a)&&jn(e=a.then)?e:!1},Ig=function(a,e){var t=e.value,i=e.state===vg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,d;try{r?(i||(e.rejection===Sg&&RA(e),e.rejection=qc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new bg("Promise-chain cycle")):(c=Tg(u))?Vr(c,u,s,n):s(u)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},Eg=function(a,e){a.notified||(a.notified=!0,Oc(function(){for(var t=a.reactions,i;i=t.get();)Ig(i,a);a.notified=!1,e&&!a.rejection&&AA(a)}))},wg=function(a,e,t){var i,r;xA?(i=Bc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),yi.dispatchEvent(i)):i={promise:e,reason:t},!TA&&(r=yi["on"+a])?r(i):a===gg&&vA("Unhandled promise rejection",t)},AA=function(a){Vr(pg,yi,function(){var e=a.facade,t=a.value,i=dg(a),r;if(i&&(r=SA(function(){Hn?Fc.emit("unhandledRejection",t,e):wg(gg,e,t)}),a.rejection=Hn||dg(a)?Sg:qc,r.error))throw r.value})},dg=function(a){return a.rejection!==qc&&!a.parent},RA=function(a){Vr(pg,yi,function(){var e=a.facade;Hn?Fc.emit("rejectionHandled",e):wg(PA,e,a.value)})},Lr=function(a,e,t){return function(i){a(e,i,t)}},Br=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=kA,Eg(a,!0))},_c=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new bg("Promise can't be resolved itself");var i=Tg(e);i?Oc(function(){var r={done:!1};try{Vr(i,e,Lr(_c,r,a),Lr(Br,r,a))}catch(s){Br(r,s,a)}}):(a.value=e,a.state=vg,Eg(a,!1))}catch(r){Br({done:!1},r,a)}}};if(mg&&(Ji=function(e){bA(this,qn),fA(e),Vr(Un,this);var t=Lc(this);try{e(Lr(_c,t),Lr(Br,t))}catch(i){Br(t,i)}},qn=Ji.prototype,Un=function(e){EA(this,{type:Wn,done:!1,notified:!1,parent:!1,reactions:new yA,rejection:!1,state:ug,value:null})},Un.prototype=ng(qn,"then",function(e,t){var i=Lc(this),r=Vc(gA(this,Ji));return i.parent=!0,r.ok=jn(e)?e:!0,r.fail=jn(t)&&t,r.domain=Hn?Fc.domain:void 0,i.state===ug?i.reactions.add(r):Oc(function(){Ig(r,i)}),r.promise}),cg=function(){var a=new Un,e=Lc(a);this.promise=a,this.resolve=Lr(_c,e),this.reject=Lr(Br,e)},fg.f=Vc=function(a){return a===Ji||a===yg?new cg(a):wA(a)},!lA&&jn(Qn)&&Dr!==Object.prototype)){lg=Dr.then,IA||ng(Dr,"then",function(e,t){var i=this;return new Ji(function(r,s){Vr(lg,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Dr.constructor}catch(a){}og&&og(Dr,qn)}cA({global:!0,constructor:!0,wrap:!0,forced:mg},{Promise:Ji});yg=dA.Promise;pA(Ji,Wn,!1,!0);hA(Wn)});var Mg=g((GB,Rg)=>{"use strict";var MA=je(),kg=MA("iterator"),Ag=!1;try{Pg=0,Uc={next:function(){return{done:!!Pg++}},return:function(){Ag=!0}},Uc[kg]=function(){return this},Array.from(Uc,function(){throw 2})}catch(a){}var Pg,Uc;Rg.exports=function(a,e){try{if(!e&&!Ag)return!1}catch(r){return!1}var t=!1;try{var i={};i[kg]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var jc=g((YB,$g)=>{"use strict";var $A=Xi(),CA=Mg(),DA=$r().CONSTRUCTOR;$g.exports=DA||!CA(function(a){$A.all(a).then(void 0,function(){})})});var Cg=g(()=>{"use strict";var LA=$e(),BA=ct(),VA=Nt(),_A=Cr(),OA=Fn(),NA=Ln(),FA=jc();LA({target:"Promise",stat:!0,forced:FA},{all:function(e){var t=this,i=_A.f(t),r=i.resolve,s=i.reject,n=OA(function(){var o=VA(t.resolve),u=[],c=0,d=1;NA(e,function(l){var p=c++,h=!1;d++,BA(o,t,l).then(function(m){h||(h=!0,u[p]=m,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var Lg=g(()=>{"use strict";var qA=$e(),UA=Pt(),jA=$r().CONSTRUCTOR,Qc=Xi(),HA=Xt(),QA=Re(),WA=Ar(),Dg=Qc&&Qc.prototype;qA({target:"Promise",proto:!0,forced:jA,real:!0},{catch:function(a){return this.then(void 0,a)}});!UA&&QA(Qc)&&(Hc=HA("Promise").prototype.catch,Dg.catch!==Hc&&WA(Dg,"catch",Hc,{unsafe:!0}));var Hc});var Bg=g(()=>{"use strict";var zA=$e(),GA=ct(),YA=Nt(),KA=Cr(),XA=Fn(),JA=Ln(),ZA=jc();zA({target:"Promise",stat:!0,forced:ZA},{race:function(e){var t=this,i=KA.f(t),r=i.reject,s=XA(function(){var n=YA(t.resolve);JA(e,function(o){GA(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Vg=g(()=>{"use strict";var eR=$e(),tR=Cr(),iR=$r().CONSTRUCTOR;eR({target:"Promise",stat:!0,forced:iR},{reject:function(e){var t=tR.f(this),i=t.reject;return i(e),t.promise}})});var Wc=g((aV,_g)=>{"use strict";var rR=Ft(),aR=Je(),sR=Cr();_g.exports=function(a,e){if(rR(a),aR(e)&&e.constructor===a)return e;var t=sR.f(a),i=t.resolve;return i(e),t.promise}});var Fg=g(()=>{"use strict";var nR=$e(),oR=Xt(),Og=Pt(),uR=Xi(),Ng=$r().CONSTRUCTOR,cR=Wc(),lR=oR("Promise"),dR=Og&&!Ng;nR({target:"Promise",stat:!0,forced:Og||Ng},{resolve:function(e){return cR(dR&&this===lR?uR:this,e)}})});var qg=g(()=>{"use strict";xg();Cg();Lg();Bg();Vg();Fg()});var Qg=g(()=>{"use strict";var pR=$e(),hR=Pt(),zn=Xi(),fR=Le(),jg=Xt(),Hg=Re(),mR=mc(),Ug=Wc(),bR=Ar(),Gc=zn&&zn.prototype,gR=!!zn&&fR(function(){Gc.finally.call({then:function(){}},function(){})});pR({target:"Promise",proto:!0,real:!0,forced:gR},{finally:function(a){var e=mR(this,jg("Promise")),t=Hg(a);return this.then(t?function(i){return Ug(e,a()).then(function(){return i})}:a,t?function(i){return Ug(e,a()).then(function(){throw i})}:a)}});!hR&&Hg(zn)&&(zc=jg("Promise").prototype.finally,Gc.finally!==zc&&bR(Gc,"finally",zc,{unsafe:!0}));var zc});var zg=g((dV,Wg)=>{"use strict";eb();qg();Qg();var vR=bi();Wg.exports=vR("Promise","finally")});var Yg=g((pV,Gg)=>{"use strict";var SR=zg();Gg.exports=SR});var Yc=g((hV,Kg)=>{"use strict";var yR=Yg();Kg.exports=yR});var av=g(()=>{"use strict";var AR=$e(),RR=yr(),MR=Pr(),$R=ga(),CR=va();AR({target:"Array",proto:!0},{at:function(e){var t=RR(this),i=MR(t),r=$R(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});CR("at")});var nv=g((s_,sv)=>{"use strict";av();var DR=bi();sv.exports=DR("Array","at")});var uv=g((n_,ov)=>{"use strict";var LR=nv();ov.exports=LR});var vt=g((o_,cv)=>{"use strict";var BR=uv();cv.exports=BR});var bl=g((lF,qv)=>{"use strict";var KR=qi();qv.exports=Array.isArray||function(e){return KR(e)==="Array"}});var jv=g((dF,Uv)=>{"use strict";var XR=TypeError,JR=9007199254740991;Uv.exports=function(a){if(a>JR)throw XR("Maximum allowed index exceeded");return a}});var Wv=g((pF,Qv)=>{"use strict";var ZR=bl(),eM=Pr(),tM=jv(),iM=Ir(),Hv=function(a,e,t,i,r,s,n,o){for(var u=r,c=0,d=n?iM(n,o):!1,l,p;c<i;)c in t&&(l=d?d(t[c],c,e):t[c],s>0&&ZR(l)?(p=eM(l),u=Hv(a,e,l,p,u,s-1)-1):(tM(u+1),a[u]=l),u++),c++;return u};Qv.exports=Hv});var Kv=g((hF,Yv)=>{"use strict";var zv=bl(),rM=fc(),aM=Je(),sM=je(),nM=sM("species"),Gv=Array;Yv.exports=function(a){var e;return zv(a)&&(e=a.constructor,rM(e)&&(e===Gv||zv(e.prototype))?e=void 0:aM(e)&&(e=e[nM],e===null&&(e=void 0))),e===void 0?Gv:e}});var Jv=g((fF,Xv)=>{"use strict";var oM=Kv();Xv.exports=function(a,e){return new(oM(a))(e===0?0:e)}});var Zv=g(()=>{"use strict";var uM=$e(),cM=Wv(),lM=Nt(),dM=yr(),pM=Pr(),hM=Jv();uM({target:"Array",proto:!0},{flatMap:function(e){var t=dM(this),i=pM(t),r;return lM(e),r=hM(t,0),r.length=cM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var eS=g(()=>{"use strict";var fM=va();fM("flatMap")});var iS=g((SF,tS)=>{"use strict";Zv();eS();var mM=bi();tS.exports=mM("Array","flatMap")});var aS=g((yF,rS)=>{"use strict";var bM=iS();rS.exports=bM});var Ga=g((TF,sS)=>{"use strict";var gM=aS();sS.exports=gM});var Ka=g((OF,cS)=>{"use strict";var SM=wa(),yM=String;cS.exports=function(a){if(SM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return yM(a)}});var vl=g((NF,lS)=>{"use strict";lS.exports=`
|
|
7
|
+
\v\f\r \u2028\u2029\uFEFF`});var hS=g((FF,pS)=>{"use strict";var TM=Be(),IM=mi(),EM=Ka(),yl=vl(),dS=TM("".replace),wM=RegExp("^["+yl+"]+"),xM=RegExp("(^|[^"+yl+"])["+yl+"]+$"),Sl=function(a){return function(e){var t=EM(IM(e));return a&1&&(t=dS(t,wM,"")),a&2&&(t=dS(t,xM,"$1")),t}};pS.exports={start:Sl(1),end:Sl(2),trim:Sl(3)}});var gS=g((qF,bS)=>{"use strict";var PM=Gu().PROPER,kM=Le(),fS=vl(),mS="
";bS.exports=function(a){return kM(function(){return!!fS[a]()||mS[a]()!==mS||PM&&fS[a].name!==a})}});var Tl=g((UF,vS)=>{"use strict";var AM=hS().start,RM=gS();vS.exports=RM("trimStart")?function(){return AM(this)}:"".trimStart});var yS=g(()=>{"use strict";var MM=$e(),SS=Tl();MM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==SS},{trimLeft:SS})});var IS=g(()=>{"use strict";yS();var $M=$e(),TS=Tl();$M({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==TS},{trimStart:TS})});var wS=g((zF,ES)=>{"use strict";IS();var CM=bi();ES.exports=CM("String","trimLeft")});var PS=g((GF,xS)=>{"use strict";var DM=wS();xS.exports=DM});var AS=g((YF,kS)=>{"use strict";var LM=PS();kS.exports=LM});var MS=g(()=>{"use strict"});var $S=g(()=>{"use strict"});var DS=g(($q,CS)=>{"use strict";var BM=Je(),VM=qi(),_M=je(),OM=_M("match");CS.exports=function(a){var e;return BM(a)&&((e=a[OM])!==void 0?!!e:VM(a)==="RegExp")}});var VS=g((Cq,BS)=>{"use strict";var NM=Ae(),FM=Le(),LS=NM.RegExp,qM=!FM(function(){var a=!0;try{LS(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(LS.prototype,"flags").get.call(e);return o!==i||t!==i});BS.exports={correct:qM}});var OS=g((Dq,_S)=>{"use strict";var UM=Ft();_S.exports=function(){var a=UM(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 qS=g((Lq,FS)=>{"use strict";var jM=ct(),HM=kt(),QM=da(),NS=VS(),WM=OS(),zM=RegExp.prototype;FS.exports=NS.correct?function(a){return a.flags}:function(a){return!NS.correct&&QM(zM,a)&&!HM(a,"flags")?jM(WM,a):a.flags}});var jS=g((Bq,US)=>{"use strict";var xl=Be(),GM=yr(),YM=Math.floor,El=xl("".charAt),KM=xl("".replace),wl=xl("".slice),XM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,JM=/\$([$&'`]|\d{1,2})/g;US.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=JM;return r!==void 0&&(r=GM(r),u=XM),KM(s,u,function(c,d){var l;switch(El(d,0)){case"$":return"$";case"&":return a;case"`":return wl(e,0,t);case"'":return wl(e,n);case"<":l=r[wl(d,1,-1)];break;default:var p=+d;if(p===0)return c;if(p>o){var h=YM(p/10);return h===0?c:h<=o?i[h-1]===void 0?El(d,1):i[h-1]+El(d,1):c}l=i[p-1]}return l===void 0?"":l})}});var WS=g(()=>{"use strict";var ZM=$e(),e$=ct(),kl=Be(),HS=mi(),t$=Re(),i$=Je(),r$=DS(),Qr=Ka(),a$=ha(),s$=qS(),n$=jS(),o$=je(),u$=Pt(),c$=o$("replace"),l$=TypeError,Pl=kl("".indexOf),d$=kl("".replace),QS=kl("".slice),p$=Math.max;ZM({target:"String",proto:!0},{replaceAll:function(e,t){var i=HS(this),r,s,n,o,u,c,d,l,p,h,m=0,b="";if(i$(e)){if(r=r$(e),r&&(s=Qr(HS(s$(e))),!~Pl(s,"g")))throw new l$("`.replaceAll` does not allow non-global regexes");if(n=a$(e,c$),n)return e$(n,e,i,t);if(u$&&r)return d$(Qr(i),e,t)}for(o=Qr(i),u=Qr(e),c=t$(t),c||(t=Qr(t)),d=u.length,l=p$(1,d),p=Pl(o,u);p!==-1;)h=c?Qr(t(u,p,o)):n$(u,o,p,[],void 0,t),b+=QS(o,m,p)+h,m=p+d,p=p+l>o.length?-1:Pl(o,u,p+l);return m<o.length&&(b+=QS(o,m)),b}})});var GS=g((Oq,zS)=>{"use strict";MS();$S();WS();var h$=bi();zS.exports=h$("String","replaceAll")});var KS=g((Nq,YS)=>{"use strict";var f$=GS();YS.exports=f$});var JS=g((Fq,XS)=>{"use strict";var m$=KS();XS.exports=m$});var ey=g((qq,ZS)=>{"use strict";var b$=ga(),g$=Ka(),v$=mi(),S$=RangeError;ZS.exports=function(e){var t=g$(v$(this)),i="",r=b$(e);if(r<0||r===1/0)throw new S$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var sy=g((Uq,ay)=>{"use strict";var ry=Be(),y$=Cu(),ty=Ka(),T$=ey(),I$=mi(),E$=ry(T$),w$=ry("".slice),x$=Math.ceil,iy=function(a){return function(e,t,i){var r=ty(I$(e)),s=y$(t),n=r.length,o=i===void 0?" ":ty(i),u,c;return s<=n||o===""?r:(u=s-n,c=E$(o,x$(u/o.length)),c.length>u&&(c=w$(c,0,u)),a?r+c:c+r)}};ay.exports={start:iy(!1),end:iy(!0)}});var oy=g((jq,ny)=>{"use strict";var P$=Hi();ny.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(P$)});var uy=g(()=>{"use strict";var k$=$e(),A$=sy().start,R$=oy();k$({target:"String",proto:!0,forced:R$},{padStart:function(e){return A$(this,e,arguments.length>1?arguments[1]:void 0)}})});var ly=g((Wq,cy)=>{"use strict";uy();var M$=bi();cy.exports=M$("String","padStart")});var py=g((zq,dy)=>{"use strict";var $$=ly();dy.exports=$$});var fy=g((Gq,hy)=>{"use strict";var C$=py();hy.exports=C$});var IC={};$T(IC,{ChromecastState:()=>Sr,HttpConnectionType:()=>tn,Observable:()=>zt.Observable,PlaybackState:()=>Ue,Player:()=>Ns,PredefinedQualityLimits:()=>na,SDK_VERSION:()=>TC,Subject:()=>zt.Subject,Subscription:()=>zt.Subscription,Surface:()=>rn,VERSION:()=>tu,ValueSubject:()=>zt.ValueSubject,VideoFormat:()=>Ot,VideoQuality:()=>zt.VideoQuality,WebmCodecStrategy:()=>Ja,areValidLiveRecordSources:()=>gf,clientChecker:()=>G,isMobile:()=>gi});module.exports=CT(IC);var tu="2.0.151-dev.6dd94264.0";var Ue=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ue||{}),Ot=(P=>(P.MPEG="MPEG",P.DASH="DASH",P.DASH_SEP="DASH_SEP",P.DASH_SEP_VK="DASH_SEP",P.DASH_WEBM="DASH_WEBM",P.DASH_WEBM_AV1="DASH_WEBM_AV1",P.DASH_STREAMS="DASH_STREAMS",P.DASH_WEBM_VK="DASH_WEBM",P.DASH_ONDEMAND="DASH_ONDEMAND",P.DASH_ONDEMAND_VK="DASH_ONDEMAND",P.DASH_LIVE="DASH_LIVE",P.DASH_LIVE_CMAF="DASH_LIVE_CMAF",P.DASH_LIVE_WEBM="DASH_LIVE_WEBM",P.HLS="HLS",P.HLS_ONDEMAND="HLS_ONDEMAND",P.HLS_JS="HLS",P.HLS_FMP4="HLS_FMP4",P.HLS_LIVE="HLS_LIVE",P.HLS_LIVE_CMAF="HLS_LIVE_CMAF",P.WEB_RTC_LIVE="WEB_RTC_LIVE",P))(Ot||{});var Sr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Sr||{}),tn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(tn||{});var rn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(rn||{}),na=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(na||{});var ed=Z(Wi(),1),bT=Z(Ze(),1);var se=require("@vkontakte/videoplayer-shared/es2015");var nf=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var dn=class{constructor(e){this.connection$=new se.ValueSubject(void 0);this.castState$=new se.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new se.Subject;this.realCastState$=new se.ValueSubject("NOT_AVAILABLE");this.subscription=new se.Subscription;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,se.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||nf("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:se.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,se.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,se.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,se.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,se.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,se.assertNever)(r.sessionState)}})).add((0,se.merge)((0,se.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,se.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,se.map)(r=>r.castState)),(0,se.observableFrom)([i.getCastState()])).pipe((0,se.filterChanged)(),(0,se.map)(kw),(0,se.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=(0,se.isNonNullable)(this.connection$.getValue());if(s&&!n){let c=i.getCurrentSession();(0,se.assertNonNullable)(c);let d=c.getCastDevice(),l=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,se.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,se.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:se.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},kw=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(0,se.assertNever)(a)}};var oe=require("@vkontakte/videoplayer-shared/es2015");var Ve=require("@vkontakte/videoplayer-shared/es2015");var Ou=require("@vkontakte/videoplayer-shared/es2015");var He=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Ou.assertNever)(t)}return a},pn=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Ou.assertNever)(e)}};var fn=a=>{var l;let{source:e,format:t,meta:i,output:r}=a,s,n,o;switch(t){case"MPEG":{let p=e[t];(0,Ve.assertNonNullable)(p);let h=(0,Ve.getHighestQuality)(Object.keys(p));(0,Ve.assertNonNullable)(h);let m=p[h];(0,Ve.assertNonNullable)(m),s=m,n="video/mp4",o=hn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];(0,Ve.assertNonNullable)(p),s=p.url,n="application/x-mpegurl",o=hn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];(0,Ve.assertNonNullable)(p),s=p.url,n="application/dash+xml",o=hn();break}case"DASH_LIVE_CMAF":{let p=e[t];(0,Ve.assertNonNullable)(p),s=p.url,n="application/dash+xml",o=of();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];(0,Ve.assertNonNullable)(p),s=He(p.url),n="application/x-mpegurl",o=of();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let p="Unsupported format for Chromecast",h=new Error(p);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ve.ErrorCategory.VIDEO_PIPELINE,message:p,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return(0,Ve.assertNever)(t)}let u=Aw((l=i.videoId)!=null?l:s,n);u.contentUrl=s,u.streamType=o,u.metadata=Rw();let{title:c,subtitle:d}=i;return(0,Ve.isNonNullable)(c)&&(u.metadata.title=c),(0,Ve.isNonNullable)(d)&&(u.metadata.subtitle=d),u};function hn(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function of(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function Aw(a,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(a,e):{contentId:a,contentType:e,metadata:{title:"",subtitle:""},streamType:hn()}}function Rw(){var a,e;return(e=(a=chrome.cast)==null?void 0:a.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var B=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var mn=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};var Fu=require("@vkontakte/videoplayer-shared/es2015");var En=require("@vkontakte/videoplayer-shared/es2015");var uf=Z(Ze(),1),cf=require("@vkontakte/videoplayer-shared/es2015");var bn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,uf.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||c||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=(0,cf.getWindow)().navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var lf=Z(Ze(),1),vi=require("@vkontakte/videoplayer-shared/es2015");var gi=()=>{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 gn=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,lf.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||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.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=(0,vi.getWindow)();if(!(0,vi.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=gi()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return I(this,null,function*(){let e=(0,vi.getWindow)();if(!(0,vi.isBrowserWindow)(e))return;let{userAgentData:t}=e.navigator;if(t!=null&&t.getHighEntropyValues){let i=yield t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r.length>0,o=r.length>1,u="Unknown",c="Unknown";if(n){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(u=s[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(c=s[d]):d!==void 0&&(c=d)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&n&&typeof r[0]=="string"&&(c=s[1]);u=this.normalizeOSName(u),c=this.normalizeOSVersion(c,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:c||"Unknown",full:c&&c!=="Unknown"?`${u} ${c}`:u};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r[0],o=r[1],u=typeof n=="number"?s[n]!==void 0?this.normalizeVendorName(s[n]):"Unknown":this.normalizeVendorName(n),c="Unknown";typeof o=="number"?c=s[o]!==void 0?s[o]:"Unknown":o!==void 0?c=o:s[1]!==void 0?c=s[1]:s[0]!==void 0&&(c=s[0]),c=this.normalizeModelName(c,u),this.details.vendor=u,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=(0,vi.getWindow)();if(!(0,vi.isBrowserWindow)(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t!=null&&t[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var Sa=require("@vkontakte/videoplayer-shared/es2015"),vn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,Sa.getWindow)()}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 s;let e=(0,Sa.getWindow)();if(!(0,Sa.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((s=e.matchMedia("(dynamic-range: high)"))!=null&&s.matches),this._colorDepth=i.colorDepth}catch(n){console.error(n)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(n){console.error(n)}}};var zi=require("@vkontakte/videoplayer-shared/es2015");var lt=()=>window.ManagedMediaSource||window.MediaSource,kr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},df=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Sn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var pf,Mw=(pf=(0,zi.getWindow)().document)==null?void 0:pf.createElement("video"),$w='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Cw='video/mp4; codecs="hev1.1.6.L93.B0"',hf='video/webm; codecs="vp09.00.10.08"',ff='video/webm; codecs="av01.0.00M.08"',Dw='audio/mp4; codecs="mp4a.40.2"',Lw='audio/webm; codecs="opus"',mf,Bw=()=>I(null,null,function*(){let a=(0,zi.getWindow)();if(!(0,zi.isBrowserWindow)(a))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=yield Promise.all([a.navigator.mediaCapabilities.decodingInfo(U(M({},e),{video:U(M({},e.video),{contentType:ff})})),a.navigator.mediaCapabilities.decodingInfo(U(M({},e),{video:U(M({},e.video),{contentType:hf})}))]);mf={DASH_WEBM_AV1:t,DASH_WEBM:i}});Bw().catch(a=>{console.log(Mw),console.error(a)});var yn=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 mf}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,s,n,o,u,c,d,l,p,h,m,b,S,v,y,x,P,D,V;let e=(0,zi.getWindow)();if(!(0,zi.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:kr(),mse:df(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(s=this._video).canPlayType)!=null&&n.call(s,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((d=(c=this._video).canPlayType)!=null&&d.call(c,"video/webm")),cmaf:!0};let Q=!!((p=(l=lt())==null?void 0:l.isTypeSupported)!=null&&p.call(l,$w)),W=!!((m=(h=lt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,Cw)),F=!!((S=(b=lt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,Dw));this._codecs={h264:Q,h265:W,vp9:!!((y=(v=lt())==null?void 0:v.isTypeSupported)!=null&&y.call(v,hf)),av1:!!((P=(x=lt())==null?void 0:x.isTypeSupported)!=null&&P.call(x,ff)),aac:F,opus:!!((V=(D=lt())==null?void 0:D.isTypeSupported)!=null&&V.call(D,Lw)),mpeg:(Q||W)&&F},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(Q){console.error(Q)}try{this.destroyVideoElement()}catch(Q){console.error("Error destroying video element:",Q)}}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 In=require("@vkontakte/videoplayer-shared/es2015");var bf="audio/mpeg",Tn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,s,n;let e=(0,In.getWindow)();if(!(0,In.isBrowserWindow)(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!((r=(i=this._audio).canPlayType)!=null&&r.call(i,bf))},this._codecs={mp3:!!((n=(s=lt())==null?void 0:s.isTypeSupported)!=null&&n.call(s,bf))}}catch(o){console.error(o)}try{this.destroyAudioElement()}catch(o){console.error("Error destroying audio element:",o)}}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}};var Nu=class{constructor(){this.isInited$=new En.ValueSubject(!1);this._displayChecker=new vn,this._deviceChecker=new gn(this._displayChecker),this._browserChecker=new bn,this._videoChecker=new yn(this._deviceChecker,this._browserChecker),this._audioChecker=new Tn,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 I(this,null,function*(){(0,En.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))})}},G=new Nu;var qu=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=G.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return(0,Fu.assertNever)(o)}})},ya=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_FMP4":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(0,Fu.assertNever)(a)}},gf=a=>{let t=Object.keys(a).filter(i=>!ya(i));return qu(t).length>0};var Ta=class{constructor(e){this.subscription=new oe.Subscription;this.sessionId$=new oe.ValueSubject(null);this.mediaSessionId$=new oe.ValueSubject(null);this.contentId$=new oe.ValueSubject(null);this.isMobile=gi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var s,n,o;if((0,oe.isNullable)(e))return;this.media=e,this.mediaSessionId$.next((s=e.mediaSessionId)!=null?s:null);let t=(n=e.media)==null?void 0:n.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=(o=e.media)==null?void 0:o.duration;(0,oe.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,oe.isNonNullable)(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let c=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!c?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new mn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ya(e.format)),this.subscribe()}subscribe(){let e=r=>{var s;this.params.output.error$.next({category:oe.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:(s=r==null?void 0:r.message)!=null?s:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,oe.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,oe.filter)(oe.isNonNullable),(0,oe.filterChanged)(),(0,oe.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,oe.filterChanged)(),(0,oe.map)(Boolean));this.subscription.add((0,oe.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,oe.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,oe.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,oe.filter)(({mediaLoaded:r})=>r),(0,oe.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,oe.filter)(({mediaLoaded:r,playbackState:{from:s,to:n}})=>!r&&s==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,oe.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,oe.debounce)(30)),mediaLoaded:t}).pipe((0,oe.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:n}=r.to;this.setVolume(n,s)},e))}handleMessage(e){var t,i,r,s,n,o;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let u=(i=(t=e.message)==null?void 0:t.media)==null?void 0:i[0];this.syncMediaState(u);let c=(r=e.message)==null?void 0:r.receiver.volume;this.syncVolumeState(c)}break;case"v2_message":{switch((s=e.message)==null?void 0:s.type){case"MEDIA_STATUS":{let u=(o=(n=e.message)==null?void 0:n.status)==null?void 0:o[0];this.syncMediaState(u);break}}break}}}loadMedia(){var o;let e=fn(this.params),t=(o=this.media)==null?void 0:o.currentTime,i=this.params.desiredState.seekState.getState(),r=t!=null?t:i.state!=="none"?i.position/1e3:0,n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();(0,oe.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,oe.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,oe.assertNonNullable)(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":B(this.params.desiredState.playbackState,"paused");break;case"PLAYING":B(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),B(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):B(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if((0,oe.isNullable)(e))return;let{level:t,muted:i}=e,r={muted:i!=null?i:!1,volume:t!=null?t:0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let s=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,s+=`, volume passed to state machine: ${r.volume}`),this.log({message:s}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};var be=require("@vkontakte/videoplayer-shared/es2015");var vf=a=>({castDevice:{friendlyName:a},remotePlayer:{},remotePlayerController:{},session:{}}),Sf=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Ia=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new be.ValueSubject(null);this.sessionId$=new be.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new be.Subscription;this.subscriptionEvents=new be.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new be.ValueSubject(!1);this.presentationConnection$=new be.ValueSubject(null);this.message$=new be.ValueSubject(null);this.friendlyName$=new be.ValueSubject(null);this.errorEvent$=new be.Subject;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add((0,be.fromEvent)(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}connect(){return I(this,null,function*(){var e;this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let t=this.presentationRequest$.getValue();(0,be.assertNonNullable)(t,"connect with null presentationRequest");let i=yield t.start();this.handleConnection(i)}catch(t){switch(t==null?void 0:t.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:be.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}})}subscribe(){this.subscription.add((0,be.fromEvent)(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe((0,be.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,be.filter)(e=>!!e)).subscribe(e=>{let t=(0,be.fromEvent)(e,"message").subscribe(s=>{let n=JSON.parse(s.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(n),this.message$.next(n))}),i=(0,be.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,be.fromEvent)(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:be.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:s});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:U(M({},e),{sessionId:t})};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();(t==null?void 0:t.state)==="connected"&&(t==null||t.send(e))}catch(t){this.errorEvent$.next({category:be.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){var t;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":((t=e.message)==null?void 0:t.action)==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||Sf()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new be.Subscription}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};var Qe=require("@vkontakte/videoplayer-shared/es2015");var Jt=class a{constructor(e){this.subscription=new Qe.Subscription;this.connection$=new Qe.ValueSubject(void 0);this.castState$=new Qe.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new Qe.Subject;let t=a.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Ia({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,Qe.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,Qe.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,Qe.filterChanged)())});this.subscription.add(e.pipe((0,Qe.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,Qe.filterChanged)()).subscribe(t=>{var r,s;let i=(s=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?s:"";this.connection$.next(t?vf(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){var e;this.log({message:"connect"}),(e=this.chromecastConnector)==null||e.connect()}disconnect(){var e;this.log({message:"disconnect"}),(e=this.chromecastConnector)==null||e.disconnect()}stopMedia(){return I(this,null,function*(){var e;this.log({message:"stopMedia"}),(e=this.chromecastConnector)==null||e.stopMedia()})}toggleConnection(){var t;let e=!!((t=this.chromecastConnector)!=null&&t.presentationConnection$.getValue());this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){var e;this.log({message:"destroy"}),(e=this.chromecastConnector)==null||e.destroy(),this.subscription.unsubscribe()}};var Yl=Z(Ze(),1),Kl=Z(Si(),1),rT=Z(cc(),1);var Jg=Z(Yc(),1);var Ut=require("@vkontakte/videoplayer-shared/es2015"),ne=class{constructor(e){this.transitionStarted$=new Ut.Subject;this.transitionEnded$=new Ut.Subject;this.transitionUpdated$=new Ut.Subject;this.forceChanged$=new Ut.Subject;this.stateChangeStarted$=(0,Ut.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Ut.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,Ut.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var le=require("@vkontakte/videoplayer-shared/es2015");var TR=5,IR=5,ER=500,Xg=7e3,Ba=class{constructor(e){this.subscription=new le.Subscription;this.loadMediaTimeoutSubscription=new le.Subscription;this.videoState=new ne("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,le.assertNever)(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:(0,le.assertNever)(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:(0,le.assertNever)(e)}break}default:(0,le.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ya(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 le.Subscription;this.subscription.add(e),this.subscription.add((0,le.merge)(this.videoState.stateChangeStarted$.pipe((0,le.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,le.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new le.Subject;e.add(r.pipe((0,le.debounce)(ER)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,le.fromEvent)(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)>TR)&&r.next(o),s=o})),e.add((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<IR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),B(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:(0,le.assertNever)(n)}}),t((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,le.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,le.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,le.observableFrom)(["init"])).pipe((0,le.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=fn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),B(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"),B(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"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,le.timeout)(Xg).subscribe(()=>s(`timeout(${Xg})`)))});(0,Jg.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:le.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ll=Z(Ze(),1);var Va=require("@vkontakte/videoplayer-shared/es2015");var Zg=require("@vkontakte/videoplayer-shared/es2015"),ev=a=>{try{a.pause(),a.playbackRate=0,(0,Zg.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Yn=require("@vkontakte/videoplayer-shared/es2015"),Kc=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)}},Gn=(0,Va.getWindow)(),Xc=Gn.WeakMap?new Gn.WeakMap:new Kc,Jc=Gn.WeakMap?new Gn.WeakMap:new Map,wR=(a,e=20)=>{let t=0;return(0,Yn.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},et=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,Va.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),Xc.set(i,r);let s=new Yn.Subscription;return s.add(wR(i,e)),Jc.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},tt=a=>{let e=Jc.get(a);e==null||e.unsubscribe(),Jc.delete(a);let t=Xc.get(a);Xc.delete(a),t?(0,Va.clearVideoElement)(a):ev(a)};var Zc=Z(Wi(),1),J=require("@vkontakte/videoplayer-shared/es2015");var Ti=require("@vkontakte/videoplayer-shared/es2015"),Kn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Ti.isNullable)(r),c=new Ti.Subscription;return r&&c.add(r.subscribe(d=>{let l=a.getState();i(d,l)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),c},jt=(a,e,t)=>Kn(e,()=>a.loop,i=>{(0,Ti.isNonNullable)(i)&&(a.loop=i)},{onError:t}),it=(a,e,t,i)=>Kn(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,Ti.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),bt=(a,e,t,i)=>Kn(e,()=>a.playbackRate,r=>{(0,Ti.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),_a=Kn;var xR=a=>["__",a.language,a.label].join("|"),PR=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},el=class a{constructor(e){this.available$=new J.Subject;this.current$=new J.ValueSubject(void 0);this.error$=new J.Subject;this.subscription=new J.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:J.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(_a(t.internalTextTracks,()=>(0,Zc.default)(this.internalTracks),s=>{(0,J.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,J.isNonNullable)(s)&&(0,J.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,J.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(_a(t.externalTextTracks,()=>(0,Zc.default)(this.externalTracks),s=>{(0,J.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,J.isNonNullable)(s)&&(0,J.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,J.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(_a(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(_a(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,J.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,J.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,J.merge)((0,J.fromEvent)(e,"addtrack"),(0,J.fromEvent)(e,"removetrack"),(0,J.observableFrom)(["init"])).pipe((0,J.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,J.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,J.merge)((0,J.fromEvent)(e,"change"),(0,J.observableFrom)(["init"])).pipe((0,J.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,J.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,J.filterChanged)()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,J.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var c,d,l,p,h;let u=(d=(c=o.target)==null?void 0:c.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(l=o.target)==null?void 0:l.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,J.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,J.isNonNullable)(t.align)&&(r.align=t.align),(0,J.isNonNullable)(t.position)&&(r.position=t.position),(0,J.isNonNullable)(t.size)&&(r.size=t.size),(0,J.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,J.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,c,d,l;let{language:t,label:i}=e,r=e.id?e.id:xR(e),s=this.externalTracks.has(r),n=(c=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?c:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(l=this.internalTracks.get(r))==null?void 0:l.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,J.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,J.isNullable)(e)||!PR(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){(0,J.assertNonNullable)(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){(0,J.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},gt=el;var Zi=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 tv=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},tl=a=>{let e=tv(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},iv=a=>{let e=tv(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var $=require("@vkontakte/videoplayer-shared/es2015");var kR=3,rv=(a,e,t=kR)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var rt=a=>{let e=_=>(0,$.fromEvent)(a,_).pipe((0,$.mapTo)(void 0),(0,$.shareReplay)(1)),t=new $.Subscription,i=()=>t.unsubscribe(),r=(0,$.merge)((0,$.fromEvent)(a,"progress"),(0,$.fromEvent)(a,"timeupdate")).pipe((0,$.map)(()=>rv(a.buffered,a.currentTime)),(0,$.shareReplay)(1)),s=G.browser.isSafari?(0,$.combine)({play:e("play").pipe((0,$.once)()),playing:e("playing")}).pipe((0,$.mapTo)(void 0),(0,$.shareReplay)(1)):e("playing"),n=(0,$.fromEvent)(a,"volumechange").pipe((0,$.map)(()=>({muted:a.muted,volume:a.volume})),(0,$.shareReplay)(1)),o=(0,$.fromEvent)(a,"ratechange").pipe((0,$.map)(()=>a.playbackRate),(0,$.shareReplay)(1)),u=(0,$.fromEvent)(a,"error").pipe((0,$.filter)(()=>!!(a.error||a.played.length)),(0,$.map)(()=>{var K;let _=a.error;return{id:_?`MediaError#${_.code}`:"HtmlVideoError",category:$.ErrorCategory.VIDEO_PIPELINE,message:_?_.message:"Error event from HTML video element",thrown:(K=a.error)!=null?K:void 0}}),(0,$.shareReplay)(1)),c=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(()=>a.currentTime),(0,$.shareReplay)(1)),d=["waiting","seeking","seeked","timeupdate"],l=new $.Subject,p=.3,h;t.add((0,$.merge)(...d.map(_=>(0,$.fromEvent)(a,_))).subscribe(_=>{let K=a.currentTime;a.loop&&(0,$.isNonNullable)(h)&&(0,$.isNonNullable)(K)&&h>=a.duration-p&&K<=p&&l.next(h),h=K}));let m=e("pause").pipe((0,$.filter)(()=>!a.error&&h!==a.duration),(0,$.shareReplay)(1)),b=(0,$.fromEvent)(a,"enterpictureinpicture").pipe((0,$.shareReplay)(1)),S=(0,$.fromEvent)(a,"leavepictureinpicture").pipe((0,$.shareReplay)(1)),v=new $.ValueSubject(iv(a));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let y=new $.ValueSubject(tl(a)),x=(0,$.fromEvent)(a,"fullscreenchange").pipe((0,$.shareReplay)(1));t.add(x.pipe((0,$.map)(()=>tl(a))).subscribe(y));let P=.1,D=1e3,V=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(_=>a.duration-a.currentTime<P),(0,$.filterChanged)(),(0,$.shareReplay)(1)),Q=(0,$.merge)(V.pipe((0,$.filter)(_=>!a.loop&&_)),(0,$.fromEvent)(a,"ended")).pipe((0,$.throttle)(D),(0,$.mapTo)(void 0),(0,$.shareReplay)(1)),F=(0,$.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(_=>(0,$.fromEvent)(a,_)),V.pipe((0,$.map)(_=>({type:_?"ended":"unknown"})))).pipe((0,$.map)(_=>G.browser.isFirefox&&_.type==="ended"?a.readyState<2:a.readyState<3),(0,$.filterChanged)(),(0,$.shareReplay)(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:Q,looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,$.fromEvent)(a,"durationchange").pipe((0,$.map)(()=>a.duration),(0,$.shareReplay)(1)),isBuffering$:F,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:y,enterPip$:b,leavePip$:S,destroy:i}};var ei=require("@vkontakte/videoplayer-shared/es2015"),Ii=a=>{switch(a){case"mobile":return ei.VideoQuality.Q_144P;case"lowest":return ei.VideoQuality.Q_240P;case"low":return ei.VideoQuality.Q_360P;case"sd":case"medium":return ei.VideoQuality.Q_480P;case"hd":case"high":return ei.VideoQuality.Q_720P;case"fullhd":case"full":return ei.VideoQuality.Q_1080P;case"quadhd":case"quad":return ei.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ei.VideoQuality.Q_2160P}};var Ye=Z(vt(),1),rl=Z(Ze(),1),er=Z(Si(),1),L=require("@vkontakte/videoplayer-shared/es2015");var il=!1,ti={},lv=a=>{il=a},dv=()=>{ti={}},pv=a=>{a(ti)},Oa=(a,e)=>{var t;il&&(ti.meta=(t=ti.meta)!=null?t:{},ti.meta[a]=e)},Ge=class{constructor(e){this.name=e}next(e){var i,r;if(!il)return;ti.series=(i=ti.series)!=null?i:{};let t=(r=ti.series[this.name])!=null?r:[];t.push([Date.now(),e]),ti.series[this.name]=t}};var Ce=require("@vkontakte/videoplayer-shared/es2015");function hv(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function _r(a,e,t){return(0,Ce.isNullable)(a)||(0,Ce.isNonNullable)(a.min)&&(0,Ce.isNonNullable)(a.max)&&(0,Ce.isLower)(a.max,a.min)||(0,Ce.isNonNullable)(a.min)&&e&&(0,Ce.isHigher)(a.min,e)||(0,Ce.isNonNullable)(a.max)&&t&&(0,Ce.isLower)(a.max,t)}function fv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return _r({max:a!=null&&a.max?(0,Ce.videoHeightToQuality)(a.max):void 0,min:a!=null&&a.min?(0,Ce.videoHeightToQuality)(a.min):void 0},e?(0,Ce.videoHeightToQuality)(e):void 0,t?(0,Ce.videoHeightToQuality)(t):void 0)}var Sv=new Ge("best_bitrate"),Jn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Or=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ei=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,L.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Zn='Assertion "ABR Tracks is empty array" failed',Xn=new WeakMap,mv=new WeakMap,bv=new WeakMap,Na=(a,e,t,i)=>{var u;let r=[...e].sort(Or(1)),s=[...t].sort(Or(1)),n=s.filter(c=>(0,L.isNonNullable)(c.bitrate)&&(0,L.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>i:!0),o=(u=(0,Ye.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Ye.default)(s,-1);return o&&(0,rl.default)(n,o)?o:n.length?(0,Ye.default)(n,-1):(0,Ye.default)(s,0)},Fa=(a,e,t,i)=>{var u;let r=Xn.get(e);r||(r=[...e].sort(Or(1)),Xn.set(e,r));let s=Xn.get(t);s||(s=[...t].sort(Or(1)),Xn.set(t,s));let n=bv.get(a);n||(n=s.filter(c=>(0,L.isNonNullable)(c.bitrate)&&(0,L.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>i:!0),bv.set(a,n));let o=(u=(0,Ye.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Ye.default)(s,-1);return o&&(0,rl.default)(n,o)?o:n.length?(0,Ye.default)(n,-1):(0,Ye.default)(s,0)},gv=a=>"quality"in a,eo=(a,e,t,i)=>{var n;let r=(0,L.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,L.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,L.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=gv(o)?"video":"audio",c=gv(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${c}
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t},
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},VR=(a,e)=>Math.log(e)/Math.log(a),yv=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&G.display.pixelRatio){let s=G.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,c=0]=a.pixelRatioLogCoefficients,d=VR(n,o*s+u)+c;Number.isFinite(d)&&(r*=d)}}return(0,L.isNonNullable)(t==null?void 0:t.min)&&(0,L.isHigherOrEqual)(t.min,a.highQualityLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},vv=new WeakMap,Ht=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{var ee,pe,ce,N,O;(0,L.assertNotEmptyArray)(a,Zn);let{containerSizeFactor:S,containerSizeLimit:v}=yv({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,L.isNonNullable)(o)?o:1,x=vv.get(a);x||(x=a.filter(k=>!(0,L.isInvariantQuality)(k.quality)).sort((k,R)=>(0,L.isHigher)(k.quality,R.quality)?-1:1),vv.set(a,x));let P=(ee=(0,Ye.default)(x,-1))==null?void 0:ee.quality,D=(pe=(0,Ye.default)(x,0))==null?void 0:pe.quality,V=_r(r,D,P),Q=y*Jn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),W={},F=null;for(let k of x){let R=!0;if(v)if(k.size)R=k.size.width<=v.width&&k.size.height<=v.height;else{let ot=v&&(0,L.videoSizeToQuality)(v);R=ot?(0,L.isLowerOrEqual)(k.quality,ot):!0}if(!R){W[k.quality]="FitsContainer";continue}let X=h||t,z=(0,L.isNonNullable)(X)&&isFinite(X)&&(0,L.isNonNullable)(k.bitrate)?X-s>=k.bitrate*Q:!0,Ct=(r==null?void 0:r.min)===k.quality;if(!z&&!Ct){W[k.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,L.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,L.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,L.isHigher)(k.quality,u.quality)){W[k.quality]="Buffer";continue}if(!!l&&(0,L.isHigherOrEqual)(k.quality,l)&&!Ct){W[k.quality]="DroppedFramesLimit";continue}if(!!p&&(0,L.isHigherOrEqual)(k.quality,p)&&!Ct){W[k.quality]="StallsLimit";continue}let Fe=V||((0,L.isNullable)(r==null?void 0:r.max)||(0,L.isLowerOrEqual)(k.quality,r.max))&&((0,L.isNullable)(r==null?void 0:r.min)||(0,L.isHigherOrEqual)(k.quality,r.min)),qe=(0,L.isNonNullable)(d)&&!d?(0,L.isLowerOrEqual)(k.quality,i.backgroundVideoQualityLimit):!0;if(!Fe||!qe){W[k.quality]="FitsQualityLimits";continue}F||(F=k)}F&&F.bitrate&&Sv.next(F.bitrate);let _=(ce=F!=null?F:(0,Ye.default)(x,-1))!=null?ce:a[0],K=c==null?void 0:c.last,q=eo(i,m,_,c);return(0,L.isNonNullable)(c)&&q.quality!==(K==null?void 0:K.quality)&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
12
|
${a.map(k=>{var R,X;return`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate}, size: ${(R=k.size)==null?void 0:R.width}:${(X=k.size)==null?void 0:X.height} }`}).join(`
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
|
|
40
40
|
[best video track] ${F==null?void 0:F.quality}
|
|
41
41
|
[selected video track] ${q==null?void 0:q.quality}
|
|
42
|
-
`}),q},
|
|
42
|
+
`}),q},to=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{var pe,ce,N,O,k;(0,L.assertNotEmptyArray)(a,Zn);let{containerSizeFactor:S,containerSizeLimit:v}=yv({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,L.isNonNullable)(o)?o:1,x=a.filter(R=>!(0,L.isInvariantQuality)(R.quality)).sort((R,X)=>(0,L.isHigher)(R.quality,X.quality)?-1:1),P=(pe=(0,Ye.default)(x,-1))==null?void 0:pe.quality,D=(ce=(0,Ye.default)(x,0))==null?void 0:ce.quality,V=_r(r,D,P),Q=y*Jn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),W={},_=x.filter(R=>{let X=!0;if(v)if(R.size)X=R.size.width<=v.width&&R.size.height<=v.height;else{let Gt=v&&(0,L.videoSizeToQuality)(v);X=Gt?(0,L.isLowerOrEqual)(R.quality,Gt):!0}if(!X)return W[R.quality]="FitsContainer",!1;let z=h||t,Ct=(0,L.isNonNullable)(z)&&isFinite(z)&&(0,L.isNonNullable)(R.bitrate)?z-s>=R.bitrate*Q:!0,Dt=(r==null?void 0:r.min)===R.quality;if(!Ct&&!Dt)return W[R.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,L.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,L.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,L.isHigher)(R.quality,u.quality))return W[R.quality]="Buffer",!1;if(!!l&&(0,L.isHigherOrEqual)(R.quality,l)&&!Dt)return W[R.quality]="DroppedFramesLimit",!1;if(!!p&&(0,L.isHigherOrEqual)(R.quality,p)&&!Dt)return W[R.quality]="StallsLimit",!1;let qe=V||((0,L.isNullable)(r==null?void 0:r.max)||(0,L.isLowerOrEqual)(R.quality,r.max))&&((0,L.isNullable)(r==null?void 0:r.min)||(0,L.isHigherOrEqual)(R.quality,r.min)),ot=(0,L.isNonNullable)(d)&&!d?(0,L.isLowerOrEqual)(R.quality,i.backgroundVideoQualityLimit):!0;return!qe||!ot?(W[R.quality]="FitsQualityLimits",!1):!0})[0];_&&_.bitrate&&Sv.next(_.bitrate);let K=(N=_!=null?_:(0,Ye.default)(x,-1))!=null?N:a[0],q=c==null?void 0:c.last,ee=eo(i,m,K,c);return(0,L.isNonNullable)(c)&&ee.quality!==(q==null?void 0:q.quality)&&m({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
45
|
${a.map(R=>{var X,z;return`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate}, size: ${(X=R.size)==null?void 0:X.width}:${(z=R.size)==null?void 0:z.height} }`}).join(`
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
|
|
73
73
|
[best video track] ${_==null?void 0:_.quality}
|
|
74
74
|
[selected video track] ${ee==null?void 0:ee.quality}
|
|
75
|
-
`}),ee},
|
|
75
|
+
`}),ee},io=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:c})=>{(0,L.assertNotEmptyArray)(t,Zn);let d=r.considerPlaybackRate&&(0,L.isNonNullable)(s)?s:1,l=[...t].sort(Or(-1)),p=a.bitrate;(0,L.assertNonNullable)(p);let h=d*Jn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=Na(a,e,t,r.minVideoAudioRatio),S=c||i;(0,L.isNonNullable)(S)&&isFinite(S)&&(m=l.find(x=>(0,L.isNonNullable)(x.bitrate)&&(0,L.isNonNullable)(b==null?void 0:b.bitrate)?S-p>=x.bitrate*h&&x.bitrate>=b.bitrate:!1)),m||(m=b);let v=o==null?void 0:o.last,y=m&&eo(r,u,m,o);return(0,L.isNonNullable)(o)&&(y==null?void 0:y.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
78
|
${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
|
|
@@ -93,7 +93,7 @@
|
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
95
|
[selected audio track] ${y==null?void 0:y.id}
|
|
96
|
-
`}),y},
|
|
96
|
+
`}),y},ro=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:c})=>{(0,L.assertNotEmptyArray)(t,Zn);let d=r.considerPlaybackRate&&(0,L.isNonNullable)(s)?s:1,l=mv.get(t);l||(l=[...t].sort(Or(-1)),mv.set(t,l));let p=a.bitrate;(0,L.assertNonNullable)(p);let h=d*Jn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=Fa(a,e,t,r.minVideoAudioRatio),S=c||i;(0,L.isNonNullable)(S)&&isFinite(S)&&(m=l.find(x=>(0,L.isNonNullable)(x.bitrate)&&(0,L.isNonNullable)(b==null?void 0:b.bitrate)?S-p>=x.bitrate*h&&x.bitrate>=b.bitrate:!1)),m||(m=b);let v=o==null?void 0:o.last,y=m&&eo(r,u,m,o);return(0,L.isNonNullable)(o)&&(y==null?void 0:y.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
99
|
${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
|
|
@@ -114,7 +114,7 @@
|
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
116
|
[selected audio track] ${y==null?void 0:y.id}
|
|
117
|
-
`}),y};var We=a=>new URL(a).hostname;var re=require("@vkontakte/videoplayer-shared/es2015");var Pv=Z(vt(),1);var yv=Z(Ze(),1);var Sv=a=>{if(a instanceof DOMException&&(0,yv.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},at=(a,e)=>I(null,null,function*(){let t=a.muted;try{yield a.play()}catch(i){if(!Sv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{yield a.play()}catch(r){return Sv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});var pt=require("@vkontakte/videoplayer-shared/es2015");var Tv=Z(Wi(),1),Qt=require("@vkontakte/videoplayer-shared/es2015");function _e(){return(0,Qt.now)()}function il(a){return _e()-a}function rl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Iv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Nr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,c=0,d,l,p=!1,h="arraybuffer",m=7e3,b=2e3,S=()=>{if(u)return;(0,Qt.assertNonNullable)(d);let q=il(d),ee;if(q<b){ee=b-q,setTimeout(S,ee);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,V()},v=q=>(s=q,K),y=q=>(l=q,K),x=()=>(h="json",K),P=()=>{if(!u){if(--c>=0){S(),i&&i();return}u=!0,l&&l(),t&&t()}},D=q=>(p=q,K),V=()=>{d=_e(),n=new r,n.open("get",a);let q=0,ee,pe=0,ce=()=>((0,Qt.assertNonNullable)(d),Math.max(d,Math.max(ee||0,pe||0)));if(s&&n.addEventListener("progress",N=>{let O=_e();s.updateChunk&&N.loaded>q&&(s.updateChunk(ce(),N.loaded-q),q=N.loaded,ee=O)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>P())),n.addEventListener("load",()=>{if(u)return;(0,Qt.assertNonNullable)(n);let N=n.status;if(N>=200&&N<300){let{response:O,responseType:k}=n,R=O==null?void 0:O.byteLength;if(typeof R=="number"&&s){let X=R-q;X&&s.updateChunk&&s.updateChunk(ce(),X)}k==="json"&&(!O||!(0,Tv.default)(O).length)?P():(l&&l(),e(O))}else P()}),n.addEventListener("error",()=>{P()}),p){let N=()=>{(0,Qt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(pe=_e(),n.removeEventListener("readystatechange",N))};n.addEventListener("readystatechange",N)}return n.responseType=h,n.send(),K},K={withBitrateReporting:v,withParallel:D,withJSONResponse:x,withRetryCount:q=>(c=q,K),withRetryInterval:(q,ee)=>((0,Qt.isNonNullable)(q)&&(b=q),(0,Qt.isNonNullable)(ee)&&(m=ee),K),withTimeout:q=>(o=q,K),withFinally:y,send:V,abort:()=>{n&&(n.abort(),n=void 0),u=!0,l&&l()}};return K}var qa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ev=Z(Wi(),1);var Ua=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=_e(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=_e()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Nr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=_e()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=_e();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Ev.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var kv=require("@vkontakte/videoplayer-shared/es2015");var al=require("@vkontakte/videoplayer-shared/es2015"),Te=(a,e)=>(0,al.isNonNullable)(a)&&(0,al.isNonNullable)(e)&&a.readyState==="open"&&BR(a,e);function BR(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var wv=Z(Si(),1),xv=require("@vkontakte/videoplayer-shared/es2015"),sl=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){var t;let e=(0,wv.default)(this.data).map(([i,r])=>`${i}:${r}`).join(",");return{key:this.tag,strings:[e,(t=this.stack)!=null?t:""],numbers:[this.time]}}},VR=(a,e="warn")=>{let t=(0,xv.getWindow)(),i=[];function r(s,n=!1){var c,d,l;let o=(l=(d=(c=t.performance)==null?void 0:c.timing)==null?void 0:d.navigationStart)!=null?l:0,u=new sl(a,Math.round((Date.now()-o)/1e3),s,n?new Error().stack:void 0);i.push(u),e&&t.console[e](u.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let s=i;return i=[],s},r},ie=VR("vp_dash_live_debug",!1);var ro=1e4,nl=3;var OR=6e4,NR=10,FR=1,qR=500,ja=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new kv.Subject,this.chunkRateEstimator=new qa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=rl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(ie({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",ie({m:"ldp.catchUp.2"}),this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?(ie({m:"ldp.play.1"}),this._playVideoElement()):(ie({m:"ldp.play.2"}),this._notifyBuffering(!0))):(ie({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,ie({m:"startPlay",url:e.jidxUrl}),this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=rl(e),ie({m:"ldp.reinit",url:e}),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;ie({m:"iv"}),e.addEventListener("error",()=>{var r,s,n,o;!!e.error&&!this.destroyed&&(ie({m:"iv.err",e:((r=e.error)==null?void 0:r.code)+":"+((s=e.error)==null?void 0:s.message)}),t(`Video element error: ${(n=e.error)==null?void 0:n.code}, details: ${(o=e.error)==null?void 0:o.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),ie({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(G.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:c}=this.autoQualityLimits||{};!pv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Pv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||c&&s.video.height<c)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,pt.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){var o;let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(ie({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),(o=this.mediaSource)==null||o.addEventListener("sourceclose",u=>{ie({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{ie({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Iv(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ua(nl,ro,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,c=null,d=!1,l=()=>{let P=s&&(!d||d===this.rep);return P||t("Not running!"),P},p=(P,D,V)=>{u&&u.abort(),u=Nr(this.urlResolver.resolve(P,!1),D,V,()=>this._retryCallback()).withTimeout(ro).withBitrateReporting(this.bitrateSwitcher).withRetryCount(nl).withFinally(()=>{u=null}).send()},h=(P,D,V)=>{(0,pt.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(P,!1),D,V,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=P=>{let D=i.playbackRate;i.playbackRate!==P&&(t(`Playback rate switch: ${D}=>${P}`),i.playbackRate=P)},b=P=>{this.lowLatency=P,t(`lowLatency changed to ${P}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let P=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let V=_e()-1e4,Q=0;for(let F=0;F<this.bufferStates.length;F++){let _=this.bufferStates[F];P=Math.min(P,_.buf),_.ts<V&&Q++}this.bufferStates.splice(0,Q),t(`update playback rate; minBuffer=${P} drop=${Q} jitter=${this.sourceJitter}`);let W=P-FR;this.sourceJitter>=0?W-=this.sourceJitter/2:this.sourceJitter-=1,W>3?m(1.15):W>1?m(1.1):W>.3?m(1.05):m(1)}},v=P=>{let D,V=()=>D&&D.start?D.start.length:0,Q=N=>D.start[N]/1e3,W=N=>D.dur[N]/1e3,F=N=>D.fragIndex+N,_=(N,O)=>({chunkIdx:F(N),startTS:Q(N),dur:W(N),discontinuity:O}),K=()=>{let N=0;if(D&&D.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,k=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,R=O;this.sourceJitter>1&&(R+=this.sourceJitter-1);let X=D.dur.length-1;for(;X>=0&&(R-=D.dur[X],!(R<=0));--X);N=Math.min(X,D.dur.length-1-k),N=Math.max(N,0)}return _(N,!0)},q=N=>{let O=V();if(!(O<=0)){if((0,pt.isNonNullable)(N)){for(let k=0;k<O;k++)if(Q(k)>N)return _(k)}return K()}},ee=N=>{let O=V(),k=N?N.chunkIdx+1:0,R=k-D.fragIndex;if(!(O<=0)){if(!N||R<0||R-O>NR)return t(`Resync: offset=${R} bChunks=${O} chunk=`+JSON.stringify(N)),K();if(!(R>=O))return _(k-D.fragIndex,!1)}},pe=(N,O,k)=>{c&&c.abort(),c=Nr(this.urlResolver.resolve(N,!0,this.lowLatency),O,k,()=>this._retryCallback()).withTimeout(ro).withRetryCount(nl).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(N,O)=>{pe(P,k=>{if(!l())return;D=k;let R=!!D.lowLatency;R!==this.lowLatency&&b(R);let X=0;for(let z=0;z<D.dur.length;++z)X+=D.dur[z];X>0&&((0,pt.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(X/D.dur.length)),r({name:"index",zeroTime:D.zeroTime,shiftDuration:D.shiftDuration}),this.sourceJitter=D.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,D.jitter/1e3)):1,N(q(O))},()=>this._handleNetworkError())},nextChunk:ee}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),(0,pt.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:P=>{let{videoElement:D,logger:V}=this.params,Q=v(e.jidxUrl),W,F,_,K,q=0,ee,pe,ce,N=()=>{ee&&(clearTimeout(ee),ee=void 0);let me=Math.max(qR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ne=q+me,Fe=_e(),qe=Math.min(1e4,Ne-Fe);q=Fe;let ot=()=>{c||l()&&Q.seek(()=>{l()&&(q=_e(),O(),N())})};qe>0?ee=window.setTimeout(()=>{this.paused?N():ot()},qe):ot()},O=()=>{let me;for(;me=Q.nextChunk(K);)K=me,Ct(me);let Ne=Q.nextChunk(_);if(Ne){if(_&&Ne.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?N():(y(),ie({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}z(Ne)}else N()},k=(me,Ne)=>{if(!l()||!this.sourceBuffer){ie({m:"ab.0",c:[!l(),!this.sourceBuffer]});return}let Fe,qe,ot,Gt=Yt=>{ie({m:"ldp.postpone",t:Yt}),window.setTimeout(()=>{l()&&k(me,Ne)},Yt)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),ie({m:"ldp.ab.1"}),Gt(100);else{let Yt=_e(),Li=D.currentTime;!this.paused&&D.buffered.length>1&&pe===Li&&Yt-ce>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),pe!==Li&&(pe=Li,ce=Yt);let dr=this._getBufferSizeSec();if(dr>30)ie({m:"ldp.ab.3"}),V(`Buffered ${dr} seconds; delaying appendBuffer`),Gt(2e3);else try{if(this.params.config.useInvalidBufferFix&&Te(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(me),this.videoPlayStarted?(ie({m:"ldp.ab.5"}),this.bufferStates.push({ts:Yt,buf:dr}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(ie({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),Ne&&Ne()}catch(pr){if(ie({m:"ldp.ab.err",e:pr.name}),pr.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),ot=this.sourceBuffer.buffered.length,ot!==0&&(Fe=this.sourceBuffer.buffered.start(0),qe=Li,qe-Fe>4&&this.sourceBuffer.remove(Fe,qe-3)),Gt(1e3);else throw pr}}},R=()=>{F&&W&&(V([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(_)]),k(F,function(){F=null,O()}))},X=me=>e.fragUrlTemplate.replace("%%id%%",me.chunkIdx),z=me=>{l()&&h(X(me),(Ne,Fe)=>{if(l()){if(Fe/=1e3,F=Ne,_=me,n=me.startTS,Fe){let qe=Math.min(10,me.dur/Fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*qe:qe}R()}},()=>this._handleNetworkError())},Ct=me=>{l()&&((0,pt.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(X(me),!1)))},Dt=me=>{l()&&(e.cachedHeader=me,k(me,()=>{W=!0,R()}))};s=!0,Q.seek(me=>{if(l()){if(q=_e(),!me){N();return}K=me,!(0,pt.isNullable)(P)||me.startTS>P?z(me):(_=me,O())}},P),e.cachedHeader?Dt(e.cachedHeader):p(e.headerUrl,Dt,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,pt.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,pt.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,pt.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},s={updateChunk:(p,h)=>{let m=_e();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let l=s.get();if(l&&o&&this.autoQuality){if(u&&l>o&&il(n)<3e4)return;i(l)}u=this.autoQuality};return{updateChunk:(l,p)=>{let h=s.updateChunk(l,p);return h&&c(),h},notifySwitch:l=>{let p=_e();l<o&&(n=p),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=Nr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ro).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;at(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{ie({m:"ldp.pve.1"}),t||(ie({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{var d,l;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((l=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&l.call(d,u.codecs))&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},OR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Av=Z(Si(),1),ke=require("@vkontakte/videoplayer-shared/es2015"),ol=class{constructor(){this.onDroopedVideoFramesLimit$=new ke.Subject;this.subscription=new ke.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ke.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,ke.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,ke.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ke.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ke.interval)(this.droppedFramesChecker.checkTime).pipe((0,ke.filter)(()=>this.playing),(0,ke.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,ke.debounce)(this.droppedFramesChecker.checkTime)),i=(0,ke.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,Av.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,ke.isLower)(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Fr=ol;var ao=require("@vkontakte/videoplayer-shared/es2015"),Rv=require("@vkontakte/videoplayer-shared/es2015");var Ha=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var UR=(a,e)=>new ao.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ha()))},M(M({},i),e));r.observe(a);let s=(0,Rv.fromEvent)(document,"visibilitychange").pipe((0,ao.map)(n=>!document.hidden||Ha())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),St=UR;var jR=["paused","playing","ready"],HR=["paused","playing","ready"],Qa=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new ne("stopped");this.representations$=new re.ValueSubject([]);this.droppedFramesManager=new Fr;this.maxSeekBackTime$=new re.ValueSubject(1/0);this.zeroTime$=new re.ValueSubject(void 0);this.liveOffset=new Zi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:re.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),d=(i=Ii(u.name))!=null?i:(0,re.videoSizeToQuality)(u.video),l=u.bitrate/1e3,p=M({},u.video);if(!d)continue;let h={id:c,quality:d,bitrate:l,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,re.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,ul.default)(HR,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,ul.default)(jR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(He(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){ie({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&(ie({m:"dlp.sync.2"}),this.dash.catchUp()),ie({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(He(this.params.source.url,u))}return;default:return(0,re.assertNever)(e)}};this.textTracksManager=new gt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:re.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,re.merge)(this.videoState.stateChangeStarted$.pipe((0,re.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,re.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{ie({m:"dlp.s.1",t:s+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=rt(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,re.map)(r=>r.map(({track:s})=>s)),(0,re.filter)(r=>!!r.length),(0,re.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,re.filterChanged)(),(0,re.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,re.combine)({zeroTime:this.zeroTime$.pipe((0,re.filter)(re.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(jt(this.video,this.params.desiredState.isLooped,t)).add(it(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(bt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(St(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&(0,re.videoQualityToHeight)(r),min:s&&(0,re.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),ie({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&(ie({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":ie({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":ie({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return(0,re.assertNever)(r.to)}},t)).add((0,re.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){ie({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),tt(this.video)}createLiveDashPlayer(){let e=new ja({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var c,d,l,p,h,m;let e=this.representations$.getValue(),t=(d=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(p=(l=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:l.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,re.isNonNullable)(t)?t:Ht(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let b=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,re.assertNonNullable)(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,re.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),ie({m:"dlp.seek",p:e,no:n,url:this.params.source.url}),this.dash.reinit(He(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Mv=Qa;var Uy=require("@vkontakte/videoplayer-shared/es2015");var ae=require("@vkontakte/videoplayer-shared/es2015");var cl=Z(vt(),1);var $v=require("@vkontakte/videoplayer-shared/es2015"),Cv=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Ii(s):void 0)!=null?u:(0,$v.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Dv=({id:a,bitrate:e})=>({id:a,bitrate:e}),Lv=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e});var ll=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,cl.default)(i.split("."),0),isDefault:r}),so=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,cl.default)(r.split("."),0)});var Ke=a=>a.type==="template";var no=class{constructor(e,t){this.fov=e,this.orientation=t}};var oo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Vt(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=M({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*Vt(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Bv=`attribute vec2 a_vertex;
|
|
117
|
+
`}),y};var We=a=>new URL(a).hostname;var re=require("@vkontakte/videoplayer-shared/es2015");var Av=Z(vt(),1);var Iv=Z(Ze(),1);var Tv=a=>{if(a instanceof DOMException&&(0,Iv.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},at=(a,e)=>I(null,null,function*(){let t=a.muted;try{yield a.play()}catch(i){if(!Tv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{yield a.play()}catch(r){return Tv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});var pt=require("@vkontakte/videoplayer-shared/es2015");var Ev=Z(Wi(),1),Qt=require("@vkontakte/videoplayer-shared/es2015");function _e(){return(0,Qt.now)()}function al(a){return _e()-a}function sl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function wv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Nr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,c=0,d,l,p=!1,h="arraybuffer",m=7e3,b=2e3,S=()=>{if(u)return;(0,Qt.assertNonNullable)(d);let q=al(d),ee;if(q<b){ee=b-q,setTimeout(S,ee);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,V()},v=q=>(s=q,K),y=q=>(l=q,K),x=()=>(h="json",K),P=()=>{if(!u){if(--c>=0){S(),i&&i();return}u=!0,l&&l(),t&&t()}},D=q=>(p=q,K),V=()=>{d=_e(),n=new r,n.open("get",a);let q=0,ee,pe=0,ce=()=>((0,Qt.assertNonNullable)(d),Math.max(d,Math.max(ee||0,pe||0)));if(s&&n.addEventListener("progress",N=>{let O=_e();s.updateChunk&&N.loaded>q&&(s.updateChunk(ce(),N.loaded-q),q=N.loaded,ee=O)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>P())),n.addEventListener("load",()=>{if(u)return;(0,Qt.assertNonNullable)(n);let N=n.status;if(N>=200&&N<300){let{response:O,responseType:k}=n,R=O==null?void 0:O.byteLength;if(typeof R=="number"&&s){let X=R-q;X&&s.updateChunk&&s.updateChunk(ce(),X)}k==="json"&&(!O||!(0,Ev.default)(O).length)?P():(l&&l(),e(O))}else P()}),n.addEventListener("error",()=>{P()}),p){let N=()=>{(0,Qt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(pe=_e(),n.removeEventListener("readystatechange",N))};n.addEventListener("readystatechange",N)}return n.responseType=h,n.send(),K},K={withBitrateReporting:v,withParallel:D,withJSONResponse:x,withRetryCount:q=>(c=q,K),withRetryInterval:(q,ee)=>((0,Qt.isNonNullable)(q)&&(b=q),(0,Qt.isNonNullable)(ee)&&(m=ee),K),withTimeout:q=>(o=q,K),withFinally:y,send:V,abort:()=>{n&&(n.abort(),n=void 0),u=!0,l&&l()}};return K}var qa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var xv=Z(Wi(),1);var Ua=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=_e(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=_e()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Nr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=_e()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=_e();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,xv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Rv=require("@vkontakte/videoplayer-shared/es2015");var nl=require("@vkontakte/videoplayer-shared/es2015"),Te=(a,e)=>(0,nl.isNonNullable)(a)&&(0,nl.isNonNullable)(e)&&a.readyState==="open"&&_R(a,e);function _R(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Pv=Z(Si(),1),kv=require("@vkontakte/videoplayer-shared/es2015"),ol=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){var t;let e=(0,Pv.default)(this.data).map(([i,r])=>`${i}:${r}`).join(",");return{key:this.tag,strings:[e,(t=this.stack)!=null?t:""],numbers:[this.time]}}},OR=(a,e="warn")=>{let t=(0,kv.getWindow)(),i=[];function r(s,n=!1){var c,d,l;let o=(l=(d=(c=t.performance)==null?void 0:c.timing)==null?void 0:d.navigationStart)!=null?l:0,u=new ol(a,Math.round((Date.now()-o)/1e3),s,n?new Error().stack:void 0);i.push(u),e&&t.console[e](u.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let s=i;return i=[],s},r},ie=OR("vp_dash_live_debug",!1);var ao=1e4,ul=3;var FR=6e4,qR=10,UR=1,jR=500,ja=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Rv.Subject,this.chunkRateEstimator=new qa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=sl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(ie({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",ie({m:"ldp.catchUp.2"}),this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?(ie({m:"ldp.play.1"}),this._playVideoElement()):(ie({m:"ldp.play.2"}),this._notifyBuffering(!0))):(ie({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,ie({m:"startPlay",url:e.jidxUrl}),this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=sl(e),ie({m:"ldp.reinit",url:e}),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;ie({m:"iv"}),e.addEventListener("error",()=>{var r,s,n,o;!!e.error&&!this.destroyed&&(ie({m:"iv.err",e:((r=e.error)==null?void 0:r.code)+":"+((s=e.error)==null?void 0:s.message)}),t(`Video element error: ${(n=e.error)==null?void 0:n.code}, details: ${(o=e.error)==null?void 0:o.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),ie({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(G.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:c}=this.autoQualityLimits||{};!fv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Av.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||c&&s.video.height<c)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,pt.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){var o;let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(ie({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),(o=this.mediaSource)==null||o.addEventListener("sourceclose",u=>{ie({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{ie({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{wv(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ua(ul,ao,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,c=null,d=!1,l=()=>{let P=s&&(!d||d===this.rep);return P||t("Not running!"),P},p=(P,D,V)=>{u&&u.abort(),u=Nr(this.urlResolver.resolve(P,!1),D,V,()=>this._retryCallback()).withTimeout(ao).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ul).withFinally(()=>{u=null}).send()},h=(P,D,V)=>{(0,pt.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(P,!1),D,V,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=P=>{let D=i.playbackRate;i.playbackRate!==P&&(t(`Playback rate switch: ${D}=>${P}`),i.playbackRate=P)},b=P=>{this.lowLatency=P,t(`lowLatency changed to ${P}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let P=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let V=_e()-1e4,Q=0;for(let F=0;F<this.bufferStates.length;F++){let _=this.bufferStates[F];P=Math.min(P,_.buf),_.ts<V&&Q++}this.bufferStates.splice(0,Q),t(`update playback rate; minBuffer=${P} drop=${Q} jitter=${this.sourceJitter}`);let W=P-UR;this.sourceJitter>=0?W-=this.sourceJitter/2:this.sourceJitter-=1,W>3?m(1.15):W>1?m(1.1):W>.3?m(1.05):m(1)}},v=P=>{let D,V=()=>D&&D.start?D.start.length:0,Q=N=>D.start[N]/1e3,W=N=>D.dur[N]/1e3,F=N=>D.fragIndex+N,_=(N,O)=>({chunkIdx:F(N),startTS:Q(N),dur:W(N),discontinuity:O}),K=()=>{let N=0;if(D&&D.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,k=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,R=O;this.sourceJitter>1&&(R+=this.sourceJitter-1);let X=D.dur.length-1;for(;X>=0&&(R-=D.dur[X],!(R<=0));--X);N=Math.min(X,D.dur.length-1-k),N=Math.max(N,0)}return _(N,!0)},q=N=>{let O=V();if(!(O<=0)){if((0,pt.isNonNullable)(N)){for(let k=0;k<O;k++)if(Q(k)>N)return _(k)}return K()}},ee=N=>{let O=V(),k=N?N.chunkIdx+1:0,R=k-D.fragIndex;if(!(O<=0)){if(!N||R<0||R-O>qR)return t(`Resync: offset=${R} bChunks=${O} chunk=`+JSON.stringify(N)),K();if(!(R>=O))return _(k-D.fragIndex,!1)}},pe=(N,O,k)=>{c&&c.abort(),c=Nr(this.urlResolver.resolve(N,!0,this.lowLatency),O,k,()=>this._retryCallback()).withTimeout(ao).withRetryCount(ul).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(N,O)=>{pe(P,k=>{if(!l())return;D=k;let R=!!D.lowLatency;R!==this.lowLatency&&b(R);let X=0;for(let z=0;z<D.dur.length;++z)X+=D.dur[z];X>0&&((0,pt.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(X/D.dur.length)),r({name:"index",zeroTime:D.zeroTime,shiftDuration:D.shiftDuration}),this.sourceJitter=D.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,D.jitter/1e3)):1,N(q(O))},()=>this._handleNetworkError())},nextChunk:ee}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),(0,pt.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:P=>{let{videoElement:D,logger:V}=this.params,Q=v(e.jidxUrl),W,F,_,K,q=0,ee,pe,ce,N=()=>{ee&&(clearTimeout(ee),ee=void 0);let me=Math.max(jR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ne=q+me,Fe=_e(),qe=Math.min(1e4,Ne-Fe);q=Fe;let ot=()=>{c||l()&&Q.seek(()=>{l()&&(q=_e(),O(),N())})};qe>0?ee=window.setTimeout(()=>{this.paused?N():ot()},qe):ot()},O=()=>{let me;for(;me=Q.nextChunk(K);)K=me,Ct(me);let Ne=Q.nextChunk(_);if(Ne){if(_&&Ne.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?N():(y(),ie({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}z(Ne)}else N()},k=(me,Ne)=>{if(!l()||!this.sourceBuffer){ie({m:"ab.0",c:[!l(),!this.sourceBuffer]});return}let Fe,qe,ot,Gt=Yt=>{ie({m:"ldp.postpone",t:Yt}),window.setTimeout(()=>{l()&&k(me,Ne)},Yt)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),ie({m:"ldp.ab.1"}),Gt(100);else{let Yt=_e(),Li=D.currentTime;!this.paused&&D.buffered.length>1&&pe===Li&&Yt-ce>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),pe!==Li&&(pe=Li,ce=Yt);let dr=this._getBufferSizeSec();if(dr>30)ie({m:"ldp.ab.3"}),V(`Buffered ${dr} seconds; delaying appendBuffer`),Gt(2e3);else try{if(this.params.config.useInvalidBufferFix&&Te(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(me),this.videoPlayStarted?(ie({m:"ldp.ab.5"}),this.bufferStates.push({ts:Yt,buf:dr}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(ie({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),Ne&&Ne()}catch(pr){if(ie({m:"ldp.ab.err",e:pr.name}),pr.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),ot=this.sourceBuffer.buffered.length,ot!==0&&(Fe=this.sourceBuffer.buffered.start(0),qe=Li,qe-Fe>4&&this.sourceBuffer.remove(Fe,qe-3)),Gt(1e3);else throw pr}}},R=()=>{F&&W&&(V([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(_)]),k(F,function(){F=null,O()}))},X=me=>e.fragUrlTemplate.replace("%%id%%",me.chunkIdx),z=me=>{l()&&h(X(me),(Ne,Fe)=>{if(l()){if(Fe/=1e3,F=Ne,_=me,n=me.startTS,Fe){let qe=Math.min(10,me.dur/Fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*qe:qe}R()}},()=>this._handleNetworkError())},Ct=me=>{l()&&((0,pt.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(X(me),!1)))},Dt=me=>{l()&&(e.cachedHeader=me,k(me,()=>{W=!0,R()}))};s=!0,Q.seek(me=>{if(l()){if(q=_e(),!me){N();return}K=me,!(0,pt.isNullable)(P)||me.startTS>P?z(me):(_=me,O())}},P),e.cachedHeader?Dt(e.cachedHeader):p(e.headerUrl,Dt,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,pt.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,pt.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,pt.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},s={updateChunk:(p,h)=>{let m=_e();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let l=s.get();if(l&&o&&this.autoQuality){if(u&&l>o&&al(n)<3e4)return;i(l)}u=this.autoQuality};return{updateChunk:(l,p)=>{let h=s.updateChunk(l,p);return h&&c(),h},notifySwitch:l=>{let p=_e();l<o&&(n=p),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=Nr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ao).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;at(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{ie({m:"ldp.pve.1"}),t||(ie({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{var d,l;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((l=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&l.call(d,u.codecs))&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},FR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Mv=Z(Si(),1),ke=require("@vkontakte/videoplayer-shared/es2015"),cl=class{constructor(){this.onDroopedVideoFramesLimit$=new ke.Subject;this.subscription=new ke.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ke.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,ke.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,ke.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ke.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ke.interval)(this.droppedFramesChecker.checkTime).pipe((0,ke.filter)(()=>this.playing),(0,ke.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,ke.debounce)(this.droppedFramesChecker.checkTime)),i=(0,ke.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,Mv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,ke.isLower)(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Fr=cl;var so=require("@vkontakte/videoplayer-shared/es2015"),$v=require("@vkontakte/videoplayer-shared/es2015");var Ha=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var HR=(a,e)=>new so.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ha()))},M(M({},i),e));r.observe(a);let s=(0,$v.fromEvent)(document,"visibilitychange").pipe((0,so.map)(n=>!document.hidden||Ha())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),St=HR;var QR=["paused","playing","ready"],WR=["paused","playing","ready"],Qa=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new ne("stopped");this.representations$=new re.ValueSubject([]);this.droppedFramesManager=new Fr;this.maxSeekBackTime$=new re.ValueSubject(1/0);this.zeroTime$=new re.ValueSubject(void 0);this.liveOffset=new Zi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:re.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),d=(i=Ii(u.name))!=null?i:(0,re.videoSizeToQuality)(u.video),l=u.bitrate/1e3,p=M({},u.video);if(!d)continue;let h={id:c,quality:d,bitrate:l,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,re.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,ll.default)(WR,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,ll.default)(QR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(He(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){ie({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&(ie({m:"dlp.sync.2"}),this.dash.catchUp()),ie({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(He(this.params.source.url,u))}return;default:return(0,re.assertNever)(e)}};this.textTracksManager=new gt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:re.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,re.merge)(this.videoState.stateChangeStarted$.pipe((0,re.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,re.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{ie({m:"dlp.s.1",t:s+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=rt(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,re.map)(r=>r.map(({track:s})=>s)),(0,re.filter)(r=>!!r.length),(0,re.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,re.filterChanged)(),(0,re.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,re.combine)({zeroTime:this.zeroTime$.pipe((0,re.filter)(re.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(jt(this.video,this.params.desiredState.isLooped,t)).add(it(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(bt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(St(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&(0,re.videoQualityToHeight)(r),min:s&&(0,re.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),ie({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&(ie({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":ie({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":ie({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return(0,re.assertNever)(r.to)}},t)).add((0,re.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){ie({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),tt(this.video)}createLiveDashPlayer(){let e=new ja({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var c,d,l,p,h,m;let e=this.representations$.getValue(),t=(d=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(p=(l=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:l.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,re.isNonNullable)(t)?t:Ht(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let b=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,re.assertNonNullable)(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,re.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),ie({m:"dlp.seek",p:e,no:n,url:this.params.source.url}),this.dash.reinit(He(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Cv=Qa;var Hy=require("@vkontakte/videoplayer-shared/es2015");var ae=require("@vkontakte/videoplayer-shared/es2015");var dl=Z(vt(),1);var Dv=require("@vkontakte/videoplayer-shared/es2015"),Lv=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Ii(s):void 0)!=null?u:(0,Dv.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Bv=({id:a,bitrate:e})=>({id:a,bitrate:e}),Vv=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e});var pl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,dl.default)(i.split("."),0),isDefault:r}),no=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,dl.default)(r.split("."),0)});var Ke=a=>a.type==="template";var oo=class{constructor(e,t){this.fov=e,this.orientation=t}};var uo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Vt(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=M({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*Vt(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var _v=`attribute vec2 a_vertex;
|
|
118
118
|
attribute vec2 a_texel;
|
|
119
119
|
|
|
120
120
|
varying vec2 v_texel;
|
|
@@ -125,7 +125,7 @@ void main(void) {
|
|
|
125
125
|
// save texel vector to pass to fragment shader
|
|
126
126
|
v_texel = a_texel;
|
|
127
127
|
}
|
|
128
|
-
`;var
|
|
128
|
+
`;var Ov=`#ifdef GL_ES
|
|
129
129
|
precision highp float;
|
|
130
130
|
precision highp int;
|
|
131
131
|
#else
|
|
@@ -168,17 +168,17 @@ void main(void) {
|
|
|
168
168
|
// sample using new coordinates
|
|
169
169
|
gl_FragColor = texture2D(u_texture, tc);
|
|
170
170
|
}
|
|
171
|
-
`;var qr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new no(this.params.fov,this.params.orientation),this.cameraRotationManager=new oo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Bv,this.gl.VERTEX_SHADER),i=this.createShader(Vv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,c=e+i,d=t+r,l=e-i,p=t+r;return[s,n,o,u,c,d,l,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}};var Ee=require("@vkontakte/videoplayer-shared/es2015");var ii=(a,e,t)=>t*e+(1-t)*a,dl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,_v=(a,e,t,i)=>{let r=0,s=t,n=dl(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var uo="stalls_manager_metrics",pl="stalls_manager_abr_params",Ov="stalls_manager_default_tuning_abr_params",hl=class{constructor(){this.isSeeked$=new Ee.ValueSubject(!1);this.isBuffering$=new Ee.ValueSubject(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Ee.Subscription;this.severeStallOccurred$=new Ee.ValueSubject(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(pl):{};return M(M({},this.abrParams),t)}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Ee.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,Ee.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}=M({},this.getStoredData(Ov)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}=M({},this.abrParams);this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(pl),this.setStoredData(Ov,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(uo,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(uo,[]),this.setStoredData(pl,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){var i;return JSON.parse((i=Ee.safeStorage.get(e))!=null?i:t)}setStoredData(e,t){Ee.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){Ee.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(uo,"[]"),r=t/e,s=i.length?ii(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(uo,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){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(e.playing$.pipe((0,Ee.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,Ee.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,Ee.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if((0,Ee.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,Ee.now)(),l=r&&this.currentStallsCount>=r,p=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-c>=i+o&&t>=i;(l||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Ee.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,Ee.now)()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},co=hl;var st=require("@vkontakte/videoplayer-shared/es2015"),lo=class{constructor(){this.subscription=new st.Subscription;this.pipSize$=new st.ValueSubject(void 0);this.videoSize$=new st.ValueSubject(void 0);this.elementSize$=new st.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=st.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,st.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,st.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,st.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var wi=require("@vkontakte/videoplayer-shared/es2015");var xi=({subscription:a,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!G.browser.isSafari)return;let r=0,s=!1;a.add(e.volume.stateChangeStarted$.pipe((0,wi.map)(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),(0,wi.filter)(n=>!!n),(0,wi.once)()).subscribe(()=>{r=performance.now(),s=!0})),a.add(i.playbackRateState$.pipe((0,wi.filter)(()=>s),(0,wi.once)()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var za=class{constructor(e){this.subscription=new ae.Subscription;this.videoState=new ne("stopped");this.observableVideo=null;this.droppedFramesManager=new Fr;this.stallsManager=new co;this.elementSizeManager=new lo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ei;this.audioTrackSwitchHistory=new Ei;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,ae.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new qr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new gt(e.source.url),this.params=e,this.video=et(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(We(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=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,ae.isNullable)(this.observableVideo)&&(this.observableVideo=rt(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:ae.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,ae.filter)(l=>!!l.length),(0,ae.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,ae.map)(l=>l.to.state!=="none"),(0,ae.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.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.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.currentBuffer$,e.currentBuffer$),s(this.player.lastRequestFirstBytes$.pipe((0,ae.filter)(ae.isNonNullable),(0,ae.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,ae.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(jt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),xi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(it(this.video,t.volume,i.volumeState$,r)),this.subscription.add(bt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(St(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),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 p=this.player.getStreams(),h=this.player.getCodecs();if((0,ae.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of p.audio){b.push(ll(S));let v=[];for(let y of S.representations){let x=Dv(y);v.push(x),this.audioTracksMap.set(x,{stream:S,representation:y})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of p.video){m.push(so(b));let S=[];for(let v of b.representations){let y=Cv(U(M({},v),{streamId:b.id}));y&&(S.push(y),this.videoTracksMap.set(y,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of p.text)for(let S of b.representations){let v=Lv(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}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),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,ae.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,ae.fromEvent)(this.video,"progress")).pipe((0,ae.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,ae.throttle)(u))),this.subscription.add(o.subscribe(()=>I(this,null,function*(){let l=this.player.state$.getState(),p=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let m=this.selectVideoAudioRepresentations();if(!m)return;let[b,S]=m,v=[...this.videoTracksMap.keys()].find(x=>{var P;return((P=this.videoTracksMap.get(x))==null?void 0:P.representation.id)===b.id});(0,ae.isNonNullable)(v)&&(this.stallsManager.lastVideoTrackSelected=v);let y=this.params.desiredState.autoVideoTrackLimits.getTransition();y&&this.params.output.autoVideoTrackLimits$.next(y.to),l==="manifest_ready"?yield this.player.initRepresentations(b.id,S==null?void 0:S.id,this.params.sourceHls):(yield this.player.switchRepresentation("video",b.id,h),S&&(yield this.player.switchRepresentation("audio",S.id,h)))}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,ae.filterChanged)()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(ll(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var p,h;if(l!=null&&l.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe((0,ae.map)(({to:l})=>l==="ready"),(0,ae.filterChanged)());this.subscription.add((0,ae.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,ae.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,ae.merge)(c,this.player.state$.stateChangeEnded$,(0,ae.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,ae.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ae.observableFrom)(["init"])).pipe((0,ae.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var W,F,_,K,q,ee,pe,ce,N,O,k,R,X;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Fa:Na,t=this.params.tuning.useNewAutoSelectVideoTrack?io:to,i=this.params.tuning.useNewAutoSelectVideoTrack?Ht:eo,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(W=r.videoTrack.getState())==null?void 0:W.id,u=[...this.videoTracksMap.keys()].find(({id:z})=>z===o),c=s.currentVideoTrack$.getValue(),d=((K=(_=r.videoStream.getState())!=null?_:u&&((F=this.videoTracksMap.get(u))==null?void 0:F.stream))!=null?K:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:z})=>z===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=this.player.bufferLength$.getValue(),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=(q=r.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(ee=[...this.audioStreamsMap.keys()].find(({id:z})=>z===(v==null?void 0:v.id)))!=null?ee:this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let z=e(u,p,(pe=this.audioStreamsMap.get(y))!=null?pe:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(ce=z==null?void 0:z.bitrate)!=null?ce:-1/0)}if(c){let z=e(c,p,(N=this.audioStreamsMap.get(y))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(O=z==null?void 0:z.bitrate)!=null?O:-1/0)}}let P=u;(n||!P)&&(P=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:x,forwardBufferHealth:S,current:c,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}));let D=y&&t(P,p,(k=this.audioStreamsMap.get(y))!=null?k:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=(R=this.videoTracksMap.get(P))==null?void 0:R.representation,Q=D&&((X=this.audioTracksMap.get(D))==null?void 0:X.representation);if(V&&Q)return[V,Q];if(V&&!Q&&this.audioTracksMap.size===0)return[V,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ae.ErrorCategory.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),tt(this.video),this.tracer.end()}};var _l=Z(Ga(),1);var{NativeAbortSignal:TF,NativeAbortController:IF}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function aS(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function sS(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var po=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},jr=class extends po{constructor(){super(),this.listeners||po.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new tr;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new tr;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},tr=class{constructor(){Object.defineProperty(this,"signal",{value:new jr,writable:!0,configurable:!0})}abort(e){let t=sS(e),i=aS(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(tr.prototype[Symbol.toStringTag]="AbortController",jr.prototype[Symbol.toStringTag]="AbortSignal");function ho(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function ml(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!ho({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(c,d){let l;d&&d.signal&&(l=d.signal,delete d.signal);let p=new t(c,d);return l&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(d){let l;try{l=new DOMException("Aborted","AbortError")}catch(h){l=new Error("Aborted"),l.name="AbortError"}if(d.aborted)return Promise.reject(l);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(l),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(u,c)])}return n(u,c)},Request:s}}var De=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window;var bM=()=>"fetch"in De,Ya=bM()&&ho({fetch:De.fetch,Request:De.Request,AbortController:De.AbortController}),nS=Ya?ml({fetch:De.fetch,Request:De.Request,AbortController:De.AbortController}):void 0,yt=Ya?nS.fetch:De.fetch,LF=Ya?nS.Request:De.Request,Ie=Ya?tr:De.AbortController,BF=Ya?jr:De.AbortSignal;var qy=Z(Ze(),1);var kS=Z(PS(),1),Hr=require("@vkontakte/videoplayer-shared/es2015"),fo=a=>{if(!a)return{id:"EmptyResponse",category:Hr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Hr.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,kS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Hr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Hr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Hr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var E=require("@vkontakte/videoplayer-shared/es2015");var Pi=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var mo=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};var j=require("@vkontakte/videoplayer-shared/es2015");var Rt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var bo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var vo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new j.Subject;this.manifestReceived=new j.Subject;this.firstBytesRequested=new j.Subject;this.firstBytesReceived=new j.Subject;this.lastConnectionType$=new j.ValueSubject(void 0);this.lastConnectionReused$=new j.ValueSubject(void 0);this.lastRequestFirstBytes$=new j.ValueSubject(void 0);this.lastConnectionMetrics$=new j.ValueSubject(void 0);this.lastDownloadMetrics$=new j.ValueSubject(void 0);this.recoverableError$=new j.Subject;this.error$=new j.Subject;this.abortAllController=new Ie;this.subscription=new j.Subscription;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,j.abortable)(this.abortAllController.signal,function(e){return he(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Pi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=bo(i)),this.trackRequestStart(i,performance.now());let r=(0,j.now)();this.manifestRequested.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(go);if(s){let n=(0,j.now)();t.log("success",(0,j.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(s.headers);let o=s.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=yield new _t(s.text());if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",(0,j.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null})}.bind(this));this.fetch=(0,j.abortable)(this.abortAllController.signal,function(d){return he(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1}={}){var pe,ce,N;let l=e,p=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let O=new URL(l,(0,j.getWindow)().location.href);O.searchParams.append("bytes",`${i.from}-${i.to}`),l=O.toString();break}default:(0,j.assertNever)(t)}this.requestQuic&&(l=Pi(l));let m=this.abortAllController.signal,b;if(n){let O=new Ie;if(b=(0,j.merge)((0,j.fromEvent)(this.abortAllController.signal,"abort"),(0,j.fromEvent)(n,"abort")).subscribe(()=>{try{O.abort()}catch(k){go(k)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{O.abort()}catch(k){go(k)}m=O.signal}let S=0,v=(0,j.now)();h.log("startRequest",(0,j.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested.next();let y=yield this.doFetch(l,{priority:s,headers:p,signal:m}),x=(0,j.now)();if(!y)return h.error("error",{message:"No response in request"}),h.end(),b==null||b.unsubscribe(),null;if((pe=this.throughputEstimator)==null||pe.addRawRtt(x-v),!y.ok||!y.body){b==null||b.unsubscribe();let O=`Fetch error ${y.status}: ${y.statusText}`;return h.error("error",{message:O}),h.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){b==null||b.unsubscribe();let O=(0,j.now)(),k={requestStartedAt:v,requestEndedAt:O,duration:O-v};return h.log("endRequest",(0,j.flattenObject)(k)),h.end(),y.arrayBuffer()}let P=y.body;if(o){let O;[P,O]=y.body.tee(),(ce=this.throughputEstimator)==null||ce.trackStream(O,u)}let D=P.getReader(),V,Q=parseInt((N=y.headers.get("content-length"))!=null?N:"",10);Number.isFinite(Q)&&(V=Q),!V&&i&&(V=i.to-i.from+1);let W=V?new Uint8Array(V):new Uint8Array(0),F=!1,_=O=>{b==null||b.unsubscribe(),F=!0,go(O)},K=(0,j.abortable)(m,function(R){return he(this,arguments,function*({done:O,value:k}){if(S===0&&(this.lastRequestFirstBytes$.next((0,j.now)()-v),this.firstBytesReceived.next()),m.aborted){b==null||b.unsubscribe();return}if(!O&&k){if(c&&V)W.set(k,S),S+=k.byteLength;else{let X=new Uint8Array(W.length+k.length);X.set(W),X.set(k,W.length),W=X,S+=k.byteLength}r==null||r(new DataView(W.buffer),S),yield D==null?void 0:D.read().then(K,_)}})}.bind(this));yield D==null?void 0:D.read().then(K,_),b==null||b.unsubscribe();let q=(0,j.now)(),ee={failed:F,requestStartedAt:v,requestEndedAt:q,duration:q-v};if(F)return h.error("endRequest",(0,j.flattenObject)(ee)),h.end(),null;if(S>0){let O=q-v,R=S/(O/1e3)*8/1024,X={bytes:S,speed:R,url:e};this.lastDownloadMetrics$.next(X)}return h.log("endRequest",(0,j.flattenObject)(ee)),h.end(),W.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,j.abortable)(this.abortAllController.signal,function(e,t,i){return he(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!l)return null;let p=new DataView(l,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(l,m.from-n,m.to-m.from+1);else{let y=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,h,m).map(y=>({networkStatus:"none",bufferStatus:"none",status:"none",time:y.time,byte:y.byte}));return{initMetadata:h,initDataView:new DataView(l),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,j.abortable)(this.abortAllController.signal,function(e,t){return he(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});if(!r)return null;let s=e.segments.map(n=>U(M({},n),{networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:s}})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s,(0,j.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=mo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,j.getWindow)()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in(0,j.getWindow)().navigator))return"unknown";let e=(0,j.getWindow)().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(s===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch(t){this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:j.ErrorCategory.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}fetchRepresentation(e,t,i="auto"){return I(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,j.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}doFetch(e,t){return I(this,null,function*(){let i=yield yt(e,t);if(i.ok)return i;let r=yield i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:j.ErrorCategory.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:j.ErrorCategory.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:j.ErrorCategory.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:j.ErrorCategory.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:j.ErrorCategory.FATAL,httpCode:i.status,UVBackendErrorCode:r})}})}},go=a=>{if(!Rt(a))throw a};var kl=Z(KS(),1),gy=Z(Si(),1),vy=Z(py(),1),Sy=Z(vt(),1),Al=Z(Wi(),1);var hy=Z(Ze(),1),Pl=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,hy.default)(["6E","7A","F4"],o)}}return!1};var Xa=require("@vkontakte/videoplayer-shared/es2015");var fy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var my=a=>{var e;try{let t=$$(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(c=>{s[c[0]]=c.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let c=o[u];(typeof c=="undefined"||c==="")&&delete o[u]}),o}return null}catch(t){return null}};function $$(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
171
|
+
`;var qr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new oo(this.params.fov,this.params.orientation),this.cameraRotationManager=new uo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(_v,this.gl.VERTEX_SHADER),i=this.createShader(Ov,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,c=e+i,d=t+r,l=e-i,p=t+r;return[s,n,o,u,c,d,l,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}};var Ee=require("@vkontakte/videoplayer-shared/es2015");var ii=(a,e,t)=>t*e+(1-t)*a,hl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Nv=(a,e,t,i)=>{let r=0,s=t,n=hl(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var co="stalls_manager_metrics",fl="stalls_manager_abr_params",Fv="stalls_manager_default_tuning_abr_params",ml=class{constructor(){this.isSeeked$=new Ee.ValueSubject(!1);this.isBuffering$=new Ee.ValueSubject(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Ee.Subscription;this.severeStallOccurred$=new Ee.ValueSubject(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(fl):{};return M(M({},this.abrParams),t)}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Ee.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,Ee.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}=M({},this.getStoredData(Fv)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}=M({},this.abrParams);this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(fl),this.setStoredData(Fv,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(co,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(co,[]),this.setStoredData(fl,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){var i;return JSON.parse((i=Ee.safeStorage.get(e))!=null?i:t)}setStoredData(e,t){Ee.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){Ee.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(co,"[]"),r=t/e,s=i.length?ii(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(co,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){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(e.playing$.pipe((0,Ee.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,Ee.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,Ee.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if((0,Ee.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,Ee.now)(),l=r&&this.currentStallsCount>=r,p=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-c>=i+o&&t>=i;(l||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Ee.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,Ee.now)()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},lo=ml;var st=require("@vkontakte/videoplayer-shared/es2015"),po=class{constructor(){this.subscription=new st.Subscription;this.pipSize$=new st.ValueSubject(void 0);this.videoSize$=new st.ValueSubject(void 0);this.elementSize$=new st.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=st.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,st.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,st.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,st.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var wi=require("@vkontakte/videoplayer-shared/es2015");var xi=({subscription:a,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!G.browser.isSafari)return;let r=0,s=!1;a.add(e.volume.stateChangeStarted$.pipe((0,wi.map)(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),(0,wi.filter)(n=>!!n),(0,wi.once)()).subscribe(()=>{r=performance.now(),s=!0})),a.add(i.playbackRateState$.pipe((0,wi.filter)(()=>s),(0,wi.once)()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var za=class{constructor(e){this.subscription=new ae.Subscription;this.videoState=new ne("stopped");this.observableVideo=null;this.droppedFramesManager=new Fr;this.stallsManager=new lo;this.elementSizeManager=new po;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ei;this.audioTrackSwitchHistory=new Ei;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,ae.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new qr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new gt(e.source.url),this.params=e,this.video=et(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(We(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=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,ae.isNullable)(this.observableVideo)&&(this.observableVideo=rt(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:ae.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,ae.filter)(l=>!!l.length),(0,ae.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,ae.map)(l=>l.to.state!=="none"),(0,ae.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.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.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.currentBuffer$,e.currentBuffer$),s(this.player.lastRequestFirstBytes$.pipe((0,ae.filter)(ae.isNonNullable),(0,ae.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,ae.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(jt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),xi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(it(this.video,t.volume,i.volumeState$,r)),this.subscription.add(bt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(St(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),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 p=this.player.getStreams(),h=this.player.getCodecs();if((0,ae.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of p.audio){b.push(pl(S));let v=[];for(let y of S.representations){let x=Bv(y);v.push(x),this.audioTracksMap.set(x,{stream:S,representation:y})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of p.video){m.push(no(b));let S=[];for(let v of b.representations){let y=Lv(U(M({},v),{streamId:b.id}));y&&(S.push(y),this.videoTracksMap.set(y,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of p.text)for(let S of b.representations){let v=Vv(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}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),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,ae.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,ae.fromEvent)(this.video,"progress")).pipe((0,ae.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,ae.throttle)(u))),this.subscription.add(o.subscribe(()=>I(this,null,function*(){let l=this.player.state$.getState(),p=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let m=this.selectVideoAudioRepresentations();if(!m)return;let[b,S]=m,v=[...this.videoTracksMap.keys()].find(x=>{var P;return((P=this.videoTracksMap.get(x))==null?void 0:P.representation.id)===b.id});(0,ae.isNonNullable)(v)&&(this.stallsManager.lastVideoTrackSelected=v);let y=this.params.desiredState.autoVideoTrackLimits.getTransition();y&&this.params.output.autoVideoTrackLimits$.next(y.to),l==="manifest_ready"?yield this.player.initRepresentations(b.id,S==null?void 0:S.id,this.params.sourceHls):(yield this.player.switchRepresentation("video",b.id,h),S&&(yield this.player.switchRepresentation("audio",S.id,h)))}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,ae.filterChanged)()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(pl(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var p,h;if(l!=null&&l.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe((0,ae.map)(({to:l})=>l==="ready"),(0,ae.filterChanged)());this.subscription.add((0,ae.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,ae.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,ae.merge)(c,this.player.state$.stateChangeEnded$,(0,ae.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,ae.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ae.observableFrom)(["init"])).pipe((0,ae.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var W,F,_,K,q,ee,pe,ce,N,O,k,R,X;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Fa:Na,t=this.params.tuning.useNewAutoSelectVideoTrack?ro:io,i=this.params.tuning.useNewAutoSelectVideoTrack?Ht:to,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(W=r.videoTrack.getState())==null?void 0:W.id,u=[...this.videoTracksMap.keys()].find(({id:z})=>z===o),c=s.currentVideoTrack$.getValue(),d=((K=(_=r.videoStream.getState())!=null?_:u&&((F=this.videoTracksMap.get(u))==null?void 0:F.stream))!=null?K:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:z})=>z===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=this.player.bufferLength$.getValue(),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=(q=r.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(ee=[...this.audioStreamsMap.keys()].find(({id:z})=>z===(v==null?void 0:v.id)))!=null?ee:this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let z=e(u,p,(pe=this.audioStreamsMap.get(y))!=null?pe:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(ce=z==null?void 0:z.bitrate)!=null?ce:-1/0)}if(c){let z=e(c,p,(N=this.audioStreamsMap.get(y))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(O=z==null?void 0:z.bitrate)!=null?O:-1/0)}}let P=u;(n||!P)&&(P=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:x,forwardBufferHealth:S,current:c,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}));let D=y&&t(P,p,(k=this.audioStreamsMap.get(y))!=null?k:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=(R=this.videoTracksMap.get(P))==null?void 0:R.representation,Q=D&&((X=this.audioTracksMap.get(D))==null?void 0:X.representation);if(V&&Q)return[V,Q];if(V&&!Q&&this.audioTracksMap.size===0)return[V,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ae.ErrorCategory.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),tt(this.video),this.tracer.end()}};var Nl=Z(Ga(),1);var{NativeAbortSignal:IF,NativeAbortController:EF}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function nS(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function oS(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var ho=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},jr=class extends ho{constructor(){super(),this.listeners||ho.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new tr;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new tr;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},tr=class{constructor(){Object.defineProperty(this,"signal",{value:new jr,writable:!0,configurable:!0})}abort(e){let t=oS(e),i=nS(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(tr.prototype[Symbol.toStringTag]="AbortController",jr.prototype[Symbol.toStringTag]="AbortSignal");function fo(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function gl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!fo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(c,d){let l;d&&d.signal&&(l=d.signal,delete d.signal);let p=new t(c,d);return l&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(d){let l;try{l=new DOMException("Aborted","AbortError")}catch(h){l=new Error("Aborted"),l.name="AbortError"}if(d.aborted)return Promise.reject(l);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(l),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(u,c)])}return n(u,c)},Request:s}}var De=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window;var vM=()=>"fetch"in De,Ya=vM()&&fo({fetch:De.fetch,Request:De.Request,AbortController:De.AbortController}),uS=Ya?gl({fetch:De.fetch,Request:De.Request,AbortController:De.AbortController}):void 0,yt=Ya?uS.fetch:De.fetch,BF=Ya?uS.Request:De.Request,Ie=Ya?tr:De.AbortController,VF=Ya?jr:De.AbortSignal;var jy=Z(Ze(),1);var RS=Z(AS(),1),Hr=require("@vkontakte/videoplayer-shared/es2015"),mo=a=>{if(!a)return{id:"EmptyResponse",category:Hr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Hr.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,RS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Hr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Hr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Hr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var E=require("@vkontakte/videoplayer-shared/es2015");var Pi=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var bo=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};var j=require("@vkontakte/videoplayer-shared/es2015");var Rt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var go=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var So=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new j.Subject;this.manifestReceived=new j.Subject;this.firstBytesRequested=new j.Subject;this.firstBytesReceived=new j.Subject;this.lastConnectionType$=new j.ValueSubject(void 0);this.lastConnectionReused$=new j.ValueSubject(void 0);this.lastRequestFirstBytes$=new j.ValueSubject(void 0);this.lastConnectionMetrics$=new j.ValueSubject(void 0);this.lastDownloadMetrics$=new j.ValueSubject(void 0);this.recoverableError$=new j.Subject;this.error$=new j.Subject;this.abortAllController=new Ie;this.subscription=new j.Subscription;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,j.abortable)(this.abortAllController.signal,function(e){return he(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Pi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=go(i)),this.trackRequestStart(i,performance.now());let r=(0,j.now)();this.manifestRequested.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(vo);if(s){let n=(0,j.now)();t.log("success",(0,j.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(s.headers);let o=s.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=yield new _t(s.text());if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",(0,j.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null})}.bind(this));this.fetch=(0,j.abortable)(this.abortAllController.signal,function(d){return he(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1}={}){var pe,ce,N;let l=e,p=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let O=new URL(l,(0,j.getWindow)().location.href);O.searchParams.append("bytes",`${i.from}-${i.to}`),l=O.toString();break}default:(0,j.assertNever)(t)}this.requestQuic&&(l=Pi(l));let m=this.abortAllController.signal,b;if(n){let O=new Ie;if(b=(0,j.merge)((0,j.fromEvent)(this.abortAllController.signal,"abort"),(0,j.fromEvent)(n,"abort")).subscribe(()=>{try{O.abort()}catch(k){vo(k)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{O.abort()}catch(k){vo(k)}m=O.signal}let S=0,v=(0,j.now)();h.log("startRequest",(0,j.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested.next();let y=yield this.doFetch(l,{priority:s,headers:p,signal:m}),x=(0,j.now)();if(!y)return h.error("error",{message:"No response in request"}),h.end(),b==null||b.unsubscribe(),null;if((pe=this.throughputEstimator)==null||pe.addRawRtt(x-v),!y.ok||!y.body){b==null||b.unsubscribe();let O=`Fetch error ${y.status}: ${y.statusText}`;return h.error("error",{message:O}),h.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){b==null||b.unsubscribe();let O=(0,j.now)(),k={requestStartedAt:v,requestEndedAt:O,duration:O-v};return h.log("endRequest",(0,j.flattenObject)(k)),h.end(),y.arrayBuffer()}let P=y.body;if(o){let O;[P,O]=y.body.tee(),(ce=this.throughputEstimator)==null||ce.trackStream(O,u)}let D=P.getReader(),V,Q=parseInt((N=y.headers.get("content-length"))!=null?N:"",10);Number.isFinite(Q)&&(V=Q),!V&&i&&(V=i.to-i.from+1);let W=V?new Uint8Array(V):new Uint8Array(0),F=!1,_=O=>{b==null||b.unsubscribe(),F=!0,vo(O)},K=(0,j.abortable)(m,function(R){return he(this,arguments,function*({done:O,value:k}){if(S===0&&(this.lastRequestFirstBytes$.next((0,j.now)()-v),this.firstBytesReceived.next()),m.aborted){b==null||b.unsubscribe();return}if(!O&&k){if(c&&V)W.set(k,S),S+=k.byteLength;else{let X=new Uint8Array(W.length+k.length);X.set(W),X.set(k,W.length),W=X,S+=k.byteLength}r==null||r(new DataView(W.buffer),S),yield D==null?void 0:D.read().then(K,_)}})}.bind(this));yield D==null?void 0:D.read().then(K,_),b==null||b.unsubscribe();let q=(0,j.now)(),ee={failed:F,requestStartedAt:v,requestEndedAt:q,duration:q-v};if(F)return h.error("endRequest",(0,j.flattenObject)(ee)),h.end(),null;if(S>0){let O=q-v,R=S/(O/1e3)*8/1024,X={bytes:S,speed:R,url:e};this.lastDownloadMetrics$.next(X)}return h.log("endRequest",(0,j.flattenObject)(ee)),h.end(),W.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,j.abortable)(this.abortAllController.signal,function(e,t,i){return he(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!l)return null;let p=new DataView(l,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(l,m.from-n,m.to-m.from+1);else{let y=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,h,m).map(y=>({networkStatus:"none",bufferStatus:"none",status:"none",time:y.time,byte:y.byte}));return{initMetadata:h,initDataView:new DataView(l),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,j.abortable)(this.abortAllController.signal,function(e,t){return he(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});if(!r)return null;let s=e.segments.map(n=>U(M({},n),{networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:s}})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s,(0,j.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=bo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,j.getWindow)()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in(0,j.getWindow)().navigator))return"unknown";let e=(0,j.getWindow)().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(s===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch(t){this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:j.ErrorCategory.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}fetchRepresentation(e,t,i="auto"){return I(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,j.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}doFetch(e,t){return I(this,null,function*(){let i=yield yt(e,t);if(i.ok)return i;let r=yield i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:j.ErrorCategory.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:j.ErrorCategory.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:j.ErrorCategory.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:j.ErrorCategory.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:j.ErrorCategory.FATAL,httpCode:i.status,UVBackendErrorCode:r})}})}},vo=a=>{if(!Rt(a))throw a};var Rl=Z(JS(),1),Sy=Z(Si(),1),yy=Z(fy(),1),Ty=Z(vt(),1),Ml=Z(Wi(),1);var my=Z(Ze(),1),Al=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,my.default)(["6E","7A","F4"],o)}}return!1};var Xa=require("@vkontakte/videoplayer-shared/es2015");var by=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var gy=a=>{var e;try{let t=D$(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(c=>{s[c[0]]=c.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let c=o[u];(typeof c=="undefined"||c==="")&&delete o[u]}),o}return null}catch(t){return null}};function D$(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
172
172
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
173
173
|
(-(?<script>[a-z]{4}))?
|
|
174
174
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
175
175
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
176
176
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
177
177
|
(?:-(?<privateuse>(?:${e})))?
|
|
178
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var by=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Mt=(a,e)=>{let t=a;t=(0,kl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,gy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,kl.default)(t,n,(o,u)=>(0,Xa.isNullable)(s)?o:(0,Xa.isNullable)(u)?s:(0,vy.default)(s,parseInt(u,10),"0"))}return t},To=(a,e)=>{var F,_,K,q,ee,pe,ce,N,O,k,R,X,z,Ct,Dt,me,Ne,Fe,qe,ot,Gt,Yt,Li,dr,pr,Zl,ed,td,id,rd,ad,sd,nd,od,ud,cd,ld,dd,pd,hd,fd,md,bd,gd,vd,Sd,yd,Td,Id,Ed,wd,xd,Pd,kd,Ad,Rd,Md,$d,Cd,Dd,Ld;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(It=>{var ye,Bi;return(Bi=(ye=It.textContent)==null?void 0:ye.trim())!=null?Bi:""}),o=(F=(0,Sy.default)(n,0))!=null?F:"",u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),l=s.getElementsByTagName("vk:Attrs")[0],p=l==null?void 0:l.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=l==null?void 0:l.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=l==null?void 0:l.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=l==null?void 0:l.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:c?new Date(c).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,y=s.getAttribute("mediaPresentationDuration"),x=[...s.getElementsByTagName("Period")],P=x.reduce((It,ye)=>U(M({},It),{[ye.id]:ye.children}),{}),D=x.reduce((It,ye)=>U(M({},It),{[ye.id]:ye.getAttribute("duration")}),{});y?v=by(y):(0,Al.default)(D).filter(It=>It).length&&!u?v=(0,Al.default)(D).reduce((It,ye)=>{var Bi;return It+((Bi=by(ye))!=null?Bi:0)},0):b&&(v=parseInt(b,10));let V=0,Q=(K=(_=s.getAttribute("profiles"))==null?void 0:_.split(","))!=null?K:[];for(let It of x.map(ye=>ye.id))for(let ye of P[It]){let Bi=(q=ye.getAttribute("id"))!=null?q:"id"+(V++).toString(10),ea=(ee=ye.getAttribute("mimeType"))!=null?ee:"",zo=(pe=ye.getAttribute("codecs"))!=null?pe:"",Go=(ce=ye.getAttribute("contentType"))!=null?ce:ea==null?void 0:ea.split("/")[0],mT=(O=(N=ye.getAttribute("profiles"))==null?void 0:N.split(","))!=null?O:[],Bd=(R=my((k=ye.getAttribute("lang"))!=null?k:""))!=null?R:{},Ns=(Ct=(z=(X=ye.querySelector("Label"))==null?void 0:X.textContent)==null?void 0:z.trim())!=null?Ct:void 0,bT=ye.querySelectorAll("Representation"),gT=ye.querySelector("SegmentTemplate"),vT=(me=(Dt=ye.querySelector("Role"))==null?void 0:Dt.getAttribute("value"))!=null?me:void 0,hr=Go,Me={id:Bi,language:Bd.language,isDefault:vT==="main",label:Ns,codecs:zo,hdr:hr==="video"&&Pl(zo),mime:ea,representations:[]};for(let ve of bT){let ui=(Ne=ve.getAttribute("lang"))!=null?Ne:void 0,Fs=(qe=(Fe=Ns!=null?Ns:ye.getAttribute("label"))!=null?Fe:ve.getAttribute("label"))!=null?qe:void 0,qs=(Yt=(Gt=(ot=ve.querySelector("BaseURL"))==null?void 0:ot.textContent)==null?void 0:Gt.trim())!=null?Yt:"",Vi=new URL(qs||o,e).toString(),ci=(Li=ve.getAttribute("mimeType"))!=null?Li:ea,Us=(pr=(dr=ve.getAttribute("codecs"))!=null?dr:zo)!=null?pr:"",js;if(Go==="text"){let li=ve.getAttribute("id")||"",Hs=((Zl=Bd.privateuse)==null?void 0:Zl.includes("x-auto"))||li.includes("_auto"),_i=ve.querySelector("SegmentTemplate");if(_i){let ta={representationId:(ed=ve.getAttribute("id"))!=null?ed:void 0,bandwidth:(td=ve.getAttribute("bandwidth"))!=null?td:void 0},Qs=parseInt((id=ve.getAttribute("bandwidth"))!=null?id:"",10)/1e3,Ws=(ad=parseInt((rd=_i.getAttribute("startNumber"))!=null?rd:"",10))!=null?ad:1,fr=parseInt((sd=_i.getAttribute("timescale"))!=null?sd:"",10),Yo=(nd=_i.querySelectorAll("SegmentTimeline S"))!=null?nd:[],mr=_i.getAttribute("media");if(!mr)continue;let zs=[],Gs=0,Ys="",br=0,ia=Ws,ze=0;for(let Et of Yo){let Oi=parseInt((od=Et.getAttribute("d"))!=null?od:"",10),mt=parseInt((ud=Et.getAttribute("r"))!=null?ud:"",10)||0,di=parseInt((cd=Et.getAttribute("t"))!=null?cd:"",10);ze=Number.isFinite(di)?di:ze;let Ni=Oi/fr*1e3,pi=ze/fr*1e3;for(let Lt=0;Lt<mt+1;Lt++){let hi=Mt(mr,U(M({},ta),{segmentNumber:ia.toString(10),segmentTime:(ze+Lt*Oi).toString(10)})),gr=(pi!=null?pi:0)+Lt*Ni,aa=gr+Ni;ia++,zs.push({time:{from:gr,to:aa},url:hi})}ze+=(mt+1)*Oi,Gs+=(mt+1)*Ni}br=ze/fr*1e3,Ys=Mt(mr,U(M({},ta),{segmentNumber:ia.toString(10),segmentTime:ze.toString(10)}));let ra={time:{from:br,to:1/0},url:Ys},Kt={type:"template",baseUrl:Vi,segmentTemplateUrl:mr,initUrl:"",totalSegmentsDurationMs:Gs,segments:zs,nextSegmentBeyondManifest:ra,timescale:fr};js={id:li,kind:"text",segmentReference:Kt,profiles:[],duration:v,bitrate:Qs,mime:"",codecs:"",width:0,height:0,isAuto:Hs}}else js={id:li,isAuto:Hs,kind:"text",url:Vi}}else{let li=(dd=(ld=ve.getAttribute("contentType"))!=null?ld:ci==null?void 0:ci.split("/")[0])!=null?dd:Go,Hs=(hd=(pd=ye.getAttribute("profiles"))==null?void 0:pd.split(","))!=null?hd:[],_i=parseInt((fd=ve.getAttribute("width"))!=null?fd:"",10),ta=parseInt((md=ve.getAttribute("height"))!=null?md:"",10),Qs=parseInt((bd=ve.getAttribute("bandwidth"))!=null?bd:"",10)/1e3,Ws=(gd=ve.getAttribute("frameRate"))!=null?gd:"",fr=(vd=ve.getAttribute("quality"))!=null?vd:void 0,Yo=Ws?fy(Ws):void 0,mr=(Sd=ve.getAttribute("id"))!=null?Sd:"id"+(V++).toString(10),zs=li==="video"?`${ta}p`:li==="audio"?`${Qs}Kbps`:Us,Gs=`${mr}@${zs}`,Ys=[...Q,...mT,...Hs],br,ia=ve.querySelector("SegmentBase"),ze=(yd=ve.querySelector("SegmentTemplate"))!=null?yd:gT;if(ia){let Kt=(Id=(Td=ve.querySelector("SegmentBase Initialization"))==null?void 0:Td.getAttribute("range"))!=null?Id:"",[Et,Oi]=Kt.split("-").map(hi=>parseInt(hi,10)),mt={from:Et,to:Oi},di=(Ed=ve.querySelector("SegmentBase"))==null?void 0:Ed.getAttribute("indexRange"),[Ni,pi]=di?di.split("-").map(hi=>parseInt(hi,10)):[],Lt=di?{from:Ni,to:pi}:void 0;br={type:"byteRange",url:Vi,initRange:mt,indexRange:Lt}}else if(ze){let Kt={representationId:(wd=ve.getAttribute("id"))!=null?wd:void 0,bandwidth:(xd=ve.getAttribute("bandwidth"))!=null?xd:void 0},Et=parseInt((Pd=ze.getAttribute("timescale"))!=null?Pd:"",10),Oi=(kd=ze.getAttribute("initialization"))!=null?kd:"",mt=ze.getAttribute("media"),di=(Rd=parseInt((Ad=ze.getAttribute("startNumber"))!=null?Ad:"",10))!=null?Rd:1,Ni=Mt(Oi,Kt);if(!mt)throw new ReferenceError("No media attribute in SegmentTemplate");let pi=(Md=ze.querySelectorAll("SegmentTimeline S"))!=null?Md:[],Lt=[],hi=0,gr="",aa=0;if(pi.length){let Ks=di,wt=0;for(let vr of pi){let Bt=parseInt(($d=vr.getAttribute("d"))!=null?$d:"",10),Fi=parseInt((Cd=vr.getAttribute("r"))!=null?Cd:"",10)||0,Xs=parseInt((Dd=vr.getAttribute("t"))!=null?Dd:"",10);wt=Number.isFinite(Xs)?Xs:wt;let Ko=Bt/Et*1e3,Xo=wt/Et*1e3;for(let Js=0;Js<Fi+1;Js++){let yT=Mt(mt,U(M({},Kt),{segmentNumber:Ks.toString(10),segmentTime:(wt+Js*Bt).toString(10)})),Vd=(Xo!=null?Xo:0)+Js*Ko,TT=Vd+Ko;Ks++,Lt.push({time:{from:Vd,to:TT},url:yT})}wt+=(Fi+1)*Bt,hi+=(Fi+1)*Ko}aa=wt/Et*1e3,gr=Mt(mt,U(M({},Kt),{segmentNumber:Ks.toString(10),segmentTime:wt.toString(10)}))}else if((0,Xa.isNonNullable)(v)){let wt=parseInt((Ld=ze.getAttribute("duration"))!=null?Ld:"",10)/Et*1e3,vr=Math.ceil(v/wt),Bt=0;for(let Fi=1;Fi<vr;Fi++){let Xs=Mt(mt,U(M({},Kt),{segmentNumber:Fi.toString(10),segmentTime:Bt.toString(10)}));Lt.push({time:{from:Bt,to:Bt+wt},url:Xs}),Bt+=wt}aa=Bt,gr=Mt(mt,U(M({},Kt),{segmentNumber:vr.toString(10),segmentTime:Bt.toString(10)}))}let ST={time:{from:aa,to:1/0},url:gr};br={type:"template",baseUrl:Vi,segmentTemplateUrl:mt,initUrl:Ni,totalSegmentsDurationMs:hi,segments:Lt,nextSegmentBeyondManifest:ST,timescale:Et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!li||!ci)continue;let ra={video:"video",audio:"audio",text:"text"}[li];if(!ra)continue;hr||(hr=ra),js={id:Gs,kind:ra,segmentReference:br,profiles:Ys,duration:v,bitrate:Qs,mime:ci,codecs:Us,width:_i,height:ta,fps:Yo,quality:fr}}Me.language||(Me.language=ui),Me.label||(Me.label=Fs),Me.mime||(Me.mime=ci),Me.codecs||(Me.codecs=Us),Me.hdr||(Me.hdr=hr==="video"&&Pl(Us)),Me.representations.push(js)}if(hr){let ve=r[hr].find(ui=>ui.id===Me.id);if(ve&&Me.representations.every(ui=>ui.segmentReference.type==="template"))for(let ui of ve.representations){let Fs=Me.representations.find(ci=>ci.id===ui.id);if(!Fs)continue;let qs=Fs.segmentReference,Vi=ui.segmentReference;Vi.segments.push(...qs.segments),Vi.nextSegmentBeyondManifest=qs.nextSegmentBeyondManifest}else r[hr].push(Me)}}return{duration:v,streams:r,baseUrls:n,live:S}};var Eo=Z(vt(),1),Rl=Z(Ze(),1),Ja=require("@vkontakte/videoplayer-shared/es2015");var Io=a=>{let{webmDecodingInfo:e}=G.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,Ja.assertNever)(a)}},yy=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Io(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(G.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...Io(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Io(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Io(a),...s,"HLS","HLS_ONDEMAND"];default:(0,Ja.assertNever)(e)}if(G.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:(0,Ja.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},Ty=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=G.device.isMac&&G.browser.isSafari;if(G.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,Ja.assertNever)(a)}else G.video.nativeHlsSupported&&!u&&!G.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Ml=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],wo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Eo.default)(t.value.split("."),0)}for(let t of a){let i=(0,Eo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Eo.default)(e.value.split("."),0)},xo=a=>{let e=a.map(i=>Wr(i)),{codecs:t}=G.video;return B$().filter(i=>{if((0,Rl.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Po=a=>{let e=a.map(i=>Wr(i)),{codecs:t}=G.video;return V$().filter(i=>{if((0,Rl.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Wr=a=>a.split(".")[0].replace("0",""),B$=()=>["av1","vp9","hev1","avc1"],V$=()=>["opus","mp4a"];var Vy=Z(vt(),1);var _$=(a,e={})=>{let i=e.timeout||1,r=performance.now();return De.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},O$=a=>De.clearTimeout(a),Iy=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Ey=!Iy(De.requestIdleCallback)||!Iy(De.cancelIdleCallback),ir=Ey?_$:De.requestIdleCallback,rr=Ey?O$:De.cancelIdleCallback;var C=require("@vkontakte/videoplayer-shared/es2015");var xy=Z(vt(),1);var ko=a=>a.valid,de=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var zr=class extends de{};var wy=require("@vkontakte/videoplayer-shared/es2015");var Za=class extends de{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:(0,wy.assertNever)(e)}}};var es=class extends de{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var ts=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var we=class extends de{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var is=class extends we{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var rs=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var as=class extends de{constructor(e,t){super(e,t),this.data=this.content}};var ar=class extends we{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var ss=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ns=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var os=class extends we{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var us=class extends we{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var cs=class extends we{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var ls=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ds=class extends we{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ps=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hs=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fs=class extends we{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var ms=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var bs=class extends we{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var gs=class extends we{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var vs=class extends we{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Ss=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ys=class extends we{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ts=class extends de{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var F$={ftyp:es,moov:ts,mvhd:is,moof:rs,mdat:as,sidx:ar,trak:ss,mdia:ls,mfhd:fs,tkhd:ds,traf:ms,tfhd:bs,tfdt:gs,trun:vs,minf:ps,sv3d:ns,st3d:os,prhd:us,proj:hs,equi:cs,uuid:Za,stbl:Ss,stsd:ys,avc1:Ts,unknown:zr},ri=class a{constructor(e={}){this.options=M({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!ko(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=F$[e];return i?new i(t,new a):new zr(t,new a)}};var ki=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;ko(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var U$=new TextDecoder("ascii"),j$=a=>U$.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",H$=a=>{let e=new ar(a,new ri),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},Q$=(a,e)=>{let i=new ri().parse(a),r=new ki(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,l)},W$=a=>{let t=new ri().parse(a),i=new ki(t),r={},s=i.findAll("uuid"),n=(0,xy.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},z$=a=>{var r;let t=new ri().parse(a);return(r=new ki(t).find("sidx"))==null?void 0:r.timescale},G$=(a,e)=>{let i=new ri().parse(a),s=new ki(i).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),u=s[s.length-1].children.find(l=>l.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((l,p)=>l+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},Y$=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new ri().parse(a),r=new ki(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Py={validateData:j$,parseInit:Y$,getIndexRange:()=>{},parseSegments:H$,parseFeedableSegmentChunk:Q$,getChunkEndTime:G$,getServerLatencyTimestamps:W$,getTimescaleFromIndex:z$};var Es=Z(Ze(),1),ai=require("@vkontakte/videoplayer-shared/es2015");var Ay=require("@vkontakte/videoplayer-shared/es2015");var ky={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Ry=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Is(a,t),r=i in ky,s=r?ky[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,d=Is(u),l=c*Vt(2,(o-1)*8)+d,p=t+o,h;return p+l>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},Is=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*Vt(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*Vt(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*Vt(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},$t=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Is(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,Ay.assertNever)(e)}},sr=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Ry(i);if(!e(r))return;r.type==="master"&&sr(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},My=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Ry(a);return sr(r.value,({tag:s,type:n,value:o})=>(s===17143?e=$t(o,n):s===17026?t=$t(o,n):s===17029&&(i=$t(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var $y=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],K$=[231,22612,22743,167,171,163,160,175],X$=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,c,d=!1,l=0;return sr(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=$t(m,h);c=Is(S)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=$t(m,h):p===17545?r=$t(m,h):p===21420&&c===475249515?u=$t(m,h):p===374648427?sr(m,({tag:S,type:v,value:y})=>S===30321?(d=$t(y,v)===1,!1):!0):s&&n&&(0,Es.default)($y,p)&&(o=!0),!o}),(0,ai.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,ai.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,ai.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},J$=a=>{if((0,ai.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Z$=(a,e)=>{let t=!1,i=!1,r=o=>(0,ai.isNonNullable)(o.time)&&(0,ai.isNonNullable)(o.position),s=[],n;return sr(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=$t(c,u));break;case 183:break;case 241:n&&(n.position=$t(c,u));break;default:t&&(0,Es.default)($y,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:d}=o,l=s[u+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},eC=a=>{let e=0,t=!1;try{sr(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Es.default)(K$,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,Es.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Cy={validateData:My,parseInit:X$,getIndexRange:J$,parseSegments:Z$,parseFeedableSegmentChunk:eC};var nr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Cy;case"mp4":return Py}}throw new ReferenceError(`Unsupported mime type ${a}`)};var $l=Z(vt(),1);var Dy=require("@vkontakte/videoplayer-shared/es2015"),Ai=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Ii(s):void 0)!=null?u:(0,Dy.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},ws=({id:a,bitrate:e})=>({id:a,bitrate:e}),Ly=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),By=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Cl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,$l.default)(i.split("."),0),isDefault:r}),Dl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,$l.default)(r.split("."),0)}),Ll=a=>"url"in a,ht=a=>a.type==="template";var Gr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,manifest:o}){this.error$=new C.Subject;this.playingRepresentation$=new C.ValueSubject(void 0);this.playingRepresentationInit$=new C.ValueSubject(void 0);this.currentSegmentLength$=new C.ValueSubject(0);this.onLastSegment$=new C.ValueSubject(!1);this.fullyBuffered$=new C.ValueSubject(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new Ie;this.downloadAbortController=new Ie;this.subscription=new C.Subscription;this.startWith=(0,C.abortable)(this.destroyAbortController.signal,function(e){return he(this,null,function*(){let t=this.representations.get(e);(0,C.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=nr(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,C.assertNonNullable)(i,"No init buffer for starting representation"),(0,C.assertNonNullable)(r,"No segments for starting representation"),yield new _t(this.nativeBufferManager.addInitSegment(i)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)})}.bind(this));this.switchTo=(0,C.abortable)(this.destroyAbortController.signal,function(e,t=!0){return he(this,null,function*(){var l;if((0,C.isNullable)(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);(0,C.assertNonNullable)(r,`No such representation ${e}`),(0,C.assertNonNullable)(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),n=this.segments.get(r.id);(0,C.assertNonNullable)(s,"No init buffer for switching representation"),(0,C.assertNonNullable)(n,"No segments for switching representation");let o=(l=this.getCurrentPosition())!=null?l:0,u=p=>p.segment.networkStatus!=="downloaded"||p.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,c=p=>{let h=this.representations.get(p.representationId);return(0,C.assertNonNullable)(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},d=p=>t?u(p)&&c(p):u(p);this.bufferPlaybackQueue.filter(d).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!d(p)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1})}.bind(this));this.waitExponentialDownloadDelay=(0,C.abortable)(this.downloadAbortController.signal,function(){return he(this,null,function*(){let e=(0,C.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,C.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,C.fromEvent)(i,"online").pipe((0,C.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})})}.bind(this));var u;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=(u=o==null?void 0:o.baseUrls)!=null?u:[],this.representations=new Map(i.map(c=>[c.id,c]))}seek(e){return I(this,null,function*(){yield this.abort(),yield this.clearBuffer(),yield this.maintain(e)})}maintain(){return I(this,arguments,function*(e=this.getCurrentPosition()){(0,C.isNullable)(e)||(yield this.maintainPlaybackBuffer(e),yield this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))})}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return(0,C.isNonNullable)(t)&&(0,C.isNonNullable)(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}abort(){return I(this,null,function*(){this.abortDownload(),yield this.abortNativeBuffer()})}findSegmentStartTime(e){var s,n;let t=(n=(s=this.downloadingRepresentationId)!=null?s:this.playingRepresentationId)!=null?n:"",i=this.segments.get(t),r=i==null?void 0:i.find(o=>o.time.from<=e&&o.time.to>=e);return r==null?void 0:r.time.from}getRepresentationInitialTime(){var t;if((0,C.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return((t=e==null?void 0:e[0].time.from)!=null?t:0)/1e3}calculateDurationFromSegments(){var t;if((0,C.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,Vy.default)(e,-1))==null?void 0:t.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,C.getWindow)();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.__polyfill_cancelIdleCallback_6ab59jil76g6)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_6ab59jil76g6(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=Ai(e),s=Ai(t);i=(0,C.isNonNullable)(r)&&(0,C.isNonNullable)(s)&&(0,C.isHigher)(s.quality,r.quality)}else if(this.kind==="audio"){let r=ws(e),s=ws(t);i=(0,C.isNonNullable)(r==null?void 0:r.bitrate)&&(0,C.isNonNullable)(s==null?void 0:s.bitrate)&&s.bitrate>r.bitrate}return i}clearBuffer(){return I(this,null,function*(){this.bufferClearingMutex=!0,yield this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1})}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new Ie,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}abortNativeBuffer(){return I(this,null,function*(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=yield this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i})}loadInits(e){return I(this,null,function*(){yield this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,ir(r=>I(this,null,function*(){return yield this.loadInitIfNeeded(i,"low",!1)})))})}loadInitIfNeeded(e,t="auto",i=!1){return I(this,null,function*(){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():(0,C.isNonNullable)(r)?s=r:s=this.loadInit(e,t,i),yield s})}loadInit(e,t="auto",i=!1){return I(this,null,function*(){var r;try{let s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s);this.initDataPromises.set(e.id,n);let{initMetadata:o,initDataView:u,segments:c}=(r=yield n)!=null?r:{};if(this.initDataPromises.delete(e.id),(0,C.isNullable)(u)||(0,C.isNullable)(c))return;o&&this.parsedInitData.set(e.id,o);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d),this.segments.set(e.id,c),this.failedDownloads=0}catch(s){i&&this.error$.next({id:"LoadInits",category:C.ErrorCategory.WTF,message:"loadInit threw",thrown:s})}})}maintainNativeBuffer(){return I(this,null,function*(){var o;let e=this.getCurrentPosition();if((0,C.isNullable)(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(u=>this.withinInterval(e,u.segment.time)),i=this.bufferPlaybackQueue.find(u=>u.segment.bufferStatus!=="fed"),r=this.initData.get((o=i==null?void 0:i.representationId)!=null?o:""),s=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;(0,C.isNonNullable)(r)&&(0,C.isNonNullable)(i)&&(0,C.isNonNullable)(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(yield this.abortNativeBuffer(),yield this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,C.isNonNullable)(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?yield this.appendSegmentFully(i,n):yield this.appendSegmentPartially(i,n)),(0,C.isNonNullable)(s)&&this.withinRemoveInterval(e,s.segment.time)&&(yield this.removeSegment(s,n)),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1})}maintainPlaybackBuffer(e){return I(this,null,function*(){(0,C.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,C.isNullable)(t)||(0,C.isNullable)(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);(0,C.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),yield this.processCachedItems();let s=this.selectItemsToLoad();yield this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1})}actualizeLastSegmentInfo(e){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if((0,C.isNullable)(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];(0,C.isNullable)(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){(0,C.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;(0,C.isNonNullable)(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&s>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;s-=u-o,r++}return n}processCachedItems(){return I(this,null,function*(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)yield this.onDownloadItem(e[0]),e.shift()})}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return(0,C.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,C.isNonNullable)(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return(0,C.isNonNullable)(e)?e-i>t:!1}appendSegmentFully(e,t){return I(this,null,function*(){if((0,C.isNullable)(e.segment.data))return;e.segment.feedingBytes=e.segment.size,(yield this.nativeBufferManager.append(e.segment.data,t))&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))})}appendSegmentPartially(e,t){return I(this,null,function*(){if((0,C.isNullable)(e.segment.data)||(0,C.isNullable)(e.segment.loadedBytes)||(0,C.isNullable)(e.segment.feedingBytes)||(0,C.isNullable)(e.segment.fedBytes)||(0,C.isNullable)(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s!=null&&s.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,(yield this.nativeBufferManager.append(s,t))&&(e.segment.fedBytes+=s.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))})}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}removeSegment(e,t){return I(this,null,function*(){let{from:i,to:r}=e.segment.time,s=(r-i)/4;(yield this.nativeBufferManager.remove(0,r-s,t))&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())})}onDownloadItem(e){return I(this,null,function*(){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||(0,C.isNonNullable)(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()})}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let s=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)(0,C.isNonNullable)(o.size)&&s>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())(0,C.isNonNullable)(o.size)&&s>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size)}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())this.updateRepresentationBaseUrl(t,e)}};var Wt=require("@vkontakte/videoplayer-shared/es2015");var Ao=class extends Gr{constructor(e,t,i,r){super(e,t,i,r)}loadItems(e,t,i="auto"){return I(this,null,function*(){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let o=this.prepareFetchParams(e,t),{url:s}=o,n=fi(o,["url"]);if(this.failedDownloads&&(yield this.waitExponentialDownloadDelay()),!r.aborted)try{yield this.fetcher.fetch(s,U(M({},n),{priority:i})),this.lastDataObtainedTimestampMs=(0,Wt.now)(),this.failedDownloads=0}catch(u){this.abortDownloadingItems(),Rt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=s);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(Ke(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:(o,u)=>I(this,null,function*(){if(!i.aborted)try{this.lastDataObtainedTimestampMs=(0,Wt.now)(),yield this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Wt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}),signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}onSomeDataLoaded(o){return I(this,arguments,function*({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:s,signal:n}){let u=this.representations.get(i);if(!(!this.downloadingBufferItems.length||(0,Wt.isNullable)(u)||(0,Wt.isNullable)(r)||n.aborted))for(let c of e){let{segment:d}=c,l=d.byte.from-r,p=d.byte.to-r,h=p-l+1,m=l<s,b=p<=s;d.size=h,m&&(d.networkStatus==="downloading"&&d.bufferStatus==="none"&&b?(d.data=new DataView(t.buffer,t.byteOffset+l,h),this.currentVirtualBufferSize+=d.size,this.onItemFullyDownloaded(c),d.loadedBytes=Math.min(h,s-l),yield this.onDownloadItem(c)):(0,Wt.isNonNullable)(d.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&d.networkStatus==="downloading"&&(d.loadedBytes=Math.min(h,s-l),b&&(this.currentVirtualBufferSize+=d.size,this.onItemFullyDownloaded(c)),d.loadedBytes>d.feedingBytes&&(d.data=new DataView(t.buffer,t.byteOffset+l,d.loadedBytes),yield this.onDownloadItem(c))))}})}updateRepresentationBaseUrl(e,t){if(Ke(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var si=require("@vkontakte/videoplayer-shared/es2015");var Yr=class extends Gr{constructor(e,t,i,r){super(e,t,i,r)}loadItems(e,t,i="auto"){return I(this,null,function*(){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let o=this.prepareFetchParams(e,t),{url:s}=o,n=fi(o,["url"]);if(this.failedDownloads&&(yield this.waitExponentialDownloadDelay()),!r.aborted)try{let u=yield this.fetcher.fetch(s,U(M({},n),{priority:i}));if(this.lastDataObtainedTimestampMs=(0,si.now)(),(0,si.isNullable)(u))return;let c=e[0],d=new DataView(u);c.segment.size=d.byteLength,c.segment.loadedBytes=d.byteLength,c.segment.data=d,this.onItemFullyDownloaded(c),yield this.onDownloadItem(c),this.failedDownloads=0}catch(u){this.abortDownloadingItems(),Rt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:(n,o)=>I(this,null,function*(){if(!r.aborted)try{this.lastDataObtainedTimestampMs=(0,si.now)(),yield this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:si.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}),signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Ke(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}onSomeDataLoaded(n){return I(this,arguments,function*({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:s}){let o=e[0],{segment:u}=o,c=this.representations.get(i);!this.downloadingBufferItems.length||(0,si.isNullable)(c)||(0,si.isNullable)(u.feedingBytes)||u.networkStatus!=="downloading"||s.aborted||(u.loadedBytes=r,u.loadedBytes>u.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(u.data=new DataView(t.buffer,t.byteOffset,u.loadedBytes),yield this.onDownloadItem(o)))})}updateRepresentationBaseUrl(e,t){if(!Ke(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var Bl=Z(Ga(),1),_y=Z(vt(),1);var Oe=require("@vkontakte/videoplayer-shared/es2015");var Ro=class a extends Yr{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new Oe.ValueSubject(0);this.currentLowLatencySegmentLength$=new Oe.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){var r,s,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,Bl.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if((0,Oe.isNullable)(o)||!Ke(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>U(M({},h),{networkStatus:"none",bufferStatus:"none",size:void 0})),c=100,d=(r=this.segments.get(o.id))!=null?r:[],l=(n=(s=(0,_y.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>l>=h.time.from+c&&l<=h.time.to+c);if(p===-1){let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...d,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Oe.assertNonNullable)(t);let i=this.segments.get(t);if(i!=null&&i.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t==null?void 0:t.streams[this.kind],r=(0,Bl.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Oe.isNullable)(r))return;let s=this.segments.get(r.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){var r;if((0,Oe.isNullable)(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return(0,Oe.isNullable)(t)||!Ke(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return U(M({},super.prepareFetchParams(t,i)),{isLowLatency:this.isActiveLowLatency()})}onSomeDataLoaded(r){return I(this,null,function*(){var s=r,{downloadingItems:t}=s,i=fi(s,["downloadingItems"]);yield qd(a.prototype,this,"onSomeDataLoaded").call(this,M({downloadingItems:t},i)),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])})}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),(0,Oe.isNullable)(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);s&&n&&this.currentLiveSegmentServerLatency$.next(n-s),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){var n;let i=t.segment.data,r=(n=this.representations.get(t.representationId))==null?void 0:n.segmentReference;if((0,Oe.isNullable)(t.segment.data)||(0,Oe.isNullable)(r)||!Ke(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=s.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let s of this.representations.values()){let n=s.segmentReference;if(!Ke(n))return;let o=(r=this.segments.get(s.id))!=null?r:[],u=o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.from));if(u!=null&&u.isCurrentLowLatency&&(u.time.to=t.segment.time.to,i=u.time.to-u.time.from,u.isCurrentLowLatency=!1),!!!o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let d=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),l=Mt(n.segmentTemplateUrl,{segmentTime:d});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:l,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}loadInit(t,i="auto",r=!1){return I(this,null,function*(){var s;try{let n=this.tuning.dash.useFetchPriorityHints?i:"auto",o=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,n);this.initDataPromises.set(t.id,o);let{initMetadata:u,initDataView:c,segments:d}=(s=yield o)!=null?s:{};if(this.initDataPromises.delete(t.id),(0,Oe.isNullable)(c)||(0,Oe.isNullable)(d))return;u&&this.parsedInitData.set(t.id,u);let l=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,l);let p=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(t.id,p),this.failedDownloads=0}catch(n){r&&this.error$.next({id:"LoadInits",category:Oe.ErrorCategory.WTF,message:"loadInit threw",thrown:n})}})}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[],n=0,o=i.length-1;do s.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[s[0]]:s}};var xs=class{static getBufferManager(e,t,i,r){var s;return(s=r.manifest)!=null&&s.live?new Ro(e,t,i,r):Ke(i[0].segmentReference)?new Yr(e,t,i,r):new Ao(e,t,i,r)}};var Xe=require("@vkontakte/videoplayer-shared/es2015");var Ri=require("@vkontakte/videoplayer-shared/es2015");var tC=18,Oy=!1;try{Oy=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=tC}catch(a){console.error(a)}var Vl=class{constructor(e,t=!1){this.bufferFull$=new Ri.Subject;this.error$=new Ri.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Ri.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return I(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return I(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return I(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Oy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ri.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Ri.assertNever)(t)}}},Ny=Vl;var Mi=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var Ps=class{constructor(e){this.error$=new Xe.Subject;this.subscription=new Xe.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Ny(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,Xe.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Xe.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}clear(e){return I(this,null,function*(){let t=this.getBufferState();if((0,Xe.isNullable)(t))return Promise.resolve(!1);let i=!0;yield this.sourceBufferTaskQueue.abort();for(let r of t)i&&(i=yield this.sourceBufferTaskQueue.remove(r.from,r.to,e));return i})}warmUpMediaSource(){!(0,Xe.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,Xe.isNullable)(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return(0,Xe.isNullable)(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,Xe.isNullable)(e)?0:Mi(this.sourceBuffer.buffered,e)}abortBuffer(e){return I(this,null,function*(){return(0,Xe.isNullable)(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)})}destroy(){var e;if(this.subscription.unsubscribe(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null}};var iC=["timeupdate","progress","play","seeked","stalled","waiting"],Fy=["timeupdate","progress","loadeddata","playing","seeked"],Mo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new E.Subscription;this.subscriptionRemovable=new E.SubscriptionRemovable;this.representationSubscription=new E.Subscription;this.forceEnded$=new E.Subject;this.destroyController=new Ie;this.state$=new ne("none");this.currentVideoRepresentation$=new E.ValueSubject(void 0);this.currentVideoRepresentationInit$=new E.ValueSubject(void 0);this.currentAudioRepresentation$=new E.ValueSubject(void 0);this.currentVideoSegmentLength$=new E.ValueSubject(0);this.currentAudioSegmentLength$=new E.ValueSubject(0);this.error$=new E.Subject;this.manifestRequested=new E.Subject;this.manifestReceived=new E.Subject;this.firstBytesRequested=new E.Subject;this.firstBytesReceived=new E.Subject;this.lastConnectionType$=new E.ValueSubject(void 0);this.lastConnectionReused$=new E.ValueSubject(void 0);this.lastRequestFirstBytes$=new E.ValueSubject(void 0);this.lastConnectionMetrics$=new E.ValueSubject(void 0);this.lastDownloadMetrics$=new E.ValueSubject(void 0);this.currentLiveTextRepresentation$=new E.ValueSubject(null);this.isLive$=new E.ValueSubject(!1);this.isActiveLive$=new E.ValueSubject(!1);this.isLowLatency$=new E.ValueSubject(!1);this.liveDuration$=new E.ValueSubject(0);this.liveSeekableDuration$=new E.ValueSubject(0);this.liveAvailabilityStartTime$=new E.ValueSubject(0);this.liveStreamStatus$=new E.ValueSubject(void 0);this.currentBuffer$=new E.ValueSubject({from:0,to:0});this.bufferLength$=new E.ValueSubject(0);this.nativeBufferLength$=new E.ValueSubject(0);this.liveLatency$=new E.ValueSubject(void 0);this.liveLoadBufferLength$=new E.ValueSubject(0);this.livePositionFromPlayer$=new E.ValueSubject(0);this.currentStallDuration$=new E.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new E.ValueSubject(0);this.fetcherRecoverableError$=new E.Subject;this.fetcherError$=new E.Subject;this.initRepresentations=(0,E.abortable)(this.destroyController.signal,function(e,t,i){return he(this,null,function*(){var s;this.tracer.log("initRepresentationsStart",(0,E.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),(0,E.assertNonNullable)(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?(s=this.audioBufferManager)==null?void 0:s.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.fetchManifest=(0,E.abortable)(this.destroyController.signal,function(){return he(this,null,function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){(0,E.isNullable)(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:E.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:e})}})}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new vo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}initManifest(e,t,i){return I(this,null,function*(){var r;this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:E.ErrorCategory.PARSER,message:"No playable video representations"})})}initBuffer(){var t,i;(0,E.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,E.merge)(...iC.map(r=>(0,E.fromEvent)(this.element,r)),(0,E.fromEvent)((0,E.getWindow)(),"online")).subscribe(()=>this.tick(),r=>this.error$.next({id:"DashVKPlayer",category:E.ErrorCategory.WTF,message:"Internal logic error",thrown:r})));let e=[...(i=(t=this.source)==null?void 0:t.activeSourceBuffers)!=null?i:[]];this.subscription.add((0,E.merge)(...e.map(r=>(0,E.fromEvent)(r,"updateend"))).subscribe(r=>this.reinitDecoderIfNeeded())),this.subscription.add((0,E.fromEvent)(this.element,"waiting").subscribe(r=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,E.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),s=>this.error$.next({id:"StallWatchdogCallback",category:E.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:s})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}switchRepresentation(e,t,i=!1){return I(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)})}seek(e,t=!1){return I(this,null,function*(){var r,s,n,o;(0,E.assertNonNullable)(this.element),(0,E.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,yield this.videoBufferManager.seek(i),yield(o=this.audioBufferManager)==null?void 0:o.seek(i),this.tracer.log("seek",(0,E.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){(0,E.isNonNullable)(this.element)&&(0,E.isNonNullable)(this.source)&&(0,E.isNonNullable)(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(i=>i.warmUpMediaSource())}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(r=>r.destroy()),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&(0,E.getWindow)().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),(0,E.isNonNullable)(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){var e;return((e=this.source)==null?void 0:e.readyState)!=="open"}reinitDecoderIfNeeded(e=!1){return I(this,null,function*(){var r,s;let t=(s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[];if((0,E.isNullable)(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(n=>i>=n.from&&i<=n.to)&&(e?yield this.seek(i):this.element.currentTime=this.element.currentTime)})}stallWatchdogIntervalCallback(){return I(this,null,function*(){(0,E.assertNonNullable)(this.element),(0,E.assertNonNullable)(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(yield this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);yield this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",(0,E.flattenObject)(i))})}isStallExceeded(e){var p,h,m,b,S,v,y,x;let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=(0,E.now)(),s=100,n=(h=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?h:0;this.videoLastDataObtainedTimestamp$.next(n);let o=(b=(m=this.audioBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0,u=(v=(S=this.videoBufferManager)==null?void 0:S.getForwardPlaybackBufferDuration())!=null?v:0,c=(x=(y=this.audioBufferManager)==null?void 0:y.getForwardPlaybackBufferDuration())!=null?x:0,d=(0,E.isNonNullable)(this.videoBufferManager)&&u<s&&r-n>i,l=(0,E.isNonNullable)(this.audioBufferManager)&&c<s&&r-o>i;return(d||l)&&e>i||e>=t}updateManifest(){return I(this,null,function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetchManifest();if((0,E.isNullable)(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",(0,E.flattenObject)(i)),i})}parseManifest(e){var t;try{return To(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=fo(e))!=null?t:{id:"ManifestParsing",category:E.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:i};this.error$.next(r)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,c)=>{var d,l,p,h;return!!((l=(d=this.element)==null?void 0:d.canPlayType)!=null&&l.call(d,u)&&((h=(p=lt())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${c}"`))||o==="text")},r,s;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));t[o]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);o==="audio"&&(s=Po(l),d=s[0]),o==="video"&&(r=xo(l),this.forceVideoCodec&&(0,qy.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=c.filter(({codecs:p})=>Wr(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=wo(l),d&&(t[o]=c.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=t.video.some(m=>m.hdr),h=t.video.some(m=>!m.hdr);G.display.isHDR&&l&&p?t.video=t.video.filter(m=>m.hdr):h&&(t.video=t.video.filter(m=>!m.hdr))}}let n=U(M({},e),{streams:t});return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:s}),n}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){(0,E.assertNonNullable)(this.manifest),(0,E.assertNonNullable)(this.element);let s=c=>{this.representationSubscription.add((0,E.fromEvent)(c,"error").pipe((0,E.filter)(d=>{var l;return!!((l=this.element)!=null&&l.played.length)})).subscribe(d=>{this.error$.next({id:"VideoSource",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=vn();let n=(0,E.getWindow)().document,o=n.createElement("source");if(s(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),kr())if(r){let c=n.createElement("source");s(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new Ps(this.source),this.videoBufferManager=xs.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,E.isNonNullable)(i)){this.audioNativeBufferManager=new Ps(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=xs.getBufferManager("audio",this.audioNativeBufferManager,c,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}waitStreamToOpen(){return I(this,null,function*(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(t=>{var i;e&&(this.timeoutSourceOpenId=(0,E.getWindow)().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(i=this.source)==null||i.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&(0,E.getWindow)().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}})}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add((0,E.merge)(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),(0,E.assertNonNullable)(this.videoBufferManager),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add((0,E.merge)(...Fy.map(e=>(0,E.fromEvent)(this.element,e))).pipe((0,E.map)(e=>{var t;return(t=this.videoBufferManager)==null?void 0:t.getPlaybackBufferState()}),(0,E.filter)(E.isNonNullable),(0,E.map)(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add((0,E.merge)(...Fy.map(e=>(0,E.fromEvent)(this.element,e))).pipe((0,E.map)(e=>{var t,i,r,s;return Math.max((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(s=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?s:0)}),(0,E.filterChanged)()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe((0,E.filter)(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=(0,E.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}tick(){return I(this,null,function*(){var r,s,n;if((0,E.isNullable)(this.element)||(0,E.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[]).find(o=>e>=o.from&&e<=o.to);this.nativeBufferLength$.next(i?i.to-e:0),yield this.videoBufferManager.maintain(e),yield(n=this.audioBufferManager)==null?void 0:n.maintain(e)})}};var ge=require("@vkontakte/videoplayer-shared/es2015");var $o=class extends Mo{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;(0,ge.assertNonNullable)(this.manifest),(0,ge.assertNonNullable)(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,_l.default)((0,_l.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),Ke(i.segmentReference)&&i.segmentReference.totalSegmentsDurationMs&&r.push(i.segmentReference.totalSegmentsDurationMs),r})];this.source.duration=Math.max(...e)/1e3}restoreAfterDeepStall(e){return I(this,null,function*(){var i,r;(0,ge.assertNonNullable)(this.element);let t=this.element.currentTime*1e3;yield Promise.all([(i=this.videoBufferManager)==null?void 0:i.maintain(t),(r=this.audioBufferManager)==null?void 0:r.maintain(t)]),e.position=t})}initDisableStallWatchdogSubscription(){(0,ge.assertNonNullable)(this.element);let e=(0,ge.merge)((0,ge.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,ge.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,ge.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,ge.merge)(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe((0,ge.map)(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=(0,ge.merge)(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe((0,ge.map)(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=(0,ge.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,ge.filterChanged)(),(0,ge.map)(({allBuffersFull:s,someBufferEnded:n})=>s&&n),(0,ge.filter)(s=>s)),r=()=>{var s;try{(s=this.source)==null||s.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:ge.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add((0,ge.merge)(this.forceEnded$,i).pipe((0,ge.filter)(s=>(0,ge.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var Kr=class extends za{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,Uy.filterChanged)()).subscribe(s=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:l}])=>l.id===s);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,c=this.params.desiredState.videoStream.getTransition();c&&c.to&&c.to.id===u.id&&this.params.desiredState.videoStream.setState(c.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(so(u));let d=this.player.calculateDurationFromSegments();d&&this.params.output.duration$.next(d/1e3)},r))}getPlayer(){return new $o({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Y=require("@vkontakte/videoplayer-shared/es2015");var Wy=Z(Ze(),1),ql=Z(Ga(),1);var $i=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var T=require("@vkontakte/videoplayer-shared/es2015");var Co=Z(Ze(),1),or=Z(vt(),1),Do=Z(Ga(),1);var Qy=Z(zc(),1);var Ci=require("@vkontakte/videoplayer-shared/es2015");var rC=18,jy=!1;try{jy=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=rC}catch(a){console.error(a)}var Ol=class{constructor(e,t=!1){this.bufferFull$=new Ci.Subject;this.error$=new Ci.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Ci.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return I(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return I(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return I(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};jy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ci.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Ci.assertNever)(t)}}},Hy=Ol;var Nl=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var A=require("@vkontakte/videoplayer-shared/es2015");var ks=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new A.ValueSubject(0);this.currentLowLatencySegmentLength$=new A.ValueSubject(0);this.currentSegmentLength$=new A.ValueSubject(0);this.onLastSegment$=new A.ValueSubject(!1);this.fullyBuffered$=new A.ValueSubject(!1);this.playingRepresentation$=new A.ValueSubject(void 0);this.playingRepresentationInit$=new A.ValueSubject(void 0);this.error$=new A.Subject;this.gaps=[];this.subscription=new A.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ie;this.switchAbortController=new Ie;this.destroyAbortController=new Ie;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,A.abortable)(this.destroyAbortController.signal,function(e){return he(this,null,function*(){let t=this.representations.get(e);(0,A.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Hy(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:A.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Te(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Nl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<d).catch(l=>{this.handleAsyncError(l,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,A.assertNonNullable)(i,"No init buffer for starting representation"),(0,A.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,A.abortable)(this.destroyAbortController.signal,function(e,t=!1){return he(this,null,function*(){if(!Te(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,A.isNullable)(s)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new _t(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,A.abortable)(this.destroyAbortController.signal,function(e,t=!1){return he(this,null,function*(){if(!Te(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,A.isNullable)(s)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new _t(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,A.abortable)(this.destroyAbortController.signal,function(e){return he(this,null,function*(){var u;let t=(0,Do.default)(e,c=>c.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let l=this.representations.get(c);if(!l||!ht(l.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,p)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);(0,A.assertNonNullable)(r,`Representation not found by id ${i}`);let s=this.segments.get(i);(0,A.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,A.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.live),this.baseUrls=(d=c==null?void 0:c.baseUrls)!=null?d:[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Te(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ie,(0,A.abortable)(this.switchAbortController.signal,function(i,r=!1){return he(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,A.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,A.isNullable)(o)||(0,A.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,A.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,A.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!(0,A.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return I(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ie,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){var p;if((0,A.isNullable)(e)||(0,A.isNullable)(this.downloadingRepresentationId)||(0,A.isNullable)(this.playingRepresentationId)||(0,A.isNullable)(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||(0,A.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if((0,A.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,A.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,A.isNullable)(r)||(0,A.isNullable)(s))return;let n=r.find(h=>e>=h.time.from&&e<h.time.to);(0,A.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=this.getForwardBufferDuration(e),m=Ai(i),b=Ai(t),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,A.isNonNullable)(m)&&(0,A.isNonNullable)(b)&&(0,A.isHigher)(m.quality,b.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(S||v?o+=Math.min(h,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let x=(p=[...this.segments.entries()].map(([P,D])=>{let V=D.find(Q=>e>=Q.time.from&&e<Q.time.to);return{representationId:P,status:V==null?void 0:V.status}}).find(P=>P.status==="fed"))==null?void 0:p.representationId;x&&(this.playingRepresentationId=x,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Nl(this.sourceBuffer.buffered)>=this.bufferLimit){let h=this.getForwardBufferDuration(e),m=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<m).catch(b=>{this.handleAsyncError(b,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Co.default)(d,n))h="high";else{let m=(0,or.default)(d,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(d,t,h).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,or.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;(0,A.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,Do.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,s;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,Do.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!ht(n.segmentReference))return;let o=n.segmentReference.segments.map(p=>U(M({},p),{status:"none",size:void 0})),u=100,c=(i=this.segments.get(n.id))!=null?i:[],d=(s=(r=(0,or.default)(c,-1))==null?void 0:r.time.to)!=null?s:0,l=o==null?void 0:o.findIndex(p=>d>=p.time.from+u&&d<=p.time.to+u);if(l===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(l+1);this.segments.set(n.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,A.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,or.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!ht(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let c=Math.round(e.time.to*s.timescale/1e3).toString(10),d=Mt(s.segmentTemplateUrl,{segmentTime:c});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&rr&&rr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&rr&&rr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:p,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+y||r<y&&m-h>=y||m<=i+y;return(p==="none"||p==="partially_ejected"&&v&&x&&this.sourceBuffer&&Te(this.mediaSource,this.sourceBuffer)&&!($i(this.sourceBuffer.buffered,h)&&$i(this.sourceBuffer.buffered,m)))&&v&&x});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=d||u<=l);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")c.push(h);else break}return c}loadSegments(e,t,i="auto"){return I(this,null,function*(){ht(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return I(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,A.abortable)(o,function(){return he(this,null,function*(){let d=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,A.now)(),!d)return;let l=new DataView(d),p=nr(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,b)}u&&r.feedingBytes&&c?yield Promise.all(c):yield this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(l);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Rt(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ht(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return I(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,A.abortable)(n,function(){return he(this,null,function*(){let u=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,A.fromEvent)(window,"online").pipe((0,A.once)()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,A.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Rt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ht(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,or.default)(e,0).byte.from,to:(0,or.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>I(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}})}}prepareTemplateFetchSegmentParams(e,t){if(!ht(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Co.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return I(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!Te(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),l=nr(o.mime).parseFeedableSegmentChunk(d,this.isLive);l!=null&&l.byteLength&&(c.status="partially_fed",u.feedingBytes+=l.byteLength,yield this.sourceBufferTaskQueue.append(l),u.fedBytes+=l.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return I(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Te(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let c of this.activeSegments){let{segment:d}=c;if(c.representationId!==t)continue;if(s.aborted){yield n();continue}let l=d.byte.from-i,p=d.byte.to-i,h=p-l+1,m=l<r,b=p<=r;if(!m)continue;let S=nr(u.mime);if(d.status==="downloading"&&b){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+l,h);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(c,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(c.loadedBytes=Math.min(h,r-l),c.loadedBytes>c.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+l+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===h?v:S.parseFeedableSegmentChunk(v);y!=null&&y.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,(yield this.sourceBufferTaskQueue.append(y,s))&&!s.aborted?(c.fedBytes+=y.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!((0,A.isNullable)(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer))){!this.isLive&&G.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&($i(this.sourceBuffer.buffered,e.segment.time.from,100)&&$i(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Ll(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=ir(()=>(0,Qy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return I(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?(0,A.abortable)(this.destroyAbortController.signal,function(){return he(this,null,function*(){let u=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,nr(e.mime),{priority:r,ignoreNetworkErrors:s})).then(u=>I(this,null,function*(){if(!u)return;let{init:c,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=l;this.isLive&&ht(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),c&&this.parsedInitData.set(e.id,c)})).then(()=>this.failedDownloads=0,u=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:A.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o})}dropBuffer(){return I(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return I(this,null,function*(){if(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,A.isNullable)(e))return!1;let r=[],s=0,n=u=>{u.sort((d,l)=>d.from-l.from);let c=[u[0]];for(let d=1;d<u.length;d++){let{from:l,to:p}=u[d],h=c[c.length-1];h.to>=l?h.to=Math.max(h.to,p):c.push(u[d])}return c},o=u=>{var d;if(s>=t)return r;r.push(M({},u.time)),r=n(r);let c=Ll(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let d=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let p of this.segments.values())for(let h of p)(0,Co.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:c,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(yield Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,d)=>c||d,!1):!1})}abortBuffer(){return I(this,null,function*(){if(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,A.isNullable)(e)?0:Mi(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let o=s.start(n)*1e3,u=s.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=ir(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:A.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,A.isNullable)(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||(0,A.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),c=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:A.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var H=require("@vkontakte/videoplayer-shared/es2015");var Bo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new H.Subject;this.firstBytesManifest$=new H.Subject;this.firstBytesRequested$=new H.Subject;this.firstBytesReceived$=new H.Subject;this.lastConnectionType$=new H.ValueSubject(void 0);this.lastConnectionReused$=new H.ValueSubject(void 0);this.lastRequestFirstBytes$=new H.ValueSubject(void 0);this.lastConnectionMetrics$=new H.ValueSubject(void 0);this.lastDownloadMetrics$=new H.ValueSubject(void 0);this.recoverableError$=new H.Subject;this.error$=new H.Subject;this.abortAllController=new Ie;this.subscription=new H.SubscriptionRemovable;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,H.abortable)(this.abortAllController.signal,function(e){return he(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Pi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=bo(i)),this.trackRequestStart(i,performance.now());let r=(0,H.now)();this.manifestRequested$.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Lo);if(s){let n=(0,H.now)();t.log("success",(0,H.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(s.headers),this.firstBytesManifest$.next();let o=s.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=yield new _t(s.text());if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",(0,H.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null})}.bind(this));this.fetch=(0,H.abortable)(this.abortAllController.signal,function(l){return he(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:d=!1}={}){var ce,N,O;let p=e,h=new Headers,m=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let k=new URL(p,(0,H.getWindow)().location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),p=k.toString();break}default:(0,H.assertNever)(t)}this.requestQuic&&(p=Pi(p));let b=this.abortAllController.signal,S;if(n){let k=new Ie;if(S=(0,H.merge)((0,H.fromEvent)(this.abortAllController.signal,"abort"),(0,H.fromEvent)(n,"abort")).subscribe(()=>{try{k.abort()}catch(R){Lo(R)}}),this.subscription.add(S),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(R){Lo(R)}b=k.signal}let v=0,y=(0,H.now)();m.log("startRequest",(0,H.flattenObject)({url:p,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:y})),this.trackRequestStart(p,performance.now()),this.firstBytesRequested$.next();let x=yield this.doFetch(p,{priority:s,headers:h,signal:b},{ignoreNetworkErrors:d}),P=(0,H.now)();if(!x)return m.error("error",{message:"No response in request"}),m.end(),this.unsubscribeAbortSubscription(S),null;if((ce=this.throughputEstimator)==null||ce.addRawRtt(P-y),!x.ok||!x.body){this.unsubscribeAbortSubscription(S);let k=`Fetch error ${x.status}: ${x.statusText}`;return m.error("error",{message:k}),m.end(),Promise.reject(new Error(`Fetch error ${x.status}: ${x.statusText}`))}if(this.onHeadersReceived(x.headers),!r&&!o){this.unsubscribeAbortSubscription(S);let k=(0,H.now)(),R={requestStartedAt:y,requestEndedAt:k,duration:k-y};return m.log("endRequest",(0,H.flattenObject)(R)),m.end(),x.arrayBuffer()}let D=x.body;if(o){let k;[D,k]=x.body.tee(),(N=this.throughputEstimator)==null||N.trackStream(k,u)}let V=D.getReader(),Q,W=parseInt((O=x.headers.get("content-length"))!=null?O:"",10);Number.isFinite(W)&&(Q=W),!Q&&i&&(Q=i.to-i.from+1);let F=Q?new Uint8Array(Q):new Uint8Array(0),_=!1,K=k=>{this.unsubscribeAbortSubscription(S),_=!0,Lo(k)},q=(0,H.abortable)(b,function(X){return he(this,arguments,function*({done:k,value:R}){if(v===0&&(this.lastRequestFirstBytes$.next((0,H.now)()-y),this.firstBytesReceived$.next()),b.aborted){this.unsubscribeAbortSubscription(S);return}if(!k&&R){if(c&&Q)F.set(R,v),v+=R.byteLength;else{let z=new Uint8Array(F.length+R.length);z.set(F),z.set(R,F.length),F=z,v+=R.byteLength}r==null||r(new DataView(F.buffer),v),yield V==null?void 0:V.read().then(q,K)}})}.bind(this));yield V==null?void 0:V.read().then(q,K),this.unsubscribeAbortSubscription(S);let ee=(0,H.now)(),pe={failed:_,requestStartedAt:y,requestEndedAt:ee,duration:ee-y};if(_)return m.error("endRequest",(0,H.flattenObject)(pe)),m.end(),null;if(v>0){let k=ee-y,X=v/(k/1e3)*8/1024,z={bytes:v,speed:X,url:e};this.lastDownloadMetrics$.next(z)}return m.log("endRequest",(0,H.flattenObject)(pe)),m.end(),F.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,H.abortable)(this.abortAllController.signal,function(e,t,i){return he(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,M({range:{from:n,to:o},measureThroughput:!1},i));if(!l)return null;let p=new DataView(l,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(l,m.from-n,m.to-m.from+1);else{let y=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(l),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,H.abortable)(this.abortAllController.signal,function(e,t){return he(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,M({measureThroughput:!1},t));return r?{init:null,segments:e.segments.map(n=>U(M({},n),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s,(0,H.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=mo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,H.getWindow)()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processPerformanceResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in(0,H.getWindow)().navigator))return"unknown";let e=(0,H.getWindow)().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(s===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch(t){this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:H.ErrorCategory.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}fetchRepresentation(e,t,i){return I(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,H.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}doFetch(e,t,i){return I(this,null,function*(){let r=yield yt(e,t);if(r.ok)return r;if(i!=null&&i.ignoreNetworkErrors)return;let s=yield r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:H.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:H.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:H.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:H.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:H.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Lo=a=>{if(!Rt(a))throw a};var As=require("@vkontakte/videoplayer-shared/es2015");var Di=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new As.ValueSubject(e.initial),this.debounced$=new As.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ge(`raw_${t}`),this.smoothedSeries$=new Ge(`smoothed_${t}`),this.reportedSeries$=new Ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Vt(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,As.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Vo=class extends Di{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ii(this.slow,e,this.params.emaAlphaSlow),this.fast=ii(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var _o=class extends Di{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=dl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ii(this.emaSmoothed,e,this.params.emaAlpha);let i=_v(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Oo=class extends Di{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?ii(this.smoothed,t,this.params.emaAlpha):t}};var ur=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Vo({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new _o({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Oo(M({initial:e,label:"liveEdgeDelay"},t))}};var Fl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var No=require("@vkontakte/videoplayer-shared/es2015");var Rs=class a{constructor(e,t){this.currentRepresentation$=new No.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,No.isNullable)(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let c=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next(U(M({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ht(t.segmentReference))}};var nC=["timeupdate","progress","play","seeked","stalled","waiting"],oC=["timeupdate","progress","loadeddata","playing","seeked"];var Fo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;this.subscriptionRemovable=new T.SubscriptionRemovable;this.representationSubscription=new T.Subscription;this.state$=new ne("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested$=new T.Subject;this.firstBytesManifest$=new T.Subject;this.manifestReceived$=new T.Subject;this.firstBytesRequested$=new T.Subject;this.firstBytesReceived$=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.lastConnectionMetrics$=new T.ValueSubject(void 0);this.lastDownloadMetrics$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new Ie;this.initManifest=(0,T.abortable)(this.destroyController.signal,function(e,t,i){return he(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=He(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,function(){return he(this,null,function*(){var u,c;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=To(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(d){let l=(u=fo(e))!=null?u:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(l)}if(!t)return null;let i=(d,l,p)=>{var h,m,b,S;return!!((m=(h=this.element)==null?void 0:h.canPlayType)!=null&&m.call(h,l)&&((S=(b=lt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${l}; codecs="${p}"`))||d==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:d,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:h}=t.live,m=((c=t.duration)!=null?c:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((l-d)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let b="active";if(h||(b=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(b),h&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let S=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(S).catch(v=>{this.error$.next({id:"updateManifest",category:T.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:v})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let d of["video","audio"]){let p=t.streams[d].filter(({mime:m,codecs:b})=>i(d,m,b));r[d]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let m=p.map(({codecs:b})=>b);d==="audio"&&(n=Po(m),h=n[0]),d==="video"&&(s=xo(m),this.forceVideoCodec&&(0,Wy.default)(s,this.forceVideoCodec)?h=this.forceVideoCodec:h=s[0]),h&&(r[d]=p.filter(({codecs:b})=>Wr(b)===h))}else{let m=new Set(p.map(({codecs:b})=>b));h=wo(m),h&&(r[d]=p.filter(({codecs:b})=>b.startsWith(h)))}if(d==="video"){let m=this.tuning.preferHDR,b=r.video.some(v=>v.hdr),S=r.video.some(v=>!v.hdr);G.display.isHDR&&m&&b?r.video=r.video.filter(v=>v.hdr):S&&(r.video=r.video.filter(v=>!v.hdr))}}let o=U(M({},t),{streams:r});return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,T.flattenObject)(o)),o})}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,function(e,t,i){return he(this,null,function*(){var l;this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,T.fromEvent)(p,"error").pipe((0,T.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=vn();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),kr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new ks("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new ks("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(Rs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Rs(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.merge)(...oC.map(p=>(0,T.fromEvent)(this.element,p))).pipe((0,T.map)(p=>this.element?Mi(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:h}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,T.interval)(h).subscribe(m=>{let b=dn(this.manifestUrlString,2);this.manifestUrlString=He(this.manifestUrlString,b+h,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,T.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Fl(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:h})=>h),(0,T.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,T.map)(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=dn(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let P=1;Math.abs(x)>v&&(P=1+Math.sign(x)*y),Fl(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let v=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(x=>{var P,D;return(D=(P=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:P.to)!=null?D:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(b=>I(this,[b],function*({liveLoadBufferLength:h,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=dn(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),P=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,D=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,V=isFinite(h)?h:m,Q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),W=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(W);let F="none";if(Q?F="active_low_latency":this.isLowLatency$.getValue()&&W?(this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),F="active_low_latency"):v!==0&&V<x?F="live_forward_buffering":V<x+D&&(F="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),F==="live_forward_buffering"||F==="live_with_target_offset"){let _=p-(x+P),K=this.normalizeLiveOffset(Math.trunc(v+_/S)),q=Math.abs(K-v),ee=0;!h||q<=this.tuning.dashCmafLive.offsetCalculationError?ee=v:K>0&&q>this.tuning.dashCmafLive.offsetCalculationError&&(ee=K),this.manifestUrlString=He(this.manifestUrlString,ee,2)}(F==="live_with_target_offset"||F==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let u=(0,T.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,T.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=(0,T.combine)({allBuffersFull:u,someBufferEnded:c}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,T.filter)(p=>p));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(l=this.manifest.duration)!=null?l:0,...(0,ql.default)((0,ql.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),ht(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Bo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=ur.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,M({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}seekLive(e){return I(this,null,function*(){(0,T.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield this.updateLiveBuffersFromManifest(this.manifest))})}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=He(this.manifestUrlString,i,2)}updateLiveBuffersFromManifest(e){return I(this,null,function*(){var t,i,r;yield(t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)})}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...nC.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&$i(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var P,D,V,Q,W,F,_,K,q,ee,pe;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||((P=this.source)==null?void 0:P.readyState)!=="open")return;let d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=(0,T.now)(),h=100,m=(V=(D=this.videoBufferManager)==null?void 0:D.lastDataObtainedTimestamp)!=null?V:0;this.videoLastDataObtainedTimestamp$.next(m);let b=(W=(Q=this.audioBufferManager)==null?void 0:Q.lastDataObtainedTimestamp)!=null?W:0,S=(_=(F=this.videoBufferManager)==null?void 0:F.getForwardBufferDuration())!=null?_:0,v=(q=(K=this.audioBufferManager)==null?void 0:K.getForwardBufferDuration())!=null?q:0,y=S<h&&p-m>r,x=this.audioBufferManager&&v<h&&p-b>r;if((!t||c)&&((y||x)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%s===0){let ce=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(ce),this.updateManifest()):this.seekLive(ce).catch(N=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:N})}),l.liveLastOffset=ce}else{let ce=this.element.currentTime*1e3;(ee=this.videoBufferManager)==null||ee.maintain(ce),(pe=this.audioBufferManager)==null||pe.maintain(ce),l.position=ce}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return I(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return I(this,null,function*(){var r,s,n,o,u;(0,T.assertNonNullable)(this.element),(0,T.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),$i(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return I(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let c of u.gaps)(r&&c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=s&&c.to+o>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?n.push(1/0):n.push(c.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i=U(M({},i),{gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,T.flattenObject)(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var nt=require("@vkontakte/videoplayer-shared/es2015"),qo=class{constructor(){this.subscription=new nt.Subscription;this.pipSize$=new nt.ValueSubject(void 0);this.videoSize$=new nt.ValueSubject(void 0);this.elementSize$=new nt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=nt.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,nt.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,nt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,nt.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var cr=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new ne("stopped");this.observableVideo=null;this.droppedFramesManager=new Fr;this.stallsManager=new co;this.elementSizeManager=new qo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ei;this.audioTrackSwitchHistory=new Ei;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,Y.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new qr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new gt(e.source.url),this.params=e,this.video=et(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(We(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 Fo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,Y.isNullable)(this.observableVideo)&&(this.observableVideo=rt(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Y.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,Y.filter)(l=>!!l.length),(0,Y.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,Y.map)(l=>l.to.state!=="none"),(0,Y.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.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.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,Y.filter)(Y.isNonNullable),(0,Y.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,Y.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(jt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),xi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(it(this.video,t.volume,i.volumeState$,r)),this.subscription.add(bt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(St(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),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 p=this.player.getStreams(),h=this.player.getCodecs();if((0,Y.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of p.audio){b.push(Cl(S));let v=[];for(let y of S.representations){let x=ws(y);v.push(x),this.audioTracksMap.set(x,{stream:S,representation:y})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of p.video){m.push(Dl(b));let S=[];for(let v of b.representations){let y=Ai(U(M({},v),{streamId:b.id}));y&&(S.push(y),this.videoTracksMap.set(y,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of p.text)for(let S of b.representations){let v=Ly(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}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),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,Y.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,Y.fromEvent)(this.video,"progress")).pipe((0,Y.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,Y.throttle)(u))),this.subscription.add(o.subscribe(()=>I(this,null,function*(){let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,S=[...this.videoTracksMap.keys()].find(y=>{var x;return((x=this.videoTracksMap.get(y))==null?void 0:x.representation.id)===m.id});(0,Y.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),l==="manifest_ready")yield this.player.initRepresentations(m.id,b==null?void 0:b.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",m.id),b){let y=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",b.id,y)}}),r)),this.subscription.add((0,Y.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,Y.merge)((0,Y.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,Y.map)(l=>l.to)))}).pipe((0,Y.map)(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),(0,Y.filterChanged)()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),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((0,Y.filterChanged)()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Dl(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,Y.filterChanged)()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Cl(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var p,h;if(l!=null&&l.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe((0,Y.map)(({to:l})=>l==="ready"),(0,Y.filterChanged)());this.subscription.add((0,Y.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,Y.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,Y.merge)(c,this.player.state$.stateChangeEnded$,(0,Y.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,Y.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Y.observableFrom)(["init"])).pipe((0,Y.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var W,F,_,K,q,ee,pe,ce,N,O,k,R,X;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Fa:Na,t=this.params.tuning.useNewAutoSelectVideoTrack?io:to,i=this.params.tuning.useNewAutoSelectVideoTrack?Ht:eo,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(W=r.videoTrack.getState())==null?void 0:W.id,u=[...this.videoTracksMap.keys()].find(({id:z})=>z===o),c=s.currentVideoTrack$.getValue(),d=((K=(_=r.videoStream.getState())!=null?_:u&&((F=this.videoTracksMap.get(u))==null?void 0:F.stream))!=null?K:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:z})=>z===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=Mi(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=(q=r.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(ee=[...this.audioStreamsMap.keys()].find(({id:z})=>z===(v==null?void 0:v.id)))!=null?ee:this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let z=e(u,p,(pe=this.audioStreamsMap.get(y))!=null?pe:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(ce=z==null?void 0:z.bitrate)!=null?ce:-1/0)}if(c){let z=e(c,p,(N=this.audioStreamsMap.get(y))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(O=z==null?void 0:z.bitrate)!=null?O:-1/0)}}let P=u;(n||!P)&&(P=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:x,forwardBufferHealth:S,current:c,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}));let D=y&&t(P,p,(k=this.audioStreamsMap.get(y))!=null?k:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=(R=this.videoTracksMap.get(P))==null?void 0:R.representation,Q=D&&((X=this.audioTracksMap.get(D))==null?void 0:X.representation);if(V&&Q)return[V,Q];if(V&&!Q&&this.audioTracksMap.size===0)return[V,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Y.ErrorCategory.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),tt(this.video),this.tracer.end()}};var Ms=class extends cr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Se=require("@vkontakte/videoplayer-shared/es2015");var $s=class extends cr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Se.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,Se.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,Se.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,Se.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Se.map)(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).add((0,Se.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,Se.merge)(r.playbackRateState$,new Se.ValueSubject(1))}).pipe((0,Se.filter)(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||(0,Se.isNullable)(d)||(t=u-d)})).add((0,Se.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,Se.merge)(r.playbackRateState$,new Se.ValueSubject(1))}).pipe((0,Se.filterChanged)((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||(0,Se.isNullable)(u)||(0,Se.isNullable)(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=By(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,Se.filter)(u=>(0,Se.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var zy="X-Playback-Duration",Ul=a=>I(null,null,function*(){var r;let e=yield yt(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(zy)?parseInt(e.headers.get(zy),10):void 0});var ue=require("@vkontakte/videoplayer-shared/es2015");var Hl=Z(oc(),1);var Uo=require("@vkontakte/videoplayer-shared/es2015");var cC=a=>{let e=null;if(a.QUALITY&&(e=Ii(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Uo.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},lC=(a,e)=>{var s,n;let t=a.split(`
|
|
179
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!d)){if(c){let l=(0,
|
|
180
|
-
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],c=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:c}),s=s+d,!i.segmentStartTime){let l=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-l}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let c=new Date(u);c.setMilliseconds(0),s=c.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,ft.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([U(M({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return I(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Ie;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 I(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:ft.ErrorCategory.WTF,thrown:t,message:e})}};var Cs=class{constructor(e){this.subscription=new ue.Subscription;this.videoState=new ne("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ue.ValueSubject([]);this.liveOffset=new Zi;this.manifestStartTime$=new ue.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,ue.assertNever)(t)}};var i;this.params=e,this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ue.VideoQuality.INVARIANT,url:this.params.source.url};let t=(r,s)=>jo(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Ho(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new gt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ue.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:ue.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ue.ValueSubject((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:ue.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=rt(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(bt(this.video,t.playbackRate,r.playbackRateState$,i)),s(St(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,ue.filterChanged)(),(0,ue.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,ue.isNonNullable)(c.to)){let l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(We(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,c,d;let o=(d=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,ue.combine)({startTime:this.manifestStartTime$.pipe((0,ue.filter)(ue.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,ue.map)(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,ue.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),tt(this.video)}prepare(){var o,u,c;let e=this.selectManifest();if((0,ue.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[p,h]of[[d,"mq"],[l,"lq"]]){let m=String(parseFloat(p||""));h&&p&&r.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=He(r.toString(),this.liveOffset.getTotalOffset(),s);(c=this.liveTextManager)==null||c.prepare(n),this.video.setAttribute("src",n),this.video.load(),Ul(n).then(d=>{var l;if(!(0,ue.isNullable)(d))this.maxSeekBackTime$.next(d);else{let p=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();((0,ue.isNullable)(p)||!isFinite(p))&&yt(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 S=new URL(m,n).toString();Ul(S).then(v=>{(0,ue.isNullable)(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ue.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=He(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}};var fe=require("@vkontakte/videoplayer-shared/es2015");var Ds=class{constructor(e){this.subscription=new fe.Subscription;this.videoState=new ne("stopped");this.manifests$=new fe.ValueSubject([]);this.unmuteAfterBrowserResetsHappened=new fe.ValueSubject(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,fe.assertNever)(t)}};this.textTracksManager=new gt(e.source.url),this.params=e,this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:fe.VideoQuality.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(We(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),jo(He(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:fe.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:fe.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=rt(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,fe.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(jt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(bt(this.video,t.playbackRate,r.playbackRateState$,i)),xi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,fe.isNonNullable)(c.to)){let m=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let b=this.manifests$.getValue().find(S=>S.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(We(b.url)))}let l=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(l!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(l),m.playbackRate=l)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe((0,fe.map)(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!G.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,fe.merge)((0,fe.fromEvent)(o,"addtrack"),(0,fe.fromEvent)(o,"removetrack"),(0,fe.fromEvent)(o,"change"),(0,fe.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,fe.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,fe.observableFrom)(["init"])).pipe((0,fe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),tt(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,fe.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[c,d]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(c||""));d&&c&&r.searchParams.set(d,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Yy=Z(Si(),1),Ql=Z(Wi(),1),Ky=Z(vt(),1);var xe=require("@vkontakte/videoplayer-shared/es2015");var Ls=class{constructor(e){this.subscription=new xe.Subscription;this.videoState=new ne("stopped");this.trackUrls={};this.textTracksManager=new gt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?B(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,xe.assertNever)(e)}};this.params=e,this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Yy.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Ql.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:xe.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=rt(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,xe.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(jt(this.video,t.isLooped,i)),xi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(bt(this.video,t.playbackRate,r.playbackRateState$,i)),s(St(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,xe.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),l=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(d!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=(0,xe.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,xe.observableFrom)(["init"])).pipe((0,xe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),tt(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,xe.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,xe.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Pi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(We(t))}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var c,d;this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=Ht(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=(c=this.params.output.currentVideoTrack$.getValue())==null?void 0:c.quality,s=!!(e.max||e.min),n=(0,Ql.default)(this.trackUrls).map(l=>l.track);if(!r||!s||_r(e,n[0].quality,(d=(0,Ky.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?(0,xe.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,xe.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var Pe=require("@vkontakte/videoplayer-shared/es2015");var Jy=require("@vkontakte/videoplayer-shared/es2015");var Xy=["stun:videostun.mycdn.me:80"],pC=1e3,hC=3,Wl=()=>null,Qo=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=Wl;this.externalStopCallback=Wl;this.externalErrorCallback=Wl;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return I(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 I(this,null,function*(){try{let e={iceServers:[{urls:Xy}]};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 I(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return I(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:Jy.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return I(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 I(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),pC)}normalizeOptions(e={}){let t={stunServerList:Xy,maxRetryNumber:hC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Bs=class{constructor(e){this.videoState=new ne("stopped");this.maxSeekBackTime$=new Pe.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,Pe.assertNever)(e)}};this.subscription=new Pe.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=et(e.container,e.tuning),this.liveStreamClient=new Qo(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),tt(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Pe.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,Pe.merge)(this.videoState.stateChangeStarted$.pipe((0,Pe.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Pe.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=rt(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(St(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(it(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,Pe.assertNever)(n.to)}},i)).add((0,Pe.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Pe.observableFrom)(["init"])).pipe((0,Pe.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(We(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:Pe.VideoQuality.INVARIANT}),this.video.srcObject=e,B(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.currentNativeBuffer$.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:Pe.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pe.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Xr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};var w=require("@vkontakte/videoplayer-shared/es2015");var ni=require("@vkontakte/videoplayer-shared/es2015");var Zy=a=>new ni.Observable(e=>{let t=new ni.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,ni.map)(({from:c,to:d})=>`${c}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,ni.map)(({type:c})=>c!==void 0)),n=new ni.Subject,o=0,u="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval),ie({m:"hangup.set",l:c,id:o})})),t.add(r.subscribe(()=>{ie({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(ie({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval),ie({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Tt=require("@vkontakte/videoplayer-shared/es2015");function eT(){return new(window.AudioContext||window.webkitAudioContext)}var Vs=class Vs{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Ie;this.subscriptions=new Tt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Tt.filter)(s=>!!s.type),(0,Tt.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){G.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Tt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Tt.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,Tt.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return I(this,null,function*(){let{volumeMultiplier:t}=this,i=eT();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Vs.errorId,category:Tt.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Vs.errorId} exception`,thrown:e})}};Vs.errorId="VolumeMultiplierManager";var Jr=Vs;var fC={chunkDuration:5e3,maxParallelRequests:5},_s=class{constructor(e){this.current$=new w.ValueSubject({type:void 0});this.providerError$=new w.Subject;this.noAvailableProvidersError$=new w.Subject;this.volumeMultiplierError$=new w.Subject;this.providerOutput={position$:new w.ValueSubject(0),duration$:new w.ValueSubject(1/0),volume$:new w.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new w.ValueSubject([]),currentVideoStream$:new w.ValueSubject(void 0),availableVideoTracks$:new w.ValueSubject([]),currentVideoTrack$:new w.ValueSubject(void 0),availableVideoCodecs$:new w.ValueSubject([]),availableAudioStreams$:new w.ValueSubject([]),currentAudioStream$:new w.ValueSubject(void 0),availableAudioTracks$:new w.ValueSubject([]),availableAudioCodecs$:new w.ValueSubject([]),currentVideoSegmentLength$:new w.ValueSubject(0),currentAudioSegmentLength$:new w.ValueSubject(0),isAudioAvailable$:new w.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new w.ValueSubject(!1),autoVideoTrackLimits$:new w.ValueSubject(void 0),currentBuffer$:new w.ValueSubject(void 0),currentNativeBuffer$:new w.ValueSubject(void 0),isBuffering$:new w.ValueSubject(!0),error$:new w.Subject,fetcherError$:new w.Subject,fetcherRecoverableError$:new w.Subject,warning$:new w.Subject,willSeekEvent$:new w.Subject,soundProhibitedEvent$:new w.Subject,seekedEvent$:new w.Subject,loopedEvent$:new w.Subject,endedEvent$:new w.Subject,manifestRequested$:new w.Subject,firstBytesManifest$:new w.Subject,manifestReceived$:new w.Subject,firstBytesRequested$:new w.Subject,firstBytesReceived$:new w.Subject,firstBytesEvent$:new w.Subject,loadedMetadataEvent$:new w.Subject,firstFrameEvent$:new w.Subject,canplay$:new w.Subject,isLive$:new w.ValueSubject(void 0),isLiveEnded$:new w.ValueSubject(null),canPlayLiveTailBuffer$:new w.ValueSubject(!1),isLowLatency$:new w.ValueSubject(!1),canChangePlaybackSpeed$:new w.ValueSubject(!0),liveTime$:new w.ValueSubject(void 0),liveBufferTime$:new w.ValueSubject(void 0),liveLatency$:new w.ValueSubject(void 0),severeStallOccurred$:new w.Subject,availableTextTracks$:new w.ValueSubject([]),currentTextTrack$:new w.ValueSubject(void 0),hostname$:new w.ValueSubject(void 0),httpConnectionType$:new w.ValueSubject(void 0),httpConnectionReused$:new w.ValueSubject(void 0),httpConnectionMetrics$:new w.ValueSubject(void 0),httpDownloadMetrics$:new w.ValueSubject(void 0),inPiP$:new w.ValueSubject(!1),inFullscreen$:new w.ValueSubject(!1),element$:new w.ValueSubject(void 0),elementVisible$:new w.ValueSubject(!0),availableSources$:new w.ValueSubject(void 0),is3DVideo$:new w.ValueSubject(!1),playbackState$:new w.ValueSubject(""),getCurrentTime$:new w.ValueSubject(null)};this.subscription=new w.Subscription;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=Nu([...Ty(this.params.tuning),...yy(this.params.tuning)]).filter(c=>(0,w.isNonNullable)(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(c=>!(0,zl.default)(r,c)),...t.filter(c=>(0,zl.default)(r,c))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,w.flattenObject)(s)),this.screenFormatsIterator=new Xr(s);let n=[...Ml(!0),...Ml(!1)];this.chromecastFormatsIterator=new Xr(n.filter(c=>(0,w.isNonNullable)(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Jr.isSupported()&&(this.volumeMultiplierManager=new Jr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){ie.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Xr(e))}))}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((0,w.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:w.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}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(0,w.assertNever)(e)}}createScreenProvider(e){var u,c,d;let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let l=this.applyFailoverHost(t[e]),p=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,w.assertNonNullable)(l),this.params.tuning.useDashProviderVirtual&&!G.device.isMobile?new Kr(U(M({},o),{source:l,sourceHls:p,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()})):this.params.tuning.useDashProviderVirtualMobile&&G.device.isMobile?new Kr(U(M({},o),{source:l,sourceHls:p,forceVideoCodec:(c=this.videoCodecsIterator)==null?void 0:c.getValue()})):new Ms(U(M({},o),{source:l,sourceHls:p,forceVideoCodec:(d=this.videoCodecsIterator)==null?void 0:d.getValue()}))}case"DASH_LIVE_CMAF":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new $s(U(M({},o),{source:l}))}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new Ds(U(M({},o),{source:l}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new Cs(U(M({},o),{source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new Ls(U(M({},o),{source:l}))}case"DASH_LIVE":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new Mv(U(M({},o),{source:l,config:U(M({},fC),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new Bs({container:i,source:l,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,w.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o={meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof Jt){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return(0,w.assertNonNullable)(c),new Ta(U(M({},o),{chromecastConnector:c}))}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,w.assertNonNullable)(u),new Ba(U(M({},o),{connection:u}))}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(0,w.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,w.assertNever)(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(0,w.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return U(M({},e),{url:i(e.url)})}return(0,tT.default)((0,Gl.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new w.Subscription,t=!1,i=0;e.add((0,w.merge)(this.providerOutput.error$.pipe((0,w.filter)(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),Zy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,w.map)(s=>({id:`ProviderHangup:${s}`,category:w.ErrorCategory.WTF,message:`A ${s} 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 s=this.params.desiredState.playbackState.transitionEnded$.pipe((0,w.filter)(({to:n})=>n==="playing"),(0,w.once)()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=ie.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&(0,w.getWindow)().console.log(`===== DASH_LIVE DEBUG START ====
|
|
178
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var vy=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Mt=(a,e)=>{let t=a;t=(0,Rl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,Sy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Rl.default)(t,n,(o,u)=>(0,Xa.isNullable)(s)?o:(0,Xa.isNullable)(u)?s:(0,yy.default)(s,parseInt(u,10),"0"))}return t},Io=(a,e)=>{var F,_,K,q,ee,pe,ce,N,O,k,R,X,z,Ct,Dt,me,Ne,Fe,qe,ot,Gt,Yt,Li,dr,pr,td,id,rd,ad,sd,nd,od,ud,cd,ld,dd,pd,hd,fd,md,bd,gd,vd,Sd,yd,Td,Id,Ed,wd,xd,Pd,kd,Ad,Rd,Md,$d,Cd,Dd,Ld,Bd,Vd;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(It=>{var ye,Bi;return(Bi=(ye=It.textContent)==null?void 0:ye.trim())!=null?Bi:""}),o=(F=(0,Ty.default)(n,0))!=null?F:"",u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),l=s.getElementsByTagName("vk:Attrs")[0],p=l==null?void 0:l.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=l==null?void 0:l.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=l==null?void 0:l.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=l==null?void 0:l.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:c?new Date(c).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,y=s.getAttribute("mediaPresentationDuration"),x=[...s.getElementsByTagName("Period")],P=x.reduce((It,ye)=>U(M({},It),{[ye.id]:ye.children}),{}),D=x.reduce((It,ye)=>U(M({},It),{[ye.id]:ye.getAttribute("duration")}),{});y?v=vy(y):(0,Ml.default)(D).filter(It=>It).length&&!u?v=(0,Ml.default)(D).reduce((It,ye)=>{var Bi;return It+((Bi=vy(ye))!=null?Bi:0)},0):b&&(v=parseInt(b,10));let V=0,Q=(K=(_=s.getAttribute("profiles"))==null?void 0:_.split(","))!=null?K:[];for(let It of x.map(ye=>ye.id))for(let ye of P[It]){let Bi=(q=ye.getAttribute("id"))!=null?q:"id"+(V++).toString(10),ea=(ee=ye.getAttribute("mimeType"))!=null?ee:"",Yo=(pe=ye.getAttribute("codecs"))!=null?pe:"",Ko=(ce=ye.getAttribute("contentType"))!=null?ce:ea==null?void 0:ea.split("/")[0],gT=(O=(N=ye.getAttribute("profiles"))==null?void 0:N.split(","))!=null?O:[],_d=(R=gy((k=ye.getAttribute("lang"))!=null?k:""))!=null?R:{},Fs=(Ct=(z=(X=ye.querySelector("Label"))==null?void 0:X.textContent)==null?void 0:z.trim())!=null?Ct:void 0,vT=ye.querySelectorAll("Representation"),ST=ye.querySelector("SegmentTemplate"),yT=(me=(Dt=ye.querySelector("Role"))==null?void 0:Dt.getAttribute("value"))!=null?me:void 0,hr=Ko,Me={id:Bi,language:_d.language,isDefault:yT==="main",label:Fs,codecs:Yo,hdr:hr==="video"&&Al(Yo),mime:ea,representations:[]};for(let ve of vT){let ui=(Ne=ve.getAttribute("lang"))!=null?Ne:void 0,qs=(qe=(Fe=Fs!=null?Fs:ye.getAttribute("label"))!=null?Fe:ve.getAttribute("label"))!=null?qe:void 0,Us=(Yt=(Gt=(ot=ve.querySelector("BaseURL"))==null?void 0:ot.textContent)==null?void 0:Gt.trim())!=null?Yt:"",Vi=new URL(Us||o,e).toString(),ci=(Li=ve.getAttribute("mimeType"))!=null?Li:ea,js=(pr=(dr=ve.getAttribute("codecs"))!=null?dr:Yo)!=null?pr:"",Hs;if(Ko==="text"){let li=ve.getAttribute("id")||"",Qs=((td=_d.privateuse)==null?void 0:td.includes("x-auto"))||li.includes("_auto"),_i=ve.querySelector("SegmentTemplate");if(_i){let ta={representationId:(id=ve.getAttribute("id"))!=null?id:void 0,bandwidth:(rd=ve.getAttribute("bandwidth"))!=null?rd:void 0},Ws=parseInt((ad=ve.getAttribute("bandwidth"))!=null?ad:"",10)/1e3,zs=(nd=parseInt((sd=_i.getAttribute("startNumber"))!=null?sd:"",10))!=null?nd:1,fr=parseInt((od=_i.getAttribute("timescale"))!=null?od:"",10),Xo=(ud=_i.querySelectorAll("SegmentTimeline S"))!=null?ud:[],mr=_i.getAttribute("media");if(!mr)continue;let Gs=[],Ys=0,Ks="",br=0,ia=zs,ze=0;for(let Et of Xo){let Oi=parseInt((cd=Et.getAttribute("d"))!=null?cd:"",10),mt=parseInt((ld=Et.getAttribute("r"))!=null?ld:"",10)||0,di=parseInt((dd=Et.getAttribute("t"))!=null?dd:"",10);ze=Number.isFinite(di)?di:ze;let Ni=Oi/fr*1e3,pi=ze/fr*1e3;for(let Lt=0;Lt<mt+1;Lt++){let hi=Mt(mr,U(M({},ta),{segmentNumber:ia.toString(10),segmentTime:(ze+Lt*Oi).toString(10)})),gr=(pi!=null?pi:0)+Lt*Ni,aa=gr+Ni;ia++,Gs.push({time:{from:gr,to:aa},url:hi})}ze+=(mt+1)*Oi,Ys+=(mt+1)*Ni}br=ze/fr*1e3,Ks=Mt(mr,U(M({},ta),{segmentNumber:ia.toString(10),segmentTime:ze.toString(10)}));let ra={time:{from:br,to:1/0},url:Ks},Kt={type:"template",baseUrl:Vi,segmentTemplateUrl:mr,initUrl:"",totalSegmentsDurationMs:Ys,segments:Gs,nextSegmentBeyondManifest:ra,timescale:fr};Hs={id:li,kind:"text",segmentReference:Kt,profiles:[],duration:v,bitrate:Ws,mime:"",codecs:"",width:0,height:0,isAuto:Qs}}else Hs={id:li,isAuto:Qs,kind:"text",url:Vi}}else{let li=(hd=(pd=ve.getAttribute("contentType"))!=null?pd:ci==null?void 0:ci.split("/")[0])!=null?hd:Ko,Qs=(md=(fd=ye.getAttribute("profiles"))==null?void 0:fd.split(","))!=null?md:[],_i=parseInt((bd=ve.getAttribute("width"))!=null?bd:"",10),ta=parseInt((gd=ve.getAttribute("height"))!=null?gd:"",10),Ws=parseInt((vd=ve.getAttribute("bandwidth"))!=null?vd:"",10)/1e3,zs=(Sd=ve.getAttribute("frameRate"))!=null?Sd:"",fr=(yd=ve.getAttribute("quality"))!=null?yd:void 0,Xo=zs?by(zs):void 0,mr=(Td=ve.getAttribute("id"))!=null?Td:"id"+(V++).toString(10),Gs=li==="video"?`${ta}p`:li==="audio"?`${Ws}Kbps`:js,Ys=`${mr}@${Gs}`,Ks=[...Q,...gT,...Qs],br,ia=ve.querySelector("SegmentBase"),ze=(Id=ve.querySelector("SegmentTemplate"))!=null?Id:ST;if(ia){let Kt=(wd=(Ed=ve.querySelector("SegmentBase Initialization"))==null?void 0:Ed.getAttribute("range"))!=null?wd:"",[Et,Oi]=Kt.split("-").map(hi=>parseInt(hi,10)),mt={from:Et,to:Oi},di=(xd=ve.querySelector("SegmentBase"))==null?void 0:xd.getAttribute("indexRange"),[Ni,pi]=di?di.split("-").map(hi=>parseInt(hi,10)):[],Lt=di?{from:Ni,to:pi}:void 0;br={type:"byteRange",url:Vi,initRange:mt,indexRange:Lt}}else if(ze){let Kt={representationId:(Pd=ve.getAttribute("id"))!=null?Pd:void 0,bandwidth:(kd=ve.getAttribute("bandwidth"))!=null?kd:void 0},Et=parseInt((Ad=ze.getAttribute("timescale"))!=null?Ad:"",10),Oi=(Rd=ze.getAttribute("initialization"))!=null?Rd:"",mt=ze.getAttribute("media"),di=($d=parseInt((Md=ze.getAttribute("startNumber"))!=null?Md:"",10))!=null?$d:1,Ni=Mt(Oi,Kt);if(!mt)throw new ReferenceError("No media attribute in SegmentTemplate");let pi=(Cd=ze.querySelectorAll("SegmentTimeline S"))!=null?Cd:[],Lt=[],hi=0,gr="",aa=0;if(pi.length){let Xs=di,wt=0;for(let vr of pi){let Bt=parseInt((Dd=vr.getAttribute("d"))!=null?Dd:"",10),Fi=parseInt((Ld=vr.getAttribute("r"))!=null?Ld:"",10)||0,Js=parseInt((Bd=vr.getAttribute("t"))!=null?Bd:"",10);wt=Number.isFinite(Js)?Js:wt;let Jo=Bt/Et*1e3,Zo=wt/Et*1e3;for(let Zs=0;Zs<Fi+1;Zs++){let IT=Mt(mt,U(M({},Kt),{segmentNumber:Xs.toString(10),segmentTime:(wt+Zs*Bt).toString(10)})),Od=(Zo!=null?Zo:0)+Zs*Jo,ET=Od+Jo;Xs++,Lt.push({time:{from:Od,to:ET},url:IT})}wt+=(Fi+1)*Bt,hi+=(Fi+1)*Jo}aa=wt/Et*1e3,gr=Mt(mt,U(M({},Kt),{segmentNumber:Xs.toString(10),segmentTime:wt.toString(10)}))}else if((0,Xa.isNonNullable)(v)){let wt=parseInt((Vd=ze.getAttribute("duration"))!=null?Vd:"",10)/Et*1e3,vr=Math.ceil(v/wt),Bt=0;for(let Fi=1;Fi<vr;Fi++){let Js=Mt(mt,U(M({},Kt),{segmentNumber:Fi.toString(10),segmentTime:Bt.toString(10)}));Lt.push({time:{from:Bt,to:Bt+wt},url:Js}),Bt+=wt}aa=Bt,gr=Mt(mt,U(M({},Kt),{segmentNumber:vr.toString(10),segmentTime:Bt.toString(10)}))}let TT={time:{from:aa,to:1/0},url:gr};br={type:"template",baseUrl:Vi,segmentTemplateUrl:mt,initUrl:Ni,totalSegmentsDurationMs:hi,segments:Lt,nextSegmentBeyondManifest:TT,timescale:Et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!li||!ci)continue;let ra={video:"video",audio:"audio",text:"text"}[li];if(!ra)continue;hr||(hr=ra),Hs={id:Ys,kind:ra,segmentReference:br,profiles:Ks,duration:v,bitrate:Ws,mime:ci,codecs:js,width:_i,height:ta,fps:Xo,quality:fr}}Me.language||(Me.language=ui),Me.label||(Me.label=qs),Me.mime||(Me.mime=ci),Me.codecs||(Me.codecs=js),Me.hdr||(Me.hdr=hr==="video"&&Al(js)),Me.representations.push(Hs)}if(hr){let ve=r[hr].find(ui=>ui.id===Me.id);if(ve&&Me.representations.every(ui=>ui.segmentReference.type==="template"))for(let ui of ve.representations){let qs=Me.representations.find(ci=>ci.id===ui.id);if(!qs)continue;let Us=qs.segmentReference,Vi=ui.segmentReference;Vi.segments.push(...Us.segments),Vi.nextSegmentBeyondManifest=Us.nextSegmentBeyondManifest}else r[hr].push(Me)}}return{duration:v,streams:r,baseUrls:n,live:S}};var wo=Z(vt(),1),$l=Z(Ze(),1),Za=require("@vkontakte/videoplayer-shared/es2015");var Ja=(s=>(s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient",s))(Ja||{});var Eo=a=>{let{webmDecodingInfo:e}=G.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,Za.assertNever)(a)}},Iy=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Eo(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(G.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...Eo(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Eo(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Eo(a),...s,"HLS","HLS_ONDEMAND"];default:(0,Za.assertNever)(e)}if(G.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:(0,Za.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},Ey=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=G.device.isMac&&G.browser.isSafari;if(G.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,Za.assertNever)(a)}else G.video.nativeHlsSupported&&!u&&!G.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Cl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],xo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,wo.default)(t.value.split("."),0)}for(let t of a){let i=(0,wo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,wo.default)(e.value.split("."),0)},Po=a=>{let e=a.map(i=>Wr(i)),{codecs:t}=G.video;return V$().filter(i=>{if((0,$l.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},ko=a=>{let e=a.map(i=>Wr(i)),{codecs:t}=G.video;return _$().filter(i=>{if((0,$l.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Wr=a=>a.split(".")[0].replace("0",""),V$=()=>["av1","vp9","hev1","avc1"],_$=()=>["opus","mp4a"];var Oy=Z(vt(),1);var O$=(a,e={})=>{let i=e.timeout||1,r=performance.now();return De.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},N$=a=>De.clearTimeout(a),wy=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),xy=!wy(De.requestIdleCallback)||!wy(De.cancelIdleCallback),ir=xy?O$:De.requestIdleCallback,rr=xy?N$:De.cancelIdleCallback;var C=require("@vkontakte/videoplayer-shared/es2015");var ky=Z(vt(),1);var Ao=a=>a.valid,de=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var zr=class extends de{};var Py=require("@vkontakte/videoplayer-shared/es2015");var es=class extends de{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:(0,Py.assertNever)(e)}}};var ts=class extends de{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var is=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var we=class extends de{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var rs=class extends we{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var as=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ss=class extends de{constructor(e,t){super(e,t),this.data=this.content}};var ar=class extends we{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var ns=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var os=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var us=class extends we{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var cs=class extends we{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var ls=class extends we{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var ds=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ps=class extends we{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var hs=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fs=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ms=class extends we{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var bs=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var gs=class extends we{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var vs=class extends we{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ss=class extends we{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ys=class extends de{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ts=class extends we{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Is=class extends de{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var q$={ftyp:ts,moov:is,mvhd:rs,moof:as,mdat:ss,sidx:ar,trak:ns,mdia:ds,mfhd:ms,tkhd:ps,traf:bs,tfhd:gs,tfdt:vs,trun:Ss,minf:hs,sv3d:os,st3d:us,prhd:cs,proj:fs,equi:ls,uuid:es,stbl:ys,stsd:Ts,avc1:Is,unknown:zr},ri=class a{constructor(e={}){this.options=M({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!Ao(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=q$[e];return i?new i(t,new a):new zr(t,new a)}};var ki=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;Ao(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var j$=new TextDecoder("ascii"),H$=a=>j$.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Q$=a=>{let e=new ar(a,new ri),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},W$=(a,e)=>{let i=new ri().parse(a),r=new ki(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,l)},z$=a=>{let t=new ri().parse(a),i=new ki(t),r={},s=i.findAll("uuid"),n=(0,ky.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},G$=a=>{var r;let t=new ri().parse(a);return(r=new ki(t).find("sidx"))==null?void 0:r.timescale},Y$=(a,e)=>{let i=new ri().parse(a),s=new ki(i).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),u=s[s.length-1].children.find(l=>l.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((l,p)=>l+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},K$=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new ri().parse(a),r=new ki(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Ay={validateData:H$,parseInit:K$,getIndexRange:()=>{},parseSegments:Q$,parseFeedableSegmentChunk:W$,getChunkEndTime:Y$,getServerLatencyTimestamps:z$,getTimescaleFromIndex:G$};var ws=Z(Ze(),1),ai=require("@vkontakte/videoplayer-shared/es2015");var My=require("@vkontakte/videoplayer-shared/es2015");var Ry={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},$y=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Es(a,t),r=i in Ry,s=r?Ry[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,d=Es(u),l=c*Vt(2,(o-1)*8)+d,p=t+o,h;return p+l>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},Es=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*Vt(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*Vt(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*Vt(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},$t=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Es(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,My.assertNever)(e)}},sr=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=$y(i);if(!e(r))return;r.type==="master"&&sr(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Cy=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=$y(a);return sr(r.value,({tag:s,type:n,value:o})=>(s===17143?e=$t(o,n):s===17026?t=$t(o,n):s===17029&&(i=$t(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Dy=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],X$=[231,22612,22743,167,171,163,160,175],J$=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,c,d=!1,l=0;return sr(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=$t(m,h);c=Es(S)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=$t(m,h):p===17545?r=$t(m,h):p===21420&&c===475249515?u=$t(m,h):p===374648427?sr(m,({tag:S,type:v,value:y})=>S===30321?(d=$t(y,v)===1,!1):!0):s&&n&&(0,ws.default)(Dy,p)&&(o=!0),!o}),(0,ai.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,ai.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,ai.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Z$=a=>{if((0,ai.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},eC=(a,e)=>{let t=!1,i=!1,r=o=>(0,ai.isNonNullable)(o.time)&&(0,ai.isNonNullable)(o.position),s=[],n;return sr(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=$t(c,u));break;case 183:break;case 241:n&&(n.position=$t(c,u));break;default:t&&(0,ws.default)(Dy,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:d}=o,l=s[u+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},tC=a=>{let e=0,t=!1;try{sr(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ws.default)(X$,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ws.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Ly={validateData:Cy,parseInit:J$,getIndexRange:Z$,parseSegments:eC,parseFeedableSegmentChunk:tC};var nr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ly;case"mp4":return Ay}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Dl=Z(vt(),1);var By=require("@vkontakte/videoplayer-shared/es2015"),Ai=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Ii(s):void 0)!=null?u:(0,By.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},xs=({id:a,bitrate:e})=>({id:a,bitrate:e}),Vy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),_y=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Ll=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Dl.default)(i.split("."),0),isDefault:r}),Bl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Dl.default)(r.split("."),0)}),Vl=a=>"url"in a,ht=a=>a.type==="template";var Gr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,manifest:o}){this.error$=new C.Subject;this.playingRepresentation$=new C.ValueSubject(void 0);this.playingRepresentationInit$=new C.ValueSubject(void 0);this.currentSegmentLength$=new C.ValueSubject(0);this.onLastSegment$=new C.ValueSubject(!1);this.fullyBuffered$=new C.ValueSubject(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new Ie;this.downloadAbortController=new Ie;this.subscription=new C.Subscription;this.startWith=(0,C.abortable)(this.destroyAbortController.signal,function(e){return he(this,null,function*(){let t=this.representations.get(e);(0,C.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=nr(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,C.assertNonNullable)(i,"No init buffer for starting representation"),(0,C.assertNonNullable)(r,"No segments for starting representation"),yield new _t(this.nativeBufferManager.addInitSegment(i)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)})}.bind(this));this.switchTo=(0,C.abortable)(this.destroyAbortController.signal,function(e,t=!0){return he(this,null,function*(){var l;if((0,C.isNullable)(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);(0,C.assertNonNullable)(r,`No such representation ${e}`),(0,C.assertNonNullable)(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),n=this.segments.get(r.id);(0,C.assertNonNullable)(s,"No init buffer for switching representation"),(0,C.assertNonNullable)(n,"No segments for switching representation");let o=(l=this.getCurrentPosition())!=null?l:0,u=p=>p.segment.networkStatus!=="downloaded"||p.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,c=p=>{let h=this.representations.get(p.representationId);return(0,C.assertNonNullable)(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},d=p=>t?u(p)&&c(p):u(p);this.bufferPlaybackQueue.filter(d).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!d(p)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1})}.bind(this));this.waitExponentialDownloadDelay=(0,C.abortable)(this.downloadAbortController.signal,function(){return he(this,null,function*(){let e=(0,C.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,C.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,C.fromEvent)(i,"online").pipe((0,C.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})})}.bind(this));var u;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=(u=o==null?void 0:o.baseUrls)!=null?u:[],this.representations=new Map(i.map(c=>[c.id,c]))}seek(e){return I(this,null,function*(){yield this.abort(),yield this.clearBuffer(),yield this.maintain(e)})}maintain(){return I(this,arguments,function*(e=this.getCurrentPosition()){(0,C.isNullable)(e)||(yield this.maintainPlaybackBuffer(e),yield this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))})}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return(0,C.isNonNullable)(t)&&(0,C.isNonNullable)(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}abort(){return I(this,null,function*(){this.abortDownload(),yield this.abortNativeBuffer()})}findSegmentStartTime(e){var s,n;let t=(n=(s=this.downloadingRepresentationId)!=null?s:this.playingRepresentationId)!=null?n:"",i=this.segments.get(t),r=i==null?void 0:i.find(o=>o.time.from<=e&&o.time.to>=e);return r==null?void 0:r.time.from}getRepresentationInitialTime(){var t;if((0,C.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return((t=e==null?void 0:e[0].time.from)!=null?t:0)/1e3}calculateDurationFromSegments(){var t;if((0,C.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,Oy.default)(e,-1))==null?void 0:t.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,C.getWindow)();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.__polyfill_cancelIdleCallback_bgan9da8h1hj)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_bgan9da8h1hj(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=Ai(e),s=Ai(t);i=(0,C.isNonNullable)(r)&&(0,C.isNonNullable)(s)&&(0,C.isHigher)(s.quality,r.quality)}else if(this.kind==="audio"){let r=xs(e),s=xs(t);i=(0,C.isNonNullable)(r==null?void 0:r.bitrate)&&(0,C.isNonNullable)(s==null?void 0:s.bitrate)&&s.bitrate>r.bitrate}return i}clearBuffer(){return I(this,null,function*(){this.bufferClearingMutex=!0,yield this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1})}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new Ie,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}abortNativeBuffer(){return I(this,null,function*(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=yield this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i})}loadInits(e){return I(this,null,function*(){yield this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,ir(r=>I(this,null,function*(){return yield this.loadInitIfNeeded(i,"low",!1)})))})}loadInitIfNeeded(e,t="auto",i=!1){return I(this,null,function*(){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():(0,C.isNonNullable)(r)?s=r:s=this.loadInit(e,t,i),yield s})}loadInit(e,t="auto",i=!1){return I(this,null,function*(){var r;try{let s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s);this.initDataPromises.set(e.id,n);let{initMetadata:o,initDataView:u,segments:c}=(r=yield n)!=null?r:{};if(this.initDataPromises.delete(e.id),(0,C.isNullable)(u)||(0,C.isNullable)(c))return;o&&this.parsedInitData.set(e.id,o);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d),this.segments.set(e.id,c),this.failedDownloads=0}catch(s){i&&this.error$.next({id:"LoadInits",category:C.ErrorCategory.WTF,message:"loadInit threw",thrown:s})}})}maintainNativeBuffer(){return I(this,null,function*(){var o;let e=this.getCurrentPosition();if((0,C.isNullable)(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(u=>this.withinInterval(e,u.segment.time)),i=this.bufferPlaybackQueue.find(u=>u.segment.bufferStatus!=="fed"),r=this.initData.get((o=i==null?void 0:i.representationId)!=null?o:""),s=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;(0,C.isNonNullable)(r)&&(0,C.isNonNullable)(i)&&(0,C.isNonNullable)(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(yield this.abortNativeBuffer(),yield this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,C.isNonNullable)(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?yield this.appendSegmentFully(i,n):yield this.appendSegmentPartially(i,n)),(0,C.isNonNullable)(s)&&this.withinRemoveInterval(e,s.segment.time)&&(yield this.removeSegment(s,n)),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1})}maintainPlaybackBuffer(e){return I(this,null,function*(){(0,C.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,C.isNullable)(t)||(0,C.isNullable)(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);(0,C.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),yield this.processCachedItems();let s=this.selectItemsToLoad();yield this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1})}actualizeLastSegmentInfo(e){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if((0,C.isNullable)(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];(0,C.isNullable)(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){(0,C.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;(0,C.isNonNullable)(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&s>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;s-=u-o,r++}return n}processCachedItems(){return I(this,null,function*(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)yield this.onDownloadItem(e[0]),e.shift()})}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return(0,C.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,C.isNonNullable)(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return(0,C.isNonNullable)(e)?e-i>t:!1}appendSegmentFully(e,t){return I(this,null,function*(){if((0,C.isNullable)(e.segment.data))return;e.segment.feedingBytes=e.segment.size,(yield this.nativeBufferManager.append(e.segment.data,t))&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))})}appendSegmentPartially(e,t){return I(this,null,function*(){if((0,C.isNullable)(e.segment.data)||(0,C.isNullable)(e.segment.loadedBytes)||(0,C.isNullable)(e.segment.feedingBytes)||(0,C.isNullable)(e.segment.fedBytes)||(0,C.isNullable)(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s!=null&&s.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,(yield this.nativeBufferManager.append(s,t))&&(e.segment.fedBytes+=s.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))})}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}removeSegment(e,t){return I(this,null,function*(){let{from:i,to:r}=e.segment.time,s=(r-i)/4;(yield this.nativeBufferManager.remove(0,r-s,t))&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())})}onDownloadItem(e){return I(this,null,function*(){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||(0,C.isNonNullable)(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()})}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let s=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)(0,C.isNonNullable)(o.size)&&s>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())(0,C.isNonNullable)(o.size)&&s>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size)}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())this.updateRepresentationBaseUrl(t,e)}};var Wt=require("@vkontakte/videoplayer-shared/es2015");var Ro=class extends Gr{constructor(e,t,i,r){super(e,t,i,r)}loadItems(e,t,i="auto"){return I(this,null,function*(){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let o=this.prepareFetchParams(e,t),{url:s}=o,n=fi(o,["url"]);if(this.failedDownloads&&(yield this.waitExponentialDownloadDelay()),!r.aborted)try{yield this.fetcher.fetch(s,U(M({},n),{priority:i})),this.lastDataObtainedTimestampMs=(0,Wt.now)(),this.failedDownloads=0}catch(u){this.abortDownloadingItems(),Rt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=s);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(Ke(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:(o,u)=>I(this,null,function*(){if(!i.aborted)try{this.lastDataObtainedTimestampMs=(0,Wt.now)(),yield this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Wt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}),signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}onSomeDataLoaded(o){return I(this,arguments,function*({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:s,signal:n}){let u=this.representations.get(i);if(!(!this.downloadingBufferItems.length||(0,Wt.isNullable)(u)||(0,Wt.isNullable)(r)||n.aborted))for(let c of e){let{segment:d}=c,l=d.byte.from-r,p=d.byte.to-r,h=p-l+1,m=l<s,b=p<=s;d.size=h,m&&(d.networkStatus==="downloading"&&d.bufferStatus==="none"&&b?(d.data=new DataView(t.buffer,t.byteOffset+l,h),this.currentVirtualBufferSize+=d.size,this.onItemFullyDownloaded(c),d.loadedBytes=Math.min(h,s-l),yield this.onDownloadItem(c)):(0,Wt.isNonNullable)(d.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&d.networkStatus==="downloading"&&(d.loadedBytes=Math.min(h,s-l),b&&(this.currentVirtualBufferSize+=d.size,this.onItemFullyDownloaded(c)),d.loadedBytes>d.feedingBytes&&(d.data=new DataView(t.buffer,t.byteOffset+l,d.loadedBytes),yield this.onDownloadItem(c))))}})}updateRepresentationBaseUrl(e,t){if(Ke(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var si=require("@vkontakte/videoplayer-shared/es2015");var Yr=class extends Gr{constructor(e,t,i,r){super(e,t,i,r)}loadItems(e,t,i="auto"){return I(this,null,function*(){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let o=this.prepareFetchParams(e,t),{url:s}=o,n=fi(o,["url"]);if(this.failedDownloads&&(yield this.waitExponentialDownloadDelay()),!r.aborted)try{let u=yield this.fetcher.fetch(s,U(M({},n),{priority:i}));if(this.lastDataObtainedTimestampMs=(0,si.now)(),(0,si.isNullable)(u))return;let c=e[0],d=new DataView(u);c.segment.size=d.byteLength,c.segment.loadedBytes=d.byteLength,c.segment.data=d,this.onItemFullyDownloaded(c),yield this.onDownloadItem(c),this.failedDownloads=0}catch(u){this.abortDownloadingItems(),Rt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:(n,o)=>I(this,null,function*(){if(!r.aborted)try{this.lastDataObtainedTimestampMs=(0,si.now)(),yield this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:si.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}),signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Ke(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}onSomeDataLoaded(n){return I(this,arguments,function*({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:s}){let o=e[0],{segment:u}=o,c=this.representations.get(i);!this.downloadingBufferItems.length||(0,si.isNullable)(c)||(0,si.isNullable)(u.feedingBytes)||u.networkStatus!=="downloading"||s.aborted||(u.loadedBytes=r,u.loadedBytes>u.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(u.data=new DataView(t.buffer,t.byteOffset,u.loadedBytes),yield this.onDownloadItem(o)))})}updateRepresentationBaseUrl(e,t){if(!Ke(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var _l=Z(Ga(),1),Ny=Z(vt(),1);var Oe=require("@vkontakte/videoplayer-shared/es2015");var Mo=class a extends Yr{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new Oe.ValueSubject(0);this.currentLowLatencySegmentLength$=new Oe.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){var r,s,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,_l.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if((0,Oe.isNullable)(o)||!Ke(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>U(M({},h),{networkStatus:"none",bufferStatus:"none",size:void 0})),c=100,d=(r=this.segments.get(o.id))!=null?r:[],l=(n=(s=(0,Ny.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>l>=h.time.from+c&&l<=h.time.to+c);if(p===-1){let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...d,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Oe.assertNonNullable)(t);let i=this.segments.get(t);if(i!=null&&i.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t==null?void 0:t.streams[this.kind],r=(0,_l.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Oe.isNullable)(r))return;let s=this.segments.get(r.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){var r;if((0,Oe.isNullable)(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return(0,Oe.isNullable)(t)||!Ke(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return U(M({},super.prepareFetchParams(t,i)),{isLowLatency:this.isActiveLowLatency()})}onSomeDataLoaded(r){return I(this,null,function*(){var s=r,{downloadingItems:t}=s,i=fi(s,["downloadingItems"]);yield jd(a.prototype,this,"onSomeDataLoaded").call(this,M({downloadingItems:t},i)),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])})}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),(0,Oe.isNullable)(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);s&&n&&this.currentLiveSegmentServerLatency$.next(n-s),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){var n;let i=t.segment.data,r=(n=this.representations.get(t.representationId))==null?void 0:n.segmentReference;if((0,Oe.isNullable)(t.segment.data)||(0,Oe.isNullable)(r)||!Ke(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=s.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let s of this.representations.values()){let n=s.segmentReference;if(!Ke(n))return;let o=(r=this.segments.get(s.id))!=null?r:[],u=o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.from));if(u!=null&&u.isCurrentLowLatency&&(u.time.to=t.segment.time.to,i=u.time.to-u.time.from,u.isCurrentLowLatency=!1),!!!o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let d=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),l=Mt(n.segmentTemplateUrl,{segmentTime:d});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:l,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}loadInit(t,i="auto",r=!1){return I(this,null,function*(){var s;try{let n=this.tuning.dash.useFetchPriorityHints?i:"auto",o=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,n);this.initDataPromises.set(t.id,o);let{initMetadata:u,initDataView:c,segments:d}=(s=yield o)!=null?s:{};if(this.initDataPromises.delete(t.id),(0,Oe.isNullable)(c)||(0,Oe.isNullable)(d))return;u&&this.parsedInitData.set(t.id,u);let l=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,l);let p=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(t.id,p),this.failedDownloads=0}catch(n){r&&this.error$.next({id:"LoadInits",category:Oe.ErrorCategory.WTF,message:"loadInit threw",thrown:n})}})}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[],n=0,o=i.length-1;do s.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[s[0]]:s}};var Ps=class{static getBufferManager(e,t,i,r){var s;return(s=r.manifest)!=null&&s.live?new Mo(e,t,i,r):Ke(i[0].segmentReference)?new Yr(e,t,i,r):new Ro(e,t,i,r)}};var Xe=require("@vkontakte/videoplayer-shared/es2015");var Ri=require("@vkontakte/videoplayer-shared/es2015");var iC=18,Fy=!1;try{Fy=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=iC}catch(a){console.error(a)}var Ol=class{constructor(e,t=!1){this.bufferFull$=new Ri.Subject;this.error$=new Ri.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Ri.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return I(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return I(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return I(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Fy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ri.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Ri.assertNever)(t)}}},qy=Ol;var Mi=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var ks=class{constructor(e){this.error$=new Xe.Subject;this.subscription=new Xe.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new qy(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,Xe.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Xe.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}clear(e){return I(this,null,function*(){let t=this.getBufferState();if((0,Xe.isNullable)(t))return Promise.resolve(!1);let i=!0;yield this.sourceBufferTaskQueue.abort();for(let r of t)i&&(i=yield this.sourceBufferTaskQueue.remove(r.from,r.to,e));return i})}warmUpMediaSource(){!(0,Xe.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,Xe.isNullable)(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return(0,Xe.isNullable)(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,Xe.isNullable)(e)?0:Mi(this.sourceBuffer.buffered,e)}abortBuffer(e){return I(this,null,function*(){return(0,Xe.isNullable)(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)})}destroy(){var e;if(this.subscription.unsubscribe(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null}};var $o=(a,e)=>{a.video.forEach(t=>{let i=t.representations.filter(({fps:r,height:s})=>{var o;let n=(o=e.find(([u])=>u===`${s}p`))==null?void 0:o[1];return n&&Number.isInteger(n)&&r&&Number.isInteger(r)?r<=n:!0});t.representations=i})};var rC=["timeupdate","progress","play","seeked","stalled","waiting"],Uy=["timeupdate","progress","loadeddata","playing","seeked"],Co=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new E.Subscription;this.subscriptionRemovable=new E.SubscriptionRemovable;this.representationSubscription=new E.Subscription;this.forceEnded$=new E.Subject;this.destroyController=new Ie;this.state$=new ne("none");this.currentVideoRepresentation$=new E.ValueSubject(void 0);this.currentVideoRepresentationInit$=new E.ValueSubject(void 0);this.currentAudioRepresentation$=new E.ValueSubject(void 0);this.currentVideoSegmentLength$=new E.ValueSubject(0);this.currentAudioSegmentLength$=new E.ValueSubject(0);this.error$=new E.Subject;this.manifestRequested=new E.Subject;this.manifestReceived=new E.Subject;this.firstBytesRequested=new E.Subject;this.firstBytesReceived=new E.Subject;this.lastConnectionType$=new E.ValueSubject(void 0);this.lastConnectionReused$=new E.ValueSubject(void 0);this.lastRequestFirstBytes$=new E.ValueSubject(void 0);this.lastConnectionMetrics$=new E.ValueSubject(void 0);this.lastDownloadMetrics$=new E.ValueSubject(void 0);this.currentLiveTextRepresentation$=new E.ValueSubject(null);this.isLive$=new E.ValueSubject(!1);this.isActiveLive$=new E.ValueSubject(!1);this.isLowLatency$=new E.ValueSubject(!1);this.liveDuration$=new E.ValueSubject(0);this.liveSeekableDuration$=new E.ValueSubject(0);this.liveAvailabilityStartTime$=new E.ValueSubject(0);this.liveStreamStatus$=new E.ValueSubject(void 0);this.currentBuffer$=new E.ValueSubject({from:0,to:0});this.bufferLength$=new E.ValueSubject(0);this.nativeBufferLength$=new E.ValueSubject(0);this.liveLatency$=new E.ValueSubject(void 0);this.liveLoadBufferLength$=new E.ValueSubject(0);this.livePositionFromPlayer$=new E.ValueSubject(0);this.currentStallDuration$=new E.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new E.ValueSubject(0);this.fetcherRecoverableError$=new E.Subject;this.fetcherError$=new E.Subject;this.initRepresentations=(0,E.abortable)(this.destroyController.signal,function(e,t,i){return he(this,null,function*(){var s;this.tracer.log("initRepresentationsStart",(0,E.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),(0,E.assertNonNullable)(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?(s=this.audioBufferManager)==null?void 0:s.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.fetchManifest=(0,E.abortable)(this.destroyController.signal,function(){return he(this,null,function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){(0,E.isNullable)(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:E.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:e})}})}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new So({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}initManifest(e,t,i){return I(this,null,function*(){var r;this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:E.ErrorCategory.PARSER,message:"No playable video representations"})})}initBuffer(){var t,i;(0,E.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,E.merge)(...rC.map(r=>(0,E.fromEvent)(this.element,r)),(0,E.fromEvent)((0,E.getWindow)(),"online")).subscribe(()=>this.tick(),r=>this.error$.next({id:"DashVKPlayer",category:E.ErrorCategory.WTF,message:"Internal logic error",thrown:r})));let e=[...(i=(t=this.source)==null?void 0:t.activeSourceBuffers)!=null?i:[]];this.subscription.add((0,E.merge)(...e.map(r=>(0,E.fromEvent)(r,"updateend"))).subscribe(r=>this.reinitDecoderIfNeeded())),this.subscription.add((0,E.fromEvent)(this.element,"waiting").subscribe(r=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,E.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),s=>this.error$.next({id:"StallWatchdogCallback",category:E.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:s})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}switchRepresentation(e,t,i=!1){return I(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)})}seek(e,t=!1){return I(this,null,function*(){var r,s,n,o;(0,E.assertNonNullable)(this.element),(0,E.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,yield this.videoBufferManager.seek(i),yield(o=this.audioBufferManager)==null?void 0:o.seek(i),this.tracer.log("seek",(0,E.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){(0,E.isNonNullable)(this.element)&&(0,E.isNonNullable)(this.source)&&(0,E.isNonNullable)(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(i=>i.warmUpMediaSource())}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(r=>r.destroy()),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&(0,E.getWindow)().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),(0,E.isNonNullable)(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){var e;return((e=this.source)==null?void 0:e.readyState)!=="open"}reinitDecoderIfNeeded(e=!1){return I(this,null,function*(){var r,s;let t=(s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[];if((0,E.isNullable)(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(n=>i>=n.from&&i<=n.to)&&(e?yield this.seek(i):this.element.currentTime=this.element.currentTime)})}stallWatchdogIntervalCallback(){return I(this,null,function*(){(0,E.assertNonNullable)(this.element),(0,E.assertNonNullable)(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(yield this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);yield this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",(0,E.flattenObject)(i))})}isStallExceeded(e){var p,h,m,b,S,v,y,x;let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=(0,E.now)(),s=100,n=(h=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?h:0;this.videoLastDataObtainedTimestamp$.next(n);let o=(b=(m=this.audioBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0,u=(v=(S=this.videoBufferManager)==null?void 0:S.getForwardPlaybackBufferDuration())!=null?v:0,c=(x=(y=this.audioBufferManager)==null?void 0:y.getForwardPlaybackBufferDuration())!=null?x:0,d=(0,E.isNonNullable)(this.videoBufferManager)&&u<s&&r-n>i,l=(0,E.isNonNullable)(this.audioBufferManager)&&c<s&&r-o>i;return(d||l)&&e>i||e>=t}updateManifest(){return I(this,null,function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetchManifest();if((0,E.isNullable)(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",(0,E.flattenObject)(i)),i})}parseManifest(e){var t;try{return Io(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=mo(e))!=null?t:{id:"ManifestParsing",category:E.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:i};this.error$.next(r)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,c)=>{var d,l,p,h;return!!((l=(d=this.element)==null?void 0:d.canPlayType)!=null&&l.call(d,u)&&((h=(p=lt())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${c}"`))||o==="text")},r,s;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));t[o]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);o==="audio"&&(s=ko(l),d=s[0]),o==="video"&&(r=Po(l),this.forceVideoCodec&&(0,jy.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=c.filter(({codecs:p})=>Wr(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=xo(l),d&&(t[o]=c.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=t.video.some(b=>b.hdr),h=t.video.some(b=>!b.hdr);G.display.isHDR&&l&&p?t.video=t.video.filter(b=>b.hdr):h&&(t.video=t.video.filter(b=>!b.hdr));let{videoStreamRepresentaionsFilter:m}=this.tuning.dash;m.length&&$o(t,m)}}let n=U(M({},e),{streams:t});return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:s}),n}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){(0,E.assertNonNullable)(this.manifest),(0,E.assertNonNullable)(this.element);let s=c=>{this.representationSubscription.add((0,E.fromEvent)(c,"error").pipe((0,E.filter)(d=>{var l;return!!((l=this.element)!=null&&l.played.length)})).subscribe(d=>{this.error$.next({id:"VideoSource",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Sn();let n=(0,E.getWindow)().document,o=n.createElement("source");if(s(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),kr())if(r){let c=n.createElement("source");s(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new ks(this.source),this.videoBufferManager=Ps.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,E.isNonNullable)(i)){this.audioNativeBufferManager=new ks(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=Ps.getBufferManager("audio",this.audioNativeBufferManager,c,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}waitStreamToOpen(){return I(this,null,function*(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(t=>{var i;e&&(this.timeoutSourceOpenId=(0,E.getWindow)().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(i=this.source)==null||i.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&(0,E.getWindow)().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}})}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add((0,E.merge)(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),(0,E.assertNonNullable)(this.videoBufferManager),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add((0,E.merge)(...Uy.map(e=>(0,E.fromEvent)(this.element,e))).pipe((0,E.map)(e=>{var t;return(t=this.videoBufferManager)==null?void 0:t.getPlaybackBufferState()}),(0,E.filter)(E.isNonNullable),(0,E.map)(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add((0,E.merge)(...Uy.map(e=>(0,E.fromEvent)(this.element,e))).pipe((0,E.map)(e=>{var t,i,r,s;return Math.max((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(s=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?s:0)}),(0,E.filterChanged)()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe((0,E.filter)(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=(0,E.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}tick(){return I(this,null,function*(){var r,s,n;if((0,E.isNullable)(this.element)||(0,E.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[]).find(o=>e>=o.from&&e<=o.to);this.nativeBufferLength$.next(i?i.to-e:0),yield this.videoBufferManager.maintain(e),yield(n=this.audioBufferManager)==null?void 0:n.maintain(e)})}};var ge=require("@vkontakte/videoplayer-shared/es2015");var Do=class extends Co{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;(0,ge.assertNonNullable)(this.manifest),(0,ge.assertNonNullable)(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,Nl.default)((0,Nl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),Ke(i.segmentReference)&&i.segmentReference.totalSegmentsDurationMs&&r.push(i.segmentReference.totalSegmentsDurationMs),r})];this.source.duration=Math.max(...e)/1e3}restoreAfterDeepStall(e){return I(this,null,function*(){var i,r;(0,ge.assertNonNullable)(this.element);let t=this.element.currentTime*1e3;yield Promise.all([(i=this.videoBufferManager)==null?void 0:i.maintain(t),(r=this.audioBufferManager)==null?void 0:r.maintain(t)]),e.position=t})}initDisableStallWatchdogSubscription(){(0,ge.assertNonNullable)(this.element);let e=(0,ge.merge)((0,ge.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,ge.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,ge.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,ge.merge)(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe((0,ge.map)(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=(0,ge.merge)(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe((0,ge.map)(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=(0,ge.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,ge.filterChanged)(),(0,ge.map)(({allBuffersFull:s,someBufferEnded:n})=>s&&n),(0,ge.filter)(s=>s)),r=()=>{var s;try{(s=this.source)==null||s.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:ge.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add((0,ge.merge)(this.forceEnded$,i).pipe((0,ge.filter)(s=>(0,ge.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var Kr=class extends za{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,Hy.filterChanged)()).subscribe(s=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:l}])=>l.id===s);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,c=this.params.desiredState.videoStream.getTransition();c&&c.to&&c.to.id===u.id&&this.params.desiredState.videoStream.setState(c.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(no(u));let d=this.player.calculateDurationFromSegments();d&&this.params.output.duration$.next(d/1e3)},r))}getPlayer(){return new Do({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Y=require("@vkontakte/videoplayer-shared/es2015");var Gy=Z(Ze(),1),jl=Z(Ga(),1);var $i=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var T=require("@vkontakte/videoplayer-shared/es2015");var Lo=Z(Ze(),1),or=Z(vt(),1),Bo=Z(Ga(),1);var zy=Z(Yc(),1);var Ci=require("@vkontakte/videoplayer-shared/es2015");var aC=18,Qy=!1;try{Qy=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=aC}catch(a){console.error(a)}var Fl=class{constructor(e,t=!1){this.bufferFull$=new Ci.Subject;this.error$=new Ci.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Ci.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return I(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return I(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return I(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Qy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ci.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Ci.assertNever)(t)}}},Wy=Fl;var ql=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var A=require("@vkontakte/videoplayer-shared/es2015");var As=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new A.ValueSubject(0);this.currentLowLatencySegmentLength$=new A.ValueSubject(0);this.currentSegmentLength$=new A.ValueSubject(0);this.onLastSegment$=new A.ValueSubject(!1);this.fullyBuffered$=new A.ValueSubject(!1);this.playingRepresentation$=new A.ValueSubject(void 0);this.playingRepresentationInit$=new A.ValueSubject(void 0);this.error$=new A.Subject;this.gaps=[];this.subscription=new A.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ie;this.switchAbortController=new Ie;this.destroyAbortController=new Ie;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,A.abortable)(this.destroyAbortController.signal,function(e){return he(this,null,function*(){let t=this.representations.get(e);(0,A.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Wy(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:A.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Te(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ql(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<d).catch(l=>{this.handleAsyncError(l,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,A.assertNonNullable)(i,"No init buffer for starting representation"),(0,A.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,A.abortable)(this.destroyAbortController.signal,function(e,t=!1){return he(this,null,function*(){if(!Te(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,A.isNullable)(s)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new _t(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,A.abortable)(this.destroyAbortController.signal,function(e,t=!1){return he(this,null,function*(){if(!Te(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,A.isNullable)(s)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new _t(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,A.abortable)(this.destroyAbortController.signal,function(e){return he(this,null,function*(){var u;let t=(0,Bo.default)(e,c=>c.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let l=this.representations.get(c);if(!l||!ht(l.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,p)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);(0,A.assertNonNullable)(r,`Representation not found by id ${i}`);let s=this.segments.get(i);(0,A.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,A.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.live),this.baseUrls=(d=c==null?void 0:c.baseUrls)!=null?d:[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Te(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ie,(0,A.abortable)(this.switchAbortController.signal,function(i,r=!1){return he(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,A.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,A.isNullable)(o)||(0,A.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,A.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,A.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!(0,A.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return I(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ie,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){var p;if((0,A.isNullable)(e)||(0,A.isNullable)(this.downloadingRepresentationId)||(0,A.isNullable)(this.playingRepresentationId)||(0,A.isNullable)(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||(0,A.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if((0,A.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,A.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,A.isNullable)(r)||(0,A.isNullable)(s))return;let n=r.find(h=>e>=h.time.from&&e<h.time.to);(0,A.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=this.getForwardBufferDuration(e),m=Ai(i),b=Ai(t),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,A.isNonNullable)(m)&&(0,A.isNonNullable)(b)&&(0,A.isHigher)(m.quality,b.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(S||v?o+=Math.min(h,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let x=(p=[...this.segments.entries()].map(([P,D])=>{let V=D.find(Q=>e>=Q.time.from&&e<Q.time.to);return{representationId:P,status:V==null?void 0:V.status}}).find(P=>P.status==="fed"))==null?void 0:p.representationId;x&&(this.playingRepresentationId=x,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ql(this.sourceBuffer.buffered)>=this.bufferLimit){let h=this.getForwardBufferDuration(e),m=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<m).catch(b=>{this.handleAsyncError(b,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Lo.default)(d,n))h="high";else{let m=(0,or.default)(d,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(d,t,h).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,or.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;(0,A.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,Bo.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,s;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,Bo.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!ht(n.segmentReference))return;let o=n.segmentReference.segments.map(p=>U(M({},p),{status:"none",size:void 0})),u=100,c=(i=this.segments.get(n.id))!=null?i:[],d=(s=(r=(0,or.default)(c,-1))==null?void 0:r.time.to)!=null?s:0,l=o==null?void 0:o.findIndex(p=>d>=p.time.from+u&&d<=p.time.to+u);if(l===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(l+1);this.segments.set(n.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,A.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,or.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!ht(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let c=Math.round(e.time.to*s.timescale/1e3).toString(10),d=Mt(s.segmentTemplateUrl,{segmentTime:c});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&rr&&rr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&rr&&rr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:p,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+y||r<y&&m-h>=y||m<=i+y;return(p==="none"||p==="partially_ejected"&&v&&x&&this.sourceBuffer&&Te(this.mediaSource,this.sourceBuffer)&&!($i(this.sourceBuffer.buffered,h)&&$i(this.sourceBuffer.buffered,m)))&&v&&x});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=d||u<=l);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")c.push(h);else break}return c}loadSegments(e,t,i="auto"){return I(this,null,function*(){ht(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return I(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,A.abortable)(o,function(){return he(this,null,function*(){let d=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,A.now)(),!d)return;let l=new DataView(d),p=nr(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,b)}u&&r.feedingBytes&&c?yield Promise.all(c):yield this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(l);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Rt(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ht(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return I(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,A.abortable)(n,function(){return he(this,null,function*(){let u=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,A.fromEvent)(window,"online").pipe((0,A.once)()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,A.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Rt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ht(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,or.default)(e,0).byte.from,to:(0,or.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>I(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}})}}prepareTemplateFetchSegmentParams(e,t){if(!ht(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Lo.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return I(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!Te(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),l=nr(o.mime).parseFeedableSegmentChunk(d,this.isLive);l!=null&&l.byteLength&&(c.status="partially_fed",u.feedingBytes+=l.byteLength,yield this.sourceBufferTaskQueue.append(l),u.fedBytes+=l.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return I(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Te(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let c of this.activeSegments){let{segment:d}=c;if(c.representationId!==t)continue;if(s.aborted){yield n();continue}let l=d.byte.from-i,p=d.byte.to-i,h=p-l+1,m=l<r,b=p<=r;if(!m)continue;let S=nr(u.mime);if(d.status==="downloading"&&b){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+l,h);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(c,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(c.loadedBytes=Math.min(h,r-l),c.loadedBytes>c.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+l+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===h?v:S.parseFeedableSegmentChunk(v);y!=null&&y.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,(yield this.sourceBufferTaskQueue.append(y,s))&&!s.aborted?(c.fedBytes+=y.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!((0,A.isNullable)(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer))){!this.isLive&&G.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&($i(this.sourceBuffer.buffered,e.segment.time.from,100)&&$i(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Vl(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=ir(()=>(0,zy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return I(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?(0,A.abortable)(this.destroyAbortController.signal,function(){return he(this,null,function*(){let u=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,nr(e.mime),{priority:r,ignoreNetworkErrors:s})).then(u=>I(this,null,function*(){if(!u)return;let{init:c,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=l;this.isLive&&ht(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),c&&this.parsedInitData.set(e.id,c)})).then(()=>this.failedDownloads=0,u=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:A.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o})}dropBuffer(){return I(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return I(this,null,function*(){if(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,A.isNullable)(e))return!1;let r=[],s=0,n=u=>{u.sort((d,l)=>d.from-l.from);let c=[u[0]];for(let d=1;d<u.length;d++){let{from:l,to:p}=u[d],h=c[c.length-1];h.to>=l?h.to=Math.max(h.to,p):c.push(u[d])}return c},o=u=>{var d;if(s>=t)return r;r.push(M({},u.time)),r=n(r);let c=Vl(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let d=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let p of this.segments.values())for(let h of p)(0,Lo.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:c,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(yield Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,d)=>c||d,!1):!1})}abortBuffer(){return I(this,null,function*(){if(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,A.isNullable)(e)?0:Mi(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let o=s.start(n)*1e3,u=s.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=ir(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:A.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,A.isNullable)(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||(0,A.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),c=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:A.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var H=require("@vkontakte/videoplayer-shared/es2015");var _o=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new H.Subject;this.firstBytesManifest$=new H.Subject;this.firstBytesRequested$=new H.Subject;this.firstBytesReceived$=new H.Subject;this.lastConnectionType$=new H.ValueSubject(void 0);this.lastConnectionReused$=new H.ValueSubject(void 0);this.lastRequestFirstBytes$=new H.ValueSubject(void 0);this.lastConnectionMetrics$=new H.ValueSubject(void 0);this.lastDownloadMetrics$=new H.ValueSubject(void 0);this.recoverableError$=new H.Subject;this.error$=new H.Subject;this.abortAllController=new Ie;this.subscription=new H.SubscriptionRemovable;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,H.abortable)(this.abortAllController.signal,function(e){return he(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Pi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=go(i)),this.trackRequestStart(i,performance.now());let r=(0,H.now)();this.manifestRequested$.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Vo);if(s){let n=(0,H.now)();t.log("success",(0,H.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(s.headers),this.firstBytesManifest$.next();let o=s.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=yield new _t(s.text());if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",(0,H.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null})}.bind(this));this.fetch=(0,H.abortable)(this.abortAllController.signal,function(l){return he(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:d=!1}={}){var ce,N,O;let p=e,h=new Headers,m=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let k=new URL(p,(0,H.getWindow)().location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),p=k.toString();break}default:(0,H.assertNever)(t)}this.requestQuic&&(p=Pi(p));let b=this.abortAllController.signal,S;if(n){let k=new Ie;if(S=(0,H.merge)((0,H.fromEvent)(this.abortAllController.signal,"abort"),(0,H.fromEvent)(n,"abort")).subscribe(()=>{try{k.abort()}catch(R){Vo(R)}}),this.subscription.add(S),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(R){Vo(R)}b=k.signal}let v=0,y=(0,H.now)();m.log("startRequest",(0,H.flattenObject)({url:p,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:y})),this.trackRequestStart(p,performance.now()),this.firstBytesRequested$.next();let x=yield this.doFetch(p,{priority:s,headers:h,signal:b},{ignoreNetworkErrors:d}),P=(0,H.now)();if(!x)return m.error("error",{message:"No response in request"}),m.end(),this.unsubscribeAbortSubscription(S),null;if((ce=this.throughputEstimator)==null||ce.addRawRtt(P-y),!x.ok||!x.body){this.unsubscribeAbortSubscription(S);let k=`Fetch error ${x.status}: ${x.statusText}`;return m.error("error",{message:k}),m.end(),Promise.reject(new Error(`Fetch error ${x.status}: ${x.statusText}`))}if(this.onHeadersReceived(x.headers),!r&&!o){this.unsubscribeAbortSubscription(S);let k=(0,H.now)(),R={requestStartedAt:y,requestEndedAt:k,duration:k-y};return m.log("endRequest",(0,H.flattenObject)(R)),m.end(),x.arrayBuffer()}let D=x.body;if(o){let k;[D,k]=x.body.tee(),(N=this.throughputEstimator)==null||N.trackStream(k,u)}let V=D.getReader(),Q,W=parseInt((O=x.headers.get("content-length"))!=null?O:"",10);Number.isFinite(W)&&(Q=W),!Q&&i&&(Q=i.to-i.from+1);let F=Q?new Uint8Array(Q):new Uint8Array(0),_=!1,K=k=>{this.unsubscribeAbortSubscription(S),_=!0,Vo(k)},q=(0,H.abortable)(b,function(X){return he(this,arguments,function*({done:k,value:R}){if(v===0&&(this.lastRequestFirstBytes$.next((0,H.now)()-y),this.firstBytesReceived$.next()),b.aborted){this.unsubscribeAbortSubscription(S);return}if(!k&&R){if(c&&Q)F.set(R,v),v+=R.byteLength;else{let z=new Uint8Array(F.length+R.length);z.set(F),z.set(R,F.length),F=z,v+=R.byteLength}r==null||r(new DataView(F.buffer),v),yield V==null?void 0:V.read().then(q,K)}})}.bind(this));yield V==null?void 0:V.read().then(q,K),this.unsubscribeAbortSubscription(S);let ee=(0,H.now)(),pe={failed:_,requestStartedAt:y,requestEndedAt:ee,duration:ee-y};if(_)return m.error("endRequest",(0,H.flattenObject)(pe)),m.end(),null;if(v>0){let k=ee-y,X=v/(k/1e3)*8/1024,z={bytes:v,speed:X,url:e};this.lastDownloadMetrics$.next(z)}return m.log("endRequest",(0,H.flattenObject)(pe)),m.end(),F.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,H.abortable)(this.abortAllController.signal,function(e,t,i){return he(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,M({range:{from:n,to:o},measureThroughput:!1},i));if(!l)return null;let p=new DataView(l,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(l,m.from-n,m.to-m.from+1);else{let y=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(l),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,H.abortable)(this.abortAllController.signal,function(e,t){return he(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,M({measureThroughput:!1},t));return r?{init:null,segments:e.segments.map(n=>U(M({},n),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s,(0,H.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=bo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,H.getWindow)()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processPerformanceResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in(0,H.getWindow)().navigator))return"unknown";let e=(0,H.getWindow)().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(s===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch(t){this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:H.ErrorCategory.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}fetchRepresentation(e,t,i){return I(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,H.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}doFetch(e,t,i){return I(this,null,function*(){let r=yield yt(e,t);if(r.ok)return r;if(i!=null&&i.ignoreNetworkErrors)return;let s=yield r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:H.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:H.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:H.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:H.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:H.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Vo=a=>{if(!Rt(a))throw a};var Rs=require("@vkontakte/videoplayer-shared/es2015");var Di=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Rs.ValueSubject(e.initial),this.debounced$=new Rs.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ge(`raw_${t}`),this.smoothedSeries$=new Ge(`smoothed_${t}`),this.reportedSeries$=new Ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Vt(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,Rs.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Oo=class extends Di{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ii(this.slow,e,this.params.emaAlphaSlow),this.fast=ii(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var No=class extends Di{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=hl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ii(this.emaSmoothed,e,this.params.emaAlpha);let i=Nv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Fo=class extends Di{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?ii(this.smoothed,t,this.params.emaAlpha):t}};var ur=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Oo({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new No({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Fo(M({initial:e,label:"liveEdgeDelay"},t))}};var Ul=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var qo=require("@vkontakte/videoplayer-shared/es2015");var Ms=class a{constructor(e,t){this.currentRepresentation$=new qo.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,qo.isNullable)(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let c=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next(U(M({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ht(t.segmentReference))}};var oC=["timeupdate","progress","play","seeked","stalled","waiting"],uC=["timeupdate","progress","loadeddata","playing","seeked"];var Uo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;this.subscriptionRemovable=new T.SubscriptionRemovable;this.representationSubscription=new T.Subscription;this.state$=new ne("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested$=new T.Subject;this.firstBytesManifest$=new T.Subject;this.manifestReceived$=new T.Subject;this.firstBytesRequested$=new T.Subject;this.firstBytesReceived$=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.lastConnectionMetrics$=new T.ValueSubject(void 0);this.lastDownloadMetrics$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new Ie;this.initManifest=(0,T.abortable)(this.destroyController.signal,function(e,t,i){return he(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=He(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,function(){return he(this,null,function*(){var u,c;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=Io(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(d){let l=(u=mo(e))!=null?u:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(l)}if(!t)return null;let i=(d,l,p)=>{var h,m,b,S;return!!((m=(h=this.element)==null?void 0:h.canPlayType)!=null&&m.call(h,l)&&((S=(b=lt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${l}; codecs="${p}"`))||d==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:d,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:h}=t.live,m=((c=t.duration)!=null?c:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((l-d)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let b="active";if(h||(b=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(b),h&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let S=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(S).catch(v=>{this.error$.next({id:"updateManifest",category:T.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:v})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let d of["video","audio"]){let p=t.streams[d].filter(({mime:m,codecs:b})=>i(d,m,b));r[d]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let m=p.map(({codecs:b})=>b);d==="audio"&&(n=ko(m),h=n[0]),d==="video"&&(s=Po(m),this.forceVideoCodec&&(0,Gy.default)(s,this.forceVideoCodec)?h=this.forceVideoCodec:h=s[0]),h&&(r[d]=p.filter(({codecs:b})=>Wr(b)===h))}else{let m=new Set(p.map(({codecs:b})=>b));h=xo(m),h&&(r[d]=p.filter(({codecs:b})=>b.startsWith(h)))}if(d==="video"){let m=this.tuning.preferHDR,b=r.video.some(y=>y.hdr),S=r.video.some(y=>!y.hdr);G.display.isHDR&&m&&b?r.video=r.video.filter(y=>y.hdr):S&&(r.video=r.video.filter(y=>!y.hdr));let{videoStreamRepresentaionsFilter:v}=this.tuning.dash;v.length&&$o(r,v)}}let o=U(M({},t),{streams:r});return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,T.flattenObject)(o)),o})}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,function(e,t,i){return he(this,null,function*(){var l;this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,T.fromEvent)(p,"error").pipe((0,T.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Sn();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),kr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new As("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new As("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(Ms.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ms(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.merge)(...uC.map(p=>(0,T.fromEvent)(this.element,p))).pipe((0,T.map)(p=>this.element?Mi(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:h}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,T.interval)(h).subscribe(m=>{let b=pn(this.manifestUrlString,2);this.manifestUrlString=He(this.manifestUrlString,b+h,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,T.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Ul(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:h})=>h),(0,T.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,T.map)(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=pn(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let P=1;Math.abs(x)>v&&(P=1+Math.sign(x)*y),Ul(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let v=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(x=>{var P,D;return(D=(P=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:P.to)!=null?D:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(b=>I(this,[b],function*({liveLoadBufferLength:h,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=pn(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),P=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,D=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,V=isFinite(h)?h:m,Q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),W=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(W);let F="none";if(Q?F="active_low_latency":this.isLowLatency$.getValue()&&W?(this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),F="active_low_latency"):v!==0&&V<x?F="live_forward_buffering":V<x+D&&(F="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),F==="live_forward_buffering"||F==="live_with_target_offset"){let _=p-(x+P),K=this.normalizeLiveOffset(Math.trunc(v+_/S)),q=Math.abs(K-v),ee=0;!h||q<=this.tuning.dashCmafLive.offsetCalculationError?ee=v:K>0&&q>this.tuning.dashCmafLive.offsetCalculationError&&(ee=K),this.manifestUrlString=He(this.manifestUrlString,ee,2)}(F==="live_with_target_offset"||F==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let u=(0,T.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,T.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=(0,T.combine)({allBuffersFull:u,someBufferEnded:c}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,T.filter)(p=>p));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(l=this.manifest.duration)!=null?l:0,...(0,jl.default)((0,jl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),ht(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new _o({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=ur.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,M({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}seekLive(e){return I(this,null,function*(){(0,T.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield this.updateLiveBuffersFromManifest(this.manifest))})}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=He(this.manifestUrlString,i,2)}updateLiveBuffersFromManifest(e){return I(this,null,function*(){var t,i,r;yield(t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)})}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...oC.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&$i(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var P,D,V,Q,W,F,_,K,q,ee,pe;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||((P=this.source)==null?void 0:P.readyState)!=="open")return;let d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=(0,T.now)(),h=100,m=(V=(D=this.videoBufferManager)==null?void 0:D.lastDataObtainedTimestamp)!=null?V:0;this.videoLastDataObtainedTimestamp$.next(m);let b=(W=(Q=this.audioBufferManager)==null?void 0:Q.lastDataObtainedTimestamp)!=null?W:0,S=(_=(F=this.videoBufferManager)==null?void 0:F.getForwardBufferDuration())!=null?_:0,v=(q=(K=this.audioBufferManager)==null?void 0:K.getForwardBufferDuration())!=null?q:0,y=S<h&&p-m>r,x=this.audioBufferManager&&v<h&&p-b>r;if((!t||c)&&((y||x)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%s===0){let ce=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(ce),this.updateManifest()):this.seekLive(ce).catch(N=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:N})}),l.liveLastOffset=ce}else{let ce=this.element.currentTime*1e3;(ee=this.videoBufferManager)==null||ee.maintain(ce),(pe=this.audioBufferManager)==null||pe.maintain(ce),l.position=ce}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return I(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return I(this,null,function*(){var r,s,n,o,u;(0,T.assertNonNullable)(this.element),(0,T.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),$i(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return I(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let c of u.gaps)(r&&c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=s&&c.to+o>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?n.push(1/0):n.push(c.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i=U(M({},i),{gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,T.flattenObject)(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var nt=require("@vkontakte/videoplayer-shared/es2015"),jo=class{constructor(){this.subscription=new nt.Subscription;this.pipSize$=new nt.ValueSubject(void 0);this.videoSize$=new nt.ValueSubject(void 0);this.elementSize$=new nt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=nt.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,nt.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,nt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,nt.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var cr=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new ne("stopped");this.observableVideo=null;this.droppedFramesManager=new Fr;this.stallsManager=new lo;this.elementSizeManager=new jo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ei;this.audioTrackSwitchHistory=new Ei;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,Y.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new qr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new gt(e.source.url),this.params=e,this.video=et(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(We(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 Uo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,Y.isNullable)(this.observableVideo)&&(this.observableVideo=rt(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Y.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,Y.filter)(l=>!!l.length),(0,Y.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,Y.map)(l=>l.to.state!=="none"),(0,Y.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.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.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,Y.filter)(Y.isNonNullable),(0,Y.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,Y.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(jt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),xi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(it(this.video,t.volume,i.volumeState$,r)),this.subscription.add(bt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(St(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),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 p=this.player.getStreams(),h=this.player.getCodecs();if((0,Y.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of p.audio){b.push(Ll(S));let v=[];for(let y of S.representations){let x=xs(y);v.push(x),this.audioTracksMap.set(x,{stream:S,representation:y})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of p.video){m.push(Bl(b));let S=[];for(let v of b.representations){let y=Ai(U(M({},v),{streamId:b.id}));y&&(S.push(y),this.videoTracksMap.set(y,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of p.text)for(let S of b.representations){let v=Vy(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}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),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,Y.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,Y.fromEvent)(this.video,"progress")).pipe((0,Y.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,Y.throttle)(u))),this.subscription.add(o.subscribe(()=>I(this,null,function*(){let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,S=[...this.videoTracksMap.keys()].find(y=>{var x;return((x=this.videoTracksMap.get(y))==null?void 0:x.representation.id)===m.id});(0,Y.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),l==="manifest_ready")yield this.player.initRepresentations(m.id,b==null?void 0:b.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",m.id),b){let y=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",b.id,y)}}),r)),this.subscription.add((0,Y.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,Y.merge)((0,Y.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,Y.map)(l=>l.to)))}).pipe((0,Y.map)(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),(0,Y.filterChanged)()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),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((0,Y.filterChanged)()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Bl(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,Y.filterChanged)()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Ll(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var p,h;if(l!=null&&l.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe((0,Y.map)(({to:l})=>l==="ready"),(0,Y.filterChanged)());this.subscription.add((0,Y.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,Y.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,Y.merge)(c,this.player.state$.stateChangeEnded$,(0,Y.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,Y.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Y.observableFrom)(["init"])).pipe((0,Y.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var W,F,_,K,q,ee,pe,ce,N,O,k,R,X;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Fa:Na,t=this.params.tuning.useNewAutoSelectVideoTrack?ro:io,i=this.params.tuning.useNewAutoSelectVideoTrack?Ht:to,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(W=r.videoTrack.getState())==null?void 0:W.id,u=[...this.videoTracksMap.keys()].find(({id:z})=>z===o),c=s.currentVideoTrack$.getValue(),d=((K=(_=r.videoStream.getState())!=null?_:u&&((F=this.videoTracksMap.get(u))==null?void 0:F.stream))!=null?K:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:z})=>z===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=Mi(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=(q=r.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(ee=[...this.audioStreamsMap.keys()].find(({id:z})=>z===(v==null?void 0:v.id)))!=null?ee:this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let z=e(u,p,(pe=this.audioStreamsMap.get(y))!=null?pe:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(ce=z==null?void 0:z.bitrate)!=null?ce:-1/0)}if(c){let z=e(c,p,(N=this.audioStreamsMap.get(y))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(O=z==null?void 0:z.bitrate)!=null?O:-1/0)}}let P=u;(n||!P)&&(P=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:x,forwardBufferHealth:S,current:c,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}));let D=y&&t(P,p,(k=this.audioStreamsMap.get(y))!=null?k:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=(R=this.videoTracksMap.get(P))==null?void 0:R.representation,Q=D&&((X=this.audioTracksMap.get(D))==null?void 0:X.representation);if(V&&Q)return[V,Q];if(V&&!Q&&this.audioTracksMap.size===0)return[V,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Y.ErrorCategory.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),tt(this.video),this.tracer.end()}};var $s=class extends cr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Se=require("@vkontakte/videoplayer-shared/es2015");var Cs=class extends cr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Se.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,Se.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,Se.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,Se.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Se.map)(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).add((0,Se.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,Se.merge)(r.playbackRateState$,new Se.ValueSubject(1))}).pipe((0,Se.filter)(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||(0,Se.isNullable)(d)||(t=u-d)})).add((0,Se.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,Se.merge)(r.playbackRateState$,new Se.ValueSubject(1))}).pipe((0,Se.filterChanged)((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||(0,Se.isNullable)(u)||(0,Se.isNullable)(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=_y(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,Se.filter)(u=>(0,Se.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Yy="X-Playback-Duration",Hl=a=>I(null,null,function*(){var r;let e=yield yt(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Yy)?parseInt(e.headers.get(Yy),10):void 0});var ue=require("@vkontakte/videoplayer-shared/es2015");var Wl=Z(cc(),1);var Ho=require("@vkontakte/videoplayer-shared/es2015");var lC=a=>{let e=null;if(a.QUALITY&&(e=Ii(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Ho.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},dC=(a,e)=>{var s,n;let t=a.split(`
|
|
179
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!d)){if(c){let l=(0,Wl.default)(c[1].split(",").map(y=>y.split("="))),p=(s=l.QUALITY)!=null?s:`stream-${l.BANDWIDTH}`,h=lC(l),m;l.BANDWIDTH&&(m=parseInt(l.BANDWIDTH,10)/1e3||void 0),!m&&l["AVERAGE-BANDWIDTH"]&&(m=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,S;if(l.RESOLUTION){let[y,x]=l.RESOLUTION.split("x").map(P=>parseInt(P,10));y&&x&&(S={width:y,height:x})}let v=new URL(t[++o],e).toString();h&&i.push({id:p,quality:h,url:v,bandwidth:m,size:S,fps:b})}if(d){let l=(0,Wl.default)(d[1].split(",").map(b=>{let S=b.indexOf("=");return[b.substring(0,S),b.substring(S+1)]}).map(([b,S])=>[b,S.replace(/^"|"$/g,"")])),p=(n=l.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=l.LANGUAGE,m=l.NAME;p&&h&&r.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},pC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Ql=0,Ky=(r,...s)=>I(null,[r,...s],function*(a,e=a,t,i){let o=yield(yield yt(a,i)).text();Ql+=1;try{let{qualityManifests:u,textTracks:c}=dC(o,e);return{qualityManifests:u,textTracks:c}}catch(u){if(Ql<=t.manifestRetryMaxCount)return yield pC((0,Ho.getExponentialDelay)(Ql-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ky(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Qo=Ky;var ft=require("@vkontakte/videoplayer-shared/es2015");var Wo=class{constructor(e,t,i,r,s){this.subscription=new ft.Subscription;this.abortControllers={destroy:new Ie,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new ft.ValueSubject(null);this.getCurrentTime$=new ft.ValueSubject(null);this.error$=new ft.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe((0,ft.throttle)(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 I(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return I(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return I(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield yt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}})}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
180
|
+
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],c=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:c}),s=s+d,!i.segmentStartTime){let l=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-l}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let c=new Date(u);c.setMilliseconds(0),s=c.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,ft.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([U(M({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return I(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Ie;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 I(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:ft.ErrorCategory.WTF,thrown:t,message:e})}};var Ds=class{constructor(e){this.subscription=new ue.Subscription;this.videoState=new ne("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ue.ValueSubject([]);this.liveOffset=new Zi;this.manifestStartTime$=new ue.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,ue.assertNever)(t)}};var i;this.params=e,this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ue.VideoQuality.INVARIANT,url:this.params.source.url};let t=(r,s)=>Qo(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Wo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new gt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ue.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:ue.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ue.ValueSubject((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:ue.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=rt(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(bt(this.video,t.playbackRate,r.playbackRateState$,i)),s(St(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,ue.filterChanged)(),(0,ue.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,ue.isNonNullable)(c.to)){let l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(We(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,c,d;let o=(d=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,ue.combine)({startTime:this.manifestStartTime$.pipe((0,ue.filter)(ue.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,ue.map)(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,ue.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),tt(this.video)}prepare(){var o,u,c;let e=this.selectManifest();if((0,ue.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[p,h]of[[d,"mq"],[l,"lq"]]){let m=String(parseFloat(p||""));h&&p&&r.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=He(r.toString(),this.liveOffset.getTotalOffset(),s);(c=this.liveTextManager)==null||c.prepare(n),this.video.setAttribute("src",n),this.video.load(),Hl(n).then(d=>{var l;if(!(0,ue.isNullable)(d))this.maxSeekBackTime$.next(d);else{let p=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();((0,ue.isNullable)(p)||!isFinite(p))&&yt(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 S=new URL(m,n).toString();Hl(S).then(v=>{(0,ue.isNullable)(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ue.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=He(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}};var fe=require("@vkontakte/videoplayer-shared/es2015");var Ls=class{constructor(e){this.subscription=new fe.Subscription;this.videoState=new ne("stopped");this.manifests$=new fe.ValueSubject([]);this.unmuteAfterBrowserResetsHappened=new fe.ValueSubject(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,fe.assertNever)(t)}};this.textTracksManager=new gt(e.source.url),this.params=e,this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:fe.VideoQuality.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(We(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Qo(He(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:fe.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:fe.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=rt(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,fe.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(jt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(bt(this.video,t.playbackRate,r.playbackRateState$,i)),xi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,fe.isNonNullable)(c.to)){let m=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let b=this.manifests$.getValue().find(S=>S.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(We(b.url)))}let l=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(l!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(l),m.playbackRate=l)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe((0,fe.map)(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!G.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,fe.merge)((0,fe.fromEvent)(o,"addtrack"),(0,fe.fromEvent)(o,"removetrack"),(0,fe.fromEvent)(o,"change"),(0,fe.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,fe.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,fe.observableFrom)(["init"])).pipe((0,fe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),tt(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,fe.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[c,d]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(c||""));d&&c&&r.searchParams.set(d,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Xy=Z(Si(),1),zl=Z(Wi(),1),Jy=Z(vt(),1);var xe=require("@vkontakte/videoplayer-shared/es2015");var Bs=class{constructor(e){this.subscription=new xe.Subscription;this.videoState=new ne("stopped");this.trackUrls={};this.textTracksManager=new gt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?B(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,xe.assertNever)(e)}};this.params=e,this.video=et(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Xy.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,zl.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:xe.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=rt(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,xe.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(jt(this.video,t.isLooped,i)),xi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(bt(this.video,t.playbackRate,r.playbackRateState$,i)),s(St(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,xe.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),l=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(d!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=(0,xe.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,xe.observableFrom)(["init"])).pipe((0,xe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),tt(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,xe.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,xe.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Pi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(We(t))}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var c,d;this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=Ht(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=(c=this.params.output.currentVideoTrack$.getValue())==null?void 0:c.quality,s=!!(e.max||e.min),n=(0,zl.default)(this.trackUrls).map(l=>l.track);if(!r||!s||_r(e,n[0].quality,(d=(0,Jy.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?(0,xe.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,xe.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var Pe=require("@vkontakte/videoplayer-shared/es2015");var eT=require("@vkontakte/videoplayer-shared/es2015");var Zy=["stun:videostun.mycdn.me:80"],hC=1e3,fC=3,Gl=()=>null,zo=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=Gl;this.externalStopCallback=Gl;this.externalErrorCallback=Gl;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return I(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 I(this,null,function*(){try{let e={iceServers:[{urls:Zy}]};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 I(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return I(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:eT.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return I(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 I(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),hC)}normalizeOptions(e={}){let t={stunServerList:Zy,maxRetryNumber:fC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Vs=class{constructor(e){this.videoState=new ne("stopped");this.maxSeekBackTime$=new Pe.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,Pe.assertNever)(e)}};this.subscription=new Pe.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=et(e.container,e.tuning),this.liveStreamClient=new zo(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),tt(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Pe.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,Pe.merge)(this.videoState.stateChangeStarted$.pipe((0,Pe.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Pe.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=rt(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(St(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(it(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,Pe.assertNever)(n.to)}},i)).add((0,Pe.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Pe.observableFrom)(["init"])).pipe((0,Pe.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(We(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:Pe.VideoQuality.INVARIANT}),this.video.srcObject=e,B(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.currentNativeBuffer$.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:Pe.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){at(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pe.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Xr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};var w=require("@vkontakte/videoplayer-shared/es2015");var ni=require("@vkontakte/videoplayer-shared/es2015");var tT=a=>new ni.Observable(e=>{let t=new ni.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,ni.map)(({from:c,to:d})=>`${c}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,ni.map)(({type:c})=>c!==void 0)),n=new ni.Subject,o=0,u="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval),ie({m:"hangup.set",l:c,id:o})})),t.add(r.subscribe(()=>{ie({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(ie({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval),ie({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Tt=require("@vkontakte/videoplayer-shared/es2015");function iT(){return new(window.AudioContext||window.webkitAudioContext)}var _s=class _s{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Ie;this.subscriptions=new Tt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Tt.filter)(s=>!!s.type),(0,Tt.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){G.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Tt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Tt.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,Tt.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return I(this,null,function*(){let{volumeMultiplier:t}=this,i=iT();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:_s.errorId,category:Tt.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${_s.errorId} exception`,thrown:e})}};_s.errorId="VolumeMultiplierManager";var Jr=_s;var mC={chunkDuration:5e3,maxParallelRequests:5},Os=class{constructor(e){this.current$=new w.ValueSubject({type:void 0});this.providerError$=new w.Subject;this.noAvailableProvidersError$=new w.Subject;this.volumeMultiplierError$=new w.Subject;this.providerOutput={position$:new w.ValueSubject(0),duration$:new w.ValueSubject(1/0),volume$:new w.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new w.ValueSubject([]),currentVideoStream$:new w.ValueSubject(void 0),availableVideoTracks$:new w.ValueSubject([]),currentVideoTrack$:new w.ValueSubject(void 0),availableVideoCodecs$:new w.ValueSubject([]),availableAudioStreams$:new w.ValueSubject([]),currentAudioStream$:new w.ValueSubject(void 0),availableAudioTracks$:new w.ValueSubject([]),availableAudioCodecs$:new w.ValueSubject([]),currentVideoSegmentLength$:new w.ValueSubject(0),currentAudioSegmentLength$:new w.ValueSubject(0),isAudioAvailable$:new w.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new w.ValueSubject(!1),autoVideoTrackLimits$:new w.ValueSubject(void 0),currentBuffer$:new w.ValueSubject(void 0),currentNativeBuffer$:new w.ValueSubject(void 0),isBuffering$:new w.ValueSubject(!0),error$:new w.Subject,fetcherError$:new w.Subject,fetcherRecoverableError$:new w.Subject,warning$:new w.Subject,willSeekEvent$:new w.Subject,soundProhibitedEvent$:new w.Subject,seekedEvent$:new w.Subject,loopedEvent$:new w.Subject,endedEvent$:new w.Subject,manifestRequested$:new w.Subject,firstBytesManifest$:new w.Subject,manifestReceived$:new w.Subject,firstBytesRequested$:new w.Subject,firstBytesReceived$:new w.Subject,firstBytesEvent$:new w.Subject,loadedMetadataEvent$:new w.Subject,firstFrameEvent$:new w.Subject,canplay$:new w.Subject,isLive$:new w.ValueSubject(void 0),isLiveEnded$:new w.ValueSubject(null),canPlayLiveTailBuffer$:new w.ValueSubject(!1),isLowLatency$:new w.ValueSubject(!1),canChangePlaybackSpeed$:new w.ValueSubject(!0),liveTime$:new w.ValueSubject(void 0),liveBufferTime$:new w.ValueSubject(void 0),liveLatency$:new w.ValueSubject(void 0),severeStallOccurred$:new w.Subject,availableTextTracks$:new w.ValueSubject([]),currentTextTrack$:new w.ValueSubject(void 0),hostname$:new w.ValueSubject(void 0),httpConnectionType$:new w.ValueSubject(void 0),httpConnectionReused$:new w.ValueSubject(void 0),httpConnectionMetrics$:new w.ValueSubject(void 0),httpDownloadMetrics$:new w.ValueSubject(void 0),inPiP$:new w.ValueSubject(!1),inFullscreen$:new w.ValueSubject(!1),element$:new w.ValueSubject(void 0),elementVisible$:new w.ValueSubject(!0),availableSources$:new w.ValueSubject(void 0),is3DVideo$:new w.ValueSubject(!1),playbackState$:new w.ValueSubject(""),getCurrentTime$:new w.ValueSubject(null)};this.subscription=new w.Subscription;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=qu([...Ey(this.params.tuning),...Iy(this.params.tuning)]).filter(c=>(0,w.isNonNullable)(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(c=>!(0,Yl.default)(r,c)),...t.filter(c=>(0,Yl.default)(r,c))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,w.flattenObject)(s)),this.screenFormatsIterator=new Xr(s);let n=[...Cl(!0),...Cl(!1)];this.chromecastFormatsIterator=new Xr(n.filter(c=>(0,w.isNonNullable)(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Jr.isSupported()&&(this.volumeMultiplierManager=new Jr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){ie.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Xr(e))}))}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((0,w.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:w.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}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(0,w.assertNever)(e)}}createScreenProvider(e){var u,c,d;let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let l=this.applyFailoverHost(t[e]),p=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,w.assertNonNullable)(l),this.params.tuning.useDashProviderVirtual&&!G.device.isMobile?new Kr(U(M({},o),{source:l,sourceHls:p,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()})):this.params.tuning.useDashProviderVirtualMobile&&G.device.isMobile?new Kr(U(M({},o),{source:l,sourceHls:p,forceVideoCodec:(c=this.videoCodecsIterator)==null?void 0:c.getValue()})):new $s(U(M({},o),{source:l,sourceHls:p,forceVideoCodec:(d=this.videoCodecsIterator)==null?void 0:d.getValue()}))}case"DASH_LIVE_CMAF":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new Cs(U(M({},o),{source:l}))}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new Ls(U(M({},o),{source:l}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new Ds(U(M({},o),{source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new Bs(U(M({},o),{source:l}))}case"DASH_LIVE":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new Cv(U(M({},o),{source:l,config:U(M({},mC),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let l=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(l),new Vs({container:i,source:l,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,w.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o={meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof Jt){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return(0,w.assertNonNullable)(c),new Ta(U(M({},o),{chromecastConnector:c}))}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,w.assertNonNullable)(u),new Ba(U(M({},o),{connection:u}))}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(0,w.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,w.assertNever)(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(0,w.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return U(M({},e),{url:i(e.url)})}return(0,rT.default)((0,Kl.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new w.Subscription,t=!1,i=0;e.add((0,w.merge)(this.providerOutput.error$.pipe((0,w.filter)(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),tT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,w.map)(s=>({id:`ProviderHangup:${s}`,category:w.ErrorCategory.WTF,message:`A ${s} 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 s=this.params.desiredState.playbackState.transitionEnded$.pipe((0,w.filter)(({to:n})=>n==="playing"),(0,w.once)()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=ie.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&(0,w.getWindow)().console.log(`===== DASH_LIVE DEBUG START ====
|
|
181
181
|
`,s.map(({time:u,data:c,stack:d})=>`${u}: ${JSON.stringify(c)}${d?`
|
|
182
182
|
`+d:""}`).join(`
|
|
183
183
|
`),`
|
|
184
|
-
===== DASH_LIVE DEBUG END ====`),o){let u=s.reduce((c,{time:d,data:l,stack:p})=>{let h=(0,Gl.default)(l).map(([m,b])=>`${m}:${b}`).join(",");return c+=`${d}: ${h}${p?`: ${p}`:""};`,c},"");w.devNull.push("core",{key:"vp_dash_live_debug",strings:[u]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(ie({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{ie({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(s=>{let n=this.current$.getValue().destination,o={error:s,currentDestination:n};if(n==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=s.category===w.ErrorCategory.NETWORK,c=s.category===w.ErrorCategory.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!c,p=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=d&&!c&&(u&&t||!l);o=U(M({},o),{isNetworkError:u,isFatalError:c,haveFailoverHost:d,tryFailover:h,canReinitProvider:l}),l?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(n!=null?n:"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",(0,w.flattenObject)(o)):this.tracer.error("providerError",(0,w.flattenObject)(o))})),e}};var te=require("@vkontakte/videoplayer-shared/es2015");var mC=5e3,iT="one_video_throughput",rT="one_video_rtt",Kl=()=>{let{navigator:a}=(0,te.getWindow)();if(a)return a.connection},aT=()=>{var e;let a=(e=Kl())==null?void 0:e.downlink;if((0,te.isNonNullable)(a)&&a!==10)return a*1e3},sT=()=>{var e;let a=(e=Kl())==null?void 0:e.rtt;if((0,te.isNonNullable)(a)&&a!==3e3)return a},nT=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Yl=class a{constructor(e){this.subscription=new te.Subscription;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(iT)||(e.useBrowserEstimation?aT():void 0)||mC,i=(s=(r=a.load(rT))!=null?r:e.useBrowserEstimation?sT():void 0)!=null?s:0;if(this.throughput$=new te.ValueSubject(t),this.rtt$=new te.ValueSubject(i),this.rttAdjustedThroughput$=new te.ValueSubject(nT(t,i,e.rttPenaltyRequestSize)),this.throughput=ur.getSmoothedValue(t,-1,e),this.rtt=ur.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let c=aT();c&&this.throughput.next(c);let d=sT();(0,te.isNonNullable)(d)&&this.rtt.next(d)},o=Kl();o&&"onchange"in o&&this.subscription.add((0,te.fromEvent)(o,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{te.safeStorage.set(iT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{te.safeStorage.set(rT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe((0,te.map)(n=>Math.round(n))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,te.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,te.map)(({throughput:n,rtt:o})=>nT(n,o,e.rttPenaltyRequestSize)),(0,te.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,te.now)(),r=new te.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,te.fromEvent)(e,"progress").pipe((0,te.once)()).subscribe(s=>{t=s.loaded,i=(0,te.now)()}));break;case 1:case 0:r.add((0,te.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,te.now)()}));break}r.add((0,te.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,te.now)(),u=n-t,c=o-i;this.addRawSpeed(u,c,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,te.now)(),n=0,o=(0,te.now)(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},c=p=>I(this,[p],function*({done:d,value:l}){if(d)!t&&this.addRawSpeed(r,(0,te.now)()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let h=(0,te.now)();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=l.byteLength,s=(0,te.now)()}else n+=l.byteLength;o=(0,te.now)()}else r+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,te.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,te.now)()-o,this.concurrentDownloads.size),n=0,o=(0,te.now)());yield i==null?void 0:i.read().then(c,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(c,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=te.safeStorage.get(e);if((0,te.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},oT=Yl;var lr=require("@vkontakte/videoplayer-shared/es2015"),bC={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:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:lr.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:lr.VideoQuality.Q_720P,trafficSavingLimit:lr.VideoQuality.Q_480P},stallsManager:{enabled:!1,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:lr.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,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",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",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,useNewSwitchTo:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},uT=a=>(0,lr.fillWithDefault)(a,bC);var f=require("@vkontakte/videoplayer-shared/es2015");var oi=require("@vkontakte/videoplayer-shared/es2015"),Xl=({seekState:a,position$:e})=>(0,oi.merge)(a.stateChangeEnded$.pipe((0,oi.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,oi.filter)(oi.isNonNullable)),e.pipe((0,oi.filter)(()=>a.getState().state==="none")));var cT=require("@vkontakte/videoplayer-shared/es2015"),lT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,cT.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Wo=require("@vkontakte/videoplayer-shared/es2015"),dT=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,Wo.filter)(r=>r.length>0),(0,Wo.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var pT=Z(Si(),1);var Zr=require("@vkontakte/videoplayer-shared/es2015");var hT=()=>{let a="mediaCapabilities"in(0,Zr.getWindow)().navigator?gC:vC,e=ir(()=>I(null,null,function*(){let t=yield Promise.all((0,pT.default)(SC).map(n=>I(null,[n],function*([r,s]){return{codec:r,supported:yield a(s)}}))),i=[G.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return Zr.devNull.push("core",{key:"videoplayer_decoding_info",strings:i}),t}));return()=>rr(e)},gC=a=>I(null,null,function*(){if(!a)return Promise.resolve({supported:!1});let e={["channels"in a?"audio":"video"]:a};return yield(0,Zr.getWindow)().navigator.mediaCapabilities.decodingInfo(M({type:"media-source"},e))}),vC=a=>{var i;if(!a)return Promise.resolve({supported:!1});let e=(0,Zr.getWindow)().document,t="channels"in a?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType((i=a==null?void 0:a.contentType)!=null?i:"")==="probably"})},SC={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var Os=class{constructor(e={},t=f.TracerFactory.createRootTracer(!1),i){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new f.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new ne("stopped"),seekState:new ne({state:"none"}),volume:new ne({volume:1,muted:!1}),videoTrack:new ne(void 0),videoStream:new ne(void 0),audioStream:new ne(void 0),autoVideoTrackSwitching:new ne(!0),autoVideoTrackLimits:new ne({}),isLooped:new ne(!1),isLowLatency:new ne(!1),playbackRate:new ne(1),externalTextTracks:new ne([]),internalTextTracks:new ne([]),currentTextTrack:new ne(void 0),textTrackCuesSettings:new ne({}),cameraOrientation:new ne({x:0,y:0})};this.info={playbackState$:new f.ValueSubject(void 0),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),predefinedQualityLimitType$:new f.ValueSubject("unknown"),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),currentNativeBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),isLiveEnded$:new f.ValueSubject(null),canPlayLiveTailBuffer$:new f.ValueSubject(!1),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),httpConnectionMetrics$:new f.ValueSubject(void 0),httpDownloadMetrics$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willReady$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,fetcherRecoverableError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,manifestRequested$:new f.Subject,firstBytesManifest$:new f.Subject,manifestReceived$:new f.Subject,firstBytesRequested$:new f.Subject,firstBytesReceived$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject,fetcherError$:new f.Subject,severeStallOccured$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:lv,getCurrentTime$:new f.ValueSubject(null)};this.initLogs(),this.tuning=uT(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,Jl.default)(this.info).forEach(s=>s.setSuppressErrors(!0)),(0,Jl.default)(this.events).forEach(s=>s.setSuppressErrors(!0)));let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new Jt(r):new ln(r),this.throughputEstimator=new oT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("core",(0,f.getPlayerId)(i==null?void 0:i.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i==null?void 0:i.onDevNullLog,f.devNull.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,n,o)=>{let u=Reflect.get(s,n,o);return typeof u!="function"?u:(...c)=>{try{return u.apply(s,c)}catch(d){let l=c.map(m=>JSON.stringify(m,(b,S)=>{let v=typeof S;return(0,fT.default)(["number","string","boolean"],v)?S:S===null?null:`<${v}>`})),p=`Player.${String(n)}`,h=`Exception calling ${p} (${l.join(", ")})`;throw this.events.fatalError$.next({id:p,category:f.ErrorCategory.WTF,message:h,thrown:d}),d}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var c,d,l;let u=e,{container:n}=u,o=fi(u,["container"]);this.tracer.log("initVideo",(0,f.flattenObject)(o)),this.domContainer=lT(e),this.chromecastInitializer.contentId=(c=e.meta)==null?void 0:c.videoId,this.providerContainer=new _s({sources:e.sources,meta:(d=e.meta)!=null?d:{},failoverHosts:(l=e.failoverHosts)!=null?l:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0),this.devNullLog&&this.tuning.devNullLogEnabled?(f.devNull.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=hT())):f.devNull.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?G.isInited$.pipe((0,f.filter)(n=>!!n),(0,f.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(r)):r(),this}destroy(){var e,t,i;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy(),f.devNull.destroy("core"),(i=this.collectDecodingInfoDestroyCb)==null||i.call(this)}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{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.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{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.waitInit(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Jt)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Jt)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{(0,f.assertNonNullable)(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((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>M({type:"external"},t)))}),this}selectTextTrack(e){return this.waitInit(()=>{var t;dT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",M({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{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.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(dv(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),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"ready":this.events.willReady$.next();break;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",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(U(M({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).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",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,c)=>(0,f.isInvariantQuality)(u)?1:(0,f.isInvariantQuality)(c)?-1:(0,f.isHigher)(c,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((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,f.filter)(n=>(0,f.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.httpConnectionMetrics$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionMetrics$)).add(e.providerOutput.httpDownloadMetrics$.pipe((0,f.filterChanged)()).subscribe(this.info.httpDownloadMetrics$)).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((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).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((0,f.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).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((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(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((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Xl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Xl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).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((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.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.manifestRequested$.pipe((0,f.once)()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe((0,f.once)()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe((0,f.once)()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe((0,f.once)()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe((0,f.once)()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-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 f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(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,c;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(c=n==null?void 0:n.size)==null?void 0:c.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((0,f.merge)(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(),c=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":u?c?n?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(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 f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Ht(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(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;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),cv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>uv(i)),this.providerContainer.current$.subscribe(({type:i})=>Oa("provider",i)),e.duration$.subscribe(i=>Oa("duration",i)),e.availableVideoTracks$.pipe((0,f.filter)(i=>!!i.length),(0,f.once)()).subscribe(i=>Oa("tracks",i)),this.events.fatalError$.subscribe(new Ge("fatalError")),this.events.managedError$.subscribe(new Ge("managedError")),e.position$.subscribe(new Ge("position")),e.currentVideoTrack$.pipe((0,f.map)(i=>i==null?void 0:i.quality)).subscribe(new Ge("quality")),this.info.currentBuffer$.subscribe(new Ge("buffer")),e.isBuffering$.subscribe(new Ge("isBuffering"))].forEach(i=>this.subscription.add(i)),Oa("codecs",G.video.supportedCodecs)}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(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((0,f.filterChanged)()).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((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).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((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>I(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ha()}};var zt=require("@vkontakte/videoplayer-shared/es2015"),yC=`@vkontakte/videoplayer-core@${Zo}`;
|
|
184
|
+
===== DASH_LIVE DEBUG END ====`),o){let u=s.reduce((c,{time:d,data:l,stack:p})=>{let h=(0,Kl.default)(l).map(([m,b])=>`${m}:${b}`).join(",");return c+=`${d}: ${h}${p?`: ${p}`:""};`,c},"");w.devNull.push("core",{key:"vp_dash_live_debug",strings:[u]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(ie({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{ie({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(s=>{let n=this.current$.getValue().destination,o={error:s,currentDestination:n};if(n==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=s.category===w.ErrorCategory.NETWORK,c=s.category===w.ErrorCategory.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!c,p=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=d&&!c&&(u&&t||!l);o=U(M({},o),{isNetworkError:u,isFatalError:c,haveFailoverHost:d,tryFailover:h,canReinitProvider:l}),l?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(n!=null?n:"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",(0,w.flattenObject)(o)):this.tracer.error("providerError",(0,w.flattenObject)(o))})),e}};var te=require("@vkontakte/videoplayer-shared/es2015");var bC=5e3,aT="one_video_throughput",sT="one_video_rtt",Jl=()=>{let{navigator:a}=(0,te.getWindow)();if(a)return a.connection},nT=()=>{var e;let a=(e=Jl())==null?void 0:e.downlink;if((0,te.isNonNullable)(a)&&a!==10)return a*1e3},oT=()=>{var e;let a=(e=Jl())==null?void 0:e.rtt;if((0,te.isNonNullable)(a)&&a!==3e3)return a},uT=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Xl=class a{constructor(e){this.subscription=new te.Subscription;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(aT)||(e.useBrowserEstimation?nT():void 0)||bC,i=(s=(r=a.load(sT))!=null?r:e.useBrowserEstimation?oT():void 0)!=null?s:0;if(this.throughput$=new te.ValueSubject(t),this.rtt$=new te.ValueSubject(i),this.rttAdjustedThroughput$=new te.ValueSubject(uT(t,i,e.rttPenaltyRequestSize)),this.throughput=ur.getSmoothedValue(t,-1,e),this.rtt=ur.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let c=nT();c&&this.throughput.next(c);let d=oT();(0,te.isNonNullable)(d)&&this.rtt.next(d)},o=Jl();o&&"onchange"in o&&this.subscription.add((0,te.fromEvent)(o,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{te.safeStorage.set(aT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{te.safeStorage.set(sT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe((0,te.map)(n=>Math.round(n))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,te.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,te.map)(({throughput:n,rtt:o})=>uT(n,o,e.rttPenaltyRequestSize)),(0,te.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,te.now)(),r=new te.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,te.fromEvent)(e,"progress").pipe((0,te.once)()).subscribe(s=>{t=s.loaded,i=(0,te.now)()}));break;case 1:case 0:r.add((0,te.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,te.now)()}));break}r.add((0,te.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,te.now)(),u=n-t,c=o-i;this.addRawSpeed(u,c,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,te.now)(),n=0,o=(0,te.now)(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},c=p=>I(this,[p],function*({done:d,value:l}){if(d)!t&&this.addRawSpeed(r,(0,te.now)()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let h=(0,te.now)();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=l.byteLength,s=(0,te.now)()}else n+=l.byteLength;o=(0,te.now)()}else r+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,te.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,te.now)()-o,this.concurrentDownloads.size),n=0,o=(0,te.now)());yield i==null?void 0:i.read().then(c,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(c,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=te.safeStorage.get(e);if((0,te.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},cT=Xl;var lr=require("@vkontakte/videoplayer-shared/es2015"),gC={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:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:lr.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:lr.VideoQuality.Q_720P,trafficSavingLimit:lr.VideoQuality.Q_480P},stallsManager:{enabled:!1,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:lr.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500,videoStreamRepresentaionsFilter:[]},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,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",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",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,useNewSwitchTo:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},lT=a=>(0,lr.fillWithDefault)(a,gC);var f=require("@vkontakte/videoplayer-shared/es2015");var oi=require("@vkontakte/videoplayer-shared/es2015"),Zl=({seekState:a,position$:e})=>(0,oi.merge)(a.stateChangeEnded$.pipe((0,oi.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,oi.filter)(oi.isNonNullable)),e.pipe((0,oi.filter)(()=>a.getState().state==="none")));var dT=require("@vkontakte/videoplayer-shared/es2015"),pT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,dT.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Go=require("@vkontakte/videoplayer-shared/es2015"),hT=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,Go.filter)(r=>r.length>0),(0,Go.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var fT=Z(Si(),1);var Zr=require("@vkontakte/videoplayer-shared/es2015");var mT=()=>{let a="mediaCapabilities"in(0,Zr.getWindow)().navigator?vC:SC,e=ir(()=>I(null,null,function*(){let t=yield Promise.all((0,fT.default)(yC).map(n=>I(null,[n],function*([r,s]){return{codec:r,supported:yield a(s)}}))),i=[G.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return Zr.devNull.push("core",{key:"videoplayer_decoding_info",strings:i}),t}));return()=>rr(e)},vC=a=>I(null,null,function*(){if(!a)return Promise.resolve({supported:!1});let e={["channels"in a?"audio":"video"]:a};return yield(0,Zr.getWindow)().navigator.mediaCapabilities.decodingInfo(M({type:"media-source"},e))}),SC=a=>{var i;if(!a)return Promise.resolve({supported:!1});let e=(0,Zr.getWindow)().document,t="channels"in a?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType((i=a==null?void 0:a.contentType)!=null?i:"")==="probably"})},yC={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var Ns=class{constructor(e={},t=f.TracerFactory.createRootTracer(!1),i){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new f.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new ne("stopped"),seekState:new ne({state:"none"}),volume:new ne({volume:1,muted:!1}),videoTrack:new ne(void 0),videoStream:new ne(void 0),audioStream:new ne(void 0),autoVideoTrackSwitching:new ne(!0),autoVideoTrackLimits:new ne({}),isLooped:new ne(!1),isLowLatency:new ne(!1),playbackRate:new ne(1),externalTextTracks:new ne([]),internalTextTracks:new ne([]),currentTextTrack:new ne(void 0),textTrackCuesSettings:new ne({}),cameraOrientation:new ne({x:0,y:0})};this.info={playbackState$:new f.ValueSubject(void 0),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),predefinedQualityLimitType$:new f.ValueSubject("unknown"),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),currentNativeBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),isLiveEnded$:new f.ValueSubject(null),canPlayLiveTailBuffer$:new f.ValueSubject(!1),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),httpConnectionMetrics$:new f.ValueSubject(void 0),httpDownloadMetrics$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willReady$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,fetcherRecoverableError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,manifestRequested$:new f.Subject,firstBytesManifest$:new f.Subject,manifestReceived$:new f.Subject,firstBytesRequested$:new f.Subject,firstBytesReceived$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject,fetcherError$:new f.Subject,severeStallOccured$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:pv,getCurrentTime$:new f.ValueSubject(null)};this.initLogs(),this.tuning=lT(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,ed.default)(this.info).forEach(s=>s.setSuppressErrors(!0)),(0,ed.default)(this.events).forEach(s=>s.setSuppressErrors(!0)));let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new Jt(r):new dn(r),this.throughputEstimator=new cT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("core",(0,f.getPlayerId)(i==null?void 0:i.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i==null?void 0:i.onDevNullLog,f.devNull.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,n,o)=>{let u=Reflect.get(s,n,o);return typeof u!="function"?u:(...c)=>{try{return u.apply(s,c)}catch(d){let l=c.map(m=>JSON.stringify(m,(b,S)=>{let v=typeof S;return(0,bT.default)(["number","string","boolean"],v)?S:S===null?null:`<${v}>`})),p=`Player.${String(n)}`,h=`Exception calling ${p} (${l.join(", ")})`;throw this.events.fatalError$.next({id:p,category:f.ErrorCategory.WTF,message:h,thrown:d}),d}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var c,d,l;let u=e,{container:n}=u,o=fi(u,["container"]);this.tracer.log("initVideo",(0,f.flattenObject)(o)),this.domContainer=pT(e),this.chromecastInitializer.contentId=(c=e.meta)==null?void 0:c.videoId,this.providerContainer=new Os({sources:e.sources,meta:(d=e.meta)!=null?d:{},failoverHosts:(l=e.failoverHosts)!=null?l:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0),this.devNullLog&&this.tuning.devNullLogEnabled?(f.devNull.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=mT())):f.devNull.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?G.isInited$.pipe((0,f.filter)(n=>!!n),(0,f.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(r)):r(),this}destroy(){var e,t,i;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy(),f.devNull.destroy("core"),(i=this.collectDecodingInfoDestroyCb)==null||i.call(this)}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{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.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{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.waitInit(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Jt)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Jt)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{(0,f.assertNonNullable)(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((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>M({type:"external"},t)))}),this}selectTextTrack(e){return this.waitInit(()=>{var t;hT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",M({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{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.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(hv(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),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"ready":this.events.willReady$.next();break;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",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(U(M({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).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",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,c)=>(0,f.isInvariantQuality)(u)?1:(0,f.isInvariantQuality)(c)?-1:(0,f.isHigher)(c,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((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,f.filter)(n=>(0,f.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.httpConnectionMetrics$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionMetrics$)).add(e.providerOutput.httpDownloadMetrics$.pipe((0,f.filterChanged)()).subscribe(this.info.httpDownloadMetrics$)).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((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).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((0,f.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).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((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(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((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).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((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.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.manifestRequested$.pipe((0,f.once)()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe((0,f.once)()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe((0,f.once)()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe((0,f.once)()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe((0,f.once)()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-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 f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(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,c;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(c=n==null?void 0:n.size)==null?void 0:c.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((0,f.merge)(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(),c=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":u?c?n?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(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 f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Ht(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(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;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),dv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>lv(i)),this.providerContainer.current$.subscribe(({type:i})=>Oa("provider",i)),e.duration$.subscribe(i=>Oa("duration",i)),e.availableVideoTracks$.pipe((0,f.filter)(i=>!!i.length),(0,f.once)()).subscribe(i=>Oa("tracks",i)),this.events.fatalError$.subscribe(new Ge("fatalError")),this.events.managedError$.subscribe(new Ge("managedError")),e.position$.subscribe(new Ge("position")),e.currentVideoTrack$.pipe((0,f.map)(i=>i==null?void 0:i.quality)).subscribe(new Ge("quality")),this.info.currentBuffer$.subscribe(new Ge("buffer")),e.isBuffering$.subscribe(new Ge("isBuffering"))].forEach(i=>this.subscription.add(i)),Oa("codecs",G.video.supportedCodecs)}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(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((0,f.filterChanged)()).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((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).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((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>I(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ha()}};var zt=require("@vkontakte/videoplayer-shared/es2015"),TC=`@vkontakte/videoplayer-core@${tu}`;
|