@vkontakte/videoplayer-core 2.0.139 → 2.0.140-dev.ab9700a9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +21 -21
- package/es2015.esm.js +21 -21
- package/es2018.cjs.js +21 -21
- package/es2018.esm.js +21 -21
- package/es2024.cjs.js +15 -15
- package/es2024.esm.js +21 -21
- package/esnext.cjs.js +15 -15
- package/esnext.esm.js +21 -21
- package/evergreen.esm.js +17 -17
- package/package.json +2 -2
- package/types/providers/DashProvider/lib/fetcher.d.ts +2 -1
- package/types/utils/qualityLimits.d.ts +0 -1
package/es2015.cjs.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
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.140-dev.ab9700a9.0
|
|
3
|
+
* Wed, 27 Aug 2025 11:50:09 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-140/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Yy=Object.create;var Wr=Object.defineProperty,Ky=Object.defineProperties,Xy=Object.getOwnPropertyDescriptor,Jy=Object.getOwnPropertyDescriptors,Zy=Object.getOwnPropertyNames,Ba=Object.getOwnPropertySymbols,eT=Object.getPrototypeOf,Lo=Object.prototype.hasOwnProperty,md=Object.prototype.propertyIsEnumerable;var tT=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var kt=Math.pow,fd=(s,e,t)=>e in s?Wr(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,C=(s,e)=>{for(var t in e||(e={}))Lo.call(e,t)&&fd(s,t,e[t]);if(Ba)for(var t of Ba(e))md.call(e,t)&&fd(s,t,e[t]);return s},j=(s,e)=>Ky(s,Jy(e));var bd=(s,e)=>{var t={};for(var i in s)Lo.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&Ba)for(var i of Ba(s))e.indexOf(i)<0&&md.call(s,i)&&(t[i]=s[i]);return t};var v=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),iT=(s,e)=>{for(var t in e)Wr(s,t,{get:e[t],enumerable:!0})},gd=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Zy(e))!Lo.call(s,r)&&r!==t&&Wr(s,r,{get:()=>e[r],enumerable:!(i=Xy(e,r))||i.enumerable});return s};var Y=(s,e,t)=>(t=s!=null?Yy(eT(s)):{},gd(e||!s||!s.__esModule?Wr(t,"default",{value:s,enumerable:!0}):t,s)),rT=s=>gd(Wr({},"__esModule",{value:!0}),s);var R=(s,e,t)=>new Promise((i,r)=>{var a=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(a,n);o((t=t.apply(s,e)).next())}),Pi=function(s,e){this[0]=s,this[1]=e},oe=(s,e,t)=>{var i=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Pi,f=c.done;Promise.resolve(d?o[0]:o).then(p=>d?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:f})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>a[n]=o=>new Promise((u,l)=>i(n,o,u,l)),a={};return t=t.apply(s,e),a[tT("asyncIterator")]=()=>a,r("next"),r("throw"),r("return"),a};var Ae=v((Mo,vd)=>{"use strict";var Yr=function(s){return s&&s.Math===Math&&s};vd.exports=Yr(typeof globalThis=="object"&&globalThis)||Yr(typeof window=="object"&&window)||Yr(typeof self=="object"&&self)||Yr(typeof global=="object"&&global)||Yr(typeof Mo=="object"&&Mo)||function(){return this}()||Function("return this")()});var Me=v((z$,Sd)=>{"use strict";Sd.exports=function(s){try{return!!s()}catch(e){return!0}}});var Kr=v((Y$,yd)=>{"use strict";var sT=Me();yd.exports=!sT(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Do=v((K$,xd)=>{"use strict";var aT=Kr(),Ed=Function.prototype,Td=Ed.apply,Id=Ed.call;xd.exports=typeof Reflect=="object"&&Reflect.apply||(aT?Id.bind(Td):function(){return Id.apply(Td,arguments)})});var De=v((X$,Pd)=>{"use strict";var wd=Kr(),Ad=Function.prototype,Co=Ad.call,nT=wd&&Ad.bind.bind(Co,Co);Pd.exports=wd?nT:function(s){return function(){return Co.apply(s,arguments)}}});var Ri=v((J$,kd)=>{"use strict";var Rd=De(),oT=Rd({}.toString),uT=Rd("".slice);kd.exports=function(s){return uT(oT(s),8,-1)}});var Bo=v((Z$,Ld)=>{"use strict";var lT=Ri(),cT=De();Ld.exports=function(s){if(lT(s)==="Function")return cT(s)}});var Pe=v((eM,$d)=>{"use strict";var Vo=typeof document=="object"&&document.all;$d.exports=typeof Vo=="undefined"&&Vo!==void 0?function(s){return typeof s=="function"||s===Vo}:function(s){return typeof s=="function"}});var rt=v((tM,Md)=>{"use strict";var dT=Me();Md.exports=!dT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var st=v((iM,Dd)=>{"use strict";var pT=Kr(),Oa=Function.prototype.call;Dd.exports=pT?Oa.bind(Oa):function(){return Oa.apply(Oa,arguments)}});var _o=v(Vd=>{"use strict";var Cd={}.propertyIsEnumerable,Bd=Object.getOwnPropertyDescriptor,hT=Bd&&!Cd.call({1:2},1);Vd.f=hT?function(e){var t=Bd(this,e);return!!t&&t.enumerable}:Cd});var Xr=v((sM,_d)=>{"use strict";_d.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var Fd=v((aM,Od)=>{"use strict";var fT=De(),mT=Me(),bT=Ri(),Oo=Object,gT=fT("".split);Od.exports=mT(function(){return!Oo("z").propertyIsEnumerable(0)})?function(s){return bT(s)==="String"?gT(s,""):Oo(s)}:Oo});var Jr=v((nM,Nd)=>{"use strict";Nd.exports=function(s){return s==null}});var ui=v((oM,qd)=>{"use strict";var vT=Jr(),ST=TypeError;qd.exports=function(s){if(vT(s))throw new ST("Can't call method on "+s);return s}});var ki=v((uM,Ud)=>{"use strict";var yT=Fd(),TT=ui();Ud.exports=function(s){return yT(TT(s))}});var Ge=v((lM,Hd)=>{"use strict";var IT=Pe();Hd.exports=function(s){return typeof s=="object"?s!==null:IT(s)}});var Li=v((cM,jd)=>{"use strict";jd.exports={}});var Ht=v((dM,Wd)=>{"use strict";var Fo=Li(),No=Ae(),ET=Pe(),Qd=function(s){return ET(s)?s:void 0};Wd.exports=function(s,e){return arguments.length<2?Qd(Fo[s])||Qd(No[s]):Fo[s]&&Fo[s][e]||No[s]&&No[s][e]}});var Zr=v((pM,Gd)=>{"use strict";var xT=De();Gd.exports=xT({}.isPrototypeOf)});var $i=v((hM,Kd)=>{"use strict";var wT=Ae(),zd=wT.navigator,Yd=zd&&zd.userAgent;Kd.exports=Yd?String(Yd):""});var Uo=v((fM,ip)=>{"use strict";var tp=Ae(),qo=$i(),Xd=tp.process,Jd=tp.Deno,Zd=Xd&&Xd.versions||Jd&&Jd.version,ep=Zd&&Zd.v8,yt,Fa;ep&&(yt=ep.split("."),Fa=yt[0]>0&&yt[0]<4?1:+(yt[0]+yt[1]));!Fa&&qo&&(yt=qo.match(/Edge\/(\d+)/),(!yt||yt[1]>=74)&&(yt=qo.match(/Chrome\/(\d+)/),yt&&(Fa=+yt[1])));ip.exports=Fa});var Ho=v((mM,sp)=>{"use strict";var rp=Uo(),AT=Me(),PT=Ae(),RT=PT.String;sp.exports=!!Object.getOwnPropertySymbols&&!AT(function(){var s=Symbol("symbol detection");return!RT(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&rp&&rp<41})});var jo=v((bM,ap)=>{"use strict";var kT=Ho();ap.exports=kT&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Qo=v((gM,np)=>{"use strict";var LT=Ht(),$T=Pe(),MT=Zr(),DT=jo(),CT=Object;np.exports=DT?function(s){return typeof s=="symbol"}:function(s){var e=LT("Symbol");return $T(e)&&MT(e.prototype,CT(s))}});var es=v((vM,op)=>{"use strict";var BT=String;op.exports=function(s){try{return BT(s)}catch(e){return"Object"}}});var $t=v((SM,up)=>{"use strict";var VT=Pe(),_T=es(),OT=TypeError;up.exports=function(s){if(VT(s))return s;throw new OT(_T(s)+" is not a function")}});var ts=v((yM,lp)=>{"use strict";var FT=$t(),NT=Jr();lp.exports=function(s,e){var t=s[e];return NT(t)?void 0:FT(t)}});var dp=v((TM,cp)=>{"use strict";var Wo=st(),Go=Pe(),zo=Ge(),qT=TypeError;cp.exports=function(s,e){var t,i;if(e==="string"&&Go(t=s.toString)&&!zo(i=Wo(t,s))||Go(t=s.valueOf)&&!zo(i=Wo(t,s))||e!=="string"&&Go(t=s.toString)&&!zo(i=Wo(t,s)))return i;throw new qT("Can't convert object to primitive value")}});var Tt=v((IM,pp)=>{"use strict";pp.exports=!0});var mp=v((EM,fp)=>{"use strict";var hp=Ae(),UT=Object.defineProperty;fp.exports=function(s,e){try{UT(hp,s,{value:e,configurable:!0,writable:!0})}catch(t){hp[s]=e}return e}});var is=v((xM,vp)=>{"use strict";var HT=Tt(),jT=Ae(),QT=mp(),bp="__core-js_shared__",gp=vp.exports=jT[bp]||QT(bp,{});(gp.versions||(gp.versions=[])).push({version:"3.43.0",mode:HT?"pure":"global",copyright:"\xA9 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 Yo=v((wM,yp)=>{"use strict";var Sp=is();yp.exports=function(s,e){return Sp[s]||(Sp[s]=e||{})}});var rr=v((AM,Tp)=>{"use strict";var WT=ui(),GT=Object;Tp.exports=function(s){return GT(WT(s))}});var It=v((PM,Ip)=>{"use strict";var zT=De(),YT=rr(),KT=zT({}.hasOwnProperty);Ip.exports=Object.hasOwn||function(e,t){return KT(YT(e),t)}});var Ko=v((RM,Ep)=>{"use strict";var XT=De(),JT=0,ZT=Math.random(),eI=XT(1.1.toString);Ep.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+eI(++JT+ZT,36)}});var Fe=v((kM,wp)=>{"use strict";var tI=Ae(),iI=Yo(),xp=It(),rI=Ko(),sI=Ho(),aI=jo(),sr=tI.Symbol,Xo=iI("wks"),nI=aI?sr.for||sr:sr&&sr.withoutSetter||rI;wp.exports=function(s){return xp(Xo,s)||(Xo[s]=sI&&xp(sr,s)?sr[s]:nI("Symbol."+s)),Xo[s]}});var kp=v((LM,Rp)=>{"use strict";var oI=st(),Ap=Ge(),Pp=Qo(),uI=ts(),lI=dp(),cI=Fe(),dI=TypeError,pI=cI("toPrimitive");Rp.exports=function(s,e){if(!Ap(s)||Pp(s))return s;var t=uI(s,pI),i;if(t){if(e===void 0&&(e="default"),i=oI(t,s,e),!Ap(i)||Pp(i))return i;throw new dI("Can't convert object to primitive value")}return e===void 0&&(e="number"),lI(s,e)}});var Jo=v(($M,Lp)=>{"use strict";var hI=kp(),fI=Qo();Lp.exports=function(s){var e=hI(s,"string");return fI(e)?e:e+""}});var Na=v((MM,Mp)=>{"use strict";var mI=Ae(),$p=Ge(),Zo=mI.document,bI=$p(Zo)&&$p(Zo.createElement);Mp.exports=function(s){return bI?Zo.createElement(s):{}}});var eu=v((DM,Dp)=>{"use strict";var gI=rt(),vI=Me(),SI=Na();Dp.exports=!gI&&!vI(function(){return Object.defineProperty(SI("div"),"a",{get:function(){return 7}}).a!==7})});var Vp=v(Bp=>{"use strict";var yI=rt(),TI=st(),II=_o(),EI=Xr(),xI=ki(),wI=Jo(),AI=It(),PI=eu(),Cp=Object.getOwnPropertyDescriptor;Bp.f=yI?Cp:function(e,t){if(e=xI(e),t=wI(t),PI)try{return Cp(e,t)}catch(i){}if(AI(e,t))return EI(!TI(II.f,e,t),e[t])}});var tu=v((BM,_p)=>{"use strict";var RI=Me(),kI=Pe(),LI=/#|\.prototype\./,rs=function(s,e){var t=MI[$I(s)];return t===CI?!0:t===DI?!1:kI(e)?RI(e):!!e},$I=rs.normalize=function(s){return String(s).replace(LI,".").toLowerCase()},MI=rs.data={},DI=rs.NATIVE="N",CI=rs.POLYFILL="P";_p.exports=rs});var ar=v((VM,Fp)=>{"use strict";var Op=Bo(),BI=$t(),VI=Kr(),_I=Op(Op.bind);Fp.exports=function(s,e){return BI(s),e===void 0?s:VI?_I(s,e):function(){return s.apply(e,arguments)}}});var iu=v((_M,Np)=>{"use strict";var OI=rt(),FI=Me();Np.exports=OI&&FI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Mt=v((OM,qp)=>{"use strict";var NI=Ge(),qI=String,UI=TypeError;qp.exports=function(s){if(NI(s))return s;throw new UI(qI(s)+" is not an object")}});var Mi=v(Hp=>{"use strict";var HI=rt(),jI=eu(),QI=iu(),qa=Mt(),Up=Jo(),WI=TypeError,ru=Object.defineProperty,GI=Object.getOwnPropertyDescriptor,su="enumerable",au="configurable",nu="writable";Hp.f=HI?QI?function(e,t,i){if(qa(e),t=Up(t),qa(i),typeof e=="function"&&t==="prototype"&&"value"in i&&nu in i&&!i[nu]){var r=GI(e,t);r&&r[nu]&&(e[t]=i.value,i={configurable:au in i?i[au]:r[au],enumerable:su in i?i[su]:r[su],writable:!1})}return ru(e,t,i)}:ru:function(e,t,i){if(qa(e),t=Up(t),qa(i),jI)try{return ru(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new WI("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var nr=v((NM,jp)=>{"use strict";var zI=rt(),YI=Mi(),KI=Xr();jp.exports=zI?function(s,e,t){return YI.f(s,e,KI(1,t))}:function(s,e,t){return s[e]=t,s}});var Le=v((qM,Wp)=>{"use strict";var ss=Ae(),XI=Do(),JI=Bo(),ZI=Pe(),eE=Vp().f,tE=tu(),or=Li(),iE=ar(),ur=nr(),Qp=It();is();var rE=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return XI(s,this,arguments)};return e.prototype=s.prototype,e};Wp.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ss:r?ss[t]:ss[t]&&ss[t].prototype,o=i?or:or[t]||ur(or,t,{})[t],u=o.prototype,l,c,d,f,p,h,b,S,g;for(f in e)l=tE(i?f:t+(r?".":"#")+f,s.forced),c=!l&&n&&Qp(n,f),h=o[f],c&&(s.dontCallGetSet?(g=eE(n,f),b=g&&g.value):b=n[f]),p=c&&b?b:e[f],!(!l&&!a&&typeof h==typeof p)&&(s.bind&&c?S=iE(p,ss):s.wrap&&c?S=rE(p):a&&ZI(p)?S=JI(p):S=p,(s.sham||p&&p.sham||h&&h.sham)&&ur(S,"sham",!0),ur(o,f,S),a&&(d=t+"Prototype",Qp(or,d)||ur(or,d,{}),ur(or[d],f,p),s.real&&u&&(l||!u[f])&&ur(u,f,p)))}});var Ua=v((UM,zp)=>{"use strict";var sE=Yo(),aE=Ko(),Gp=sE("keys");zp.exports=function(s){return Gp[s]||(Gp[s]=aE(s))}});var Kp=v((HM,Yp)=>{"use strict";var nE=Me();Yp.exports=!nE(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Ha=v((jM,Jp)=>{"use strict";var oE=It(),uE=Pe(),lE=rr(),cE=Ua(),dE=Kp(),Xp=cE("IE_PROTO"),ou=Object,pE=ou.prototype;Jp.exports=dE?ou.getPrototypeOf:function(s){var e=lE(s);if(oE(e,Xp))return e[Xp];var t=e.constructor;return uE(t)&&e instanceof t?t.prototype:e instanceof ou?pE:null}});var eh=v((QM,Zp)=>{"use strict";var hE=Math.ceil,fE=Math.floor;Zp.exports=Math.trunc||function(e){var t=+e;return(t>0?fE:hE)(t)}});var as=v((WM,th)=>{"use strict";var mE=eh();th.exports=function(s){var e=+s;return e!==e||e===0?0:mE(e)}});var rh=v((GM,ih)=>{"use strict";var bE=as(),gE=Math.max,vE=Math.min;ih.exports=function(s,e){var t=bE(s);return t<0?gE(t+e,0):vE(t,e)}});var uu=v((zM,sh)=>{"use strict";var SE=as(),yE=Math.min;sh.exports=function(s){var e=SE(s);return e>0?yE(e,9007199254740991):0}});var lr=v((YM,ah)=>{"use strict";var TE=uu();ah.exports=function(s){return TE(s.length)}});var lu=v((KM,oh)=>{"use strict";var IE=ki(),EE=rh(),xE=lr(),nh=function(s){return function(e,t,i){var r=IE(e),a=xE(r);if(a===0)return!s&&-1;var n=EE(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};oh.exports={includes:nh(!0),indexOf:nh(!1)}});var ja=v((XM,uh)=>{"use strict";uh.exports={}});var dh=v((JM,ch)=>{"use strict";var wE=De(),cu=It(),AE=ki(),PE=lu().indexOf,RE=ja(),lh=wE([].push);ch.exports=function(s,e){var t=AE(s),i=0,r=[],a;for(a in t)!cu(RE,a)&&cu(t,a)&&lh(r,a);for(;e.length>i;)cu(t,a=e[i++])&&(~PE(r,a)||lh(r,a));return r}});var du=v((ZM,ph)=>{"use strict";ph.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var pu=v((eD,hh)=>{"use strict";var kE=dh(),LE=du();hh.exports=Object.keys||function(e){return kE(e,LE)}});var hu=v((tD,vh)=>{"use strict";var mh=rt(),$E=Me(),bh=De(),ME=Ha(),DE=pu(),CE=ki(),BE=_o().f,gh=bh(BE),VE=bh([].push),_E=mh&&$E(function(){var s=Object.create(null);return s[2]=2,!gh(s,2)}),fh=function(s){return function(e){for(var t=CE(e),i=DE(t),r=_E&&ME(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!mh||(r?u in t:gh(t,u)))&&VE(o,s?[u,t[u]]:t[u]);return o}};vh.exports={entries:fh(!0),values:fh(!1)}});var Sh=v(()=>{"use strict";var OE=Le(),FE=hu().values;OE({target:"Object",stat:!0},{values:function(e){return FE(e)}})});var Th=v((sD,yh)=>{"use strict";Sh();var NE=Li();yh.exports=NE.Object.values});var Eh=v((aD,Ih)=>{"use strict";var qE=Th();Ih.exports=qE});var Di=v((nD,xh)=>{"use strict";var UE=Eh();xh.exports=UE});var ns=v((oD,wh)=>{"use strict";wh.exports=function(){}});var Ah=v(()=>{"use strict";var HE=Le(),jE=lu().includes,QE=Me(),WE=ns(),GE=QE(function(){return!Array(1).includes()});HE({target:"Array",proto:!0,forced:GE},{includes:function(e){return jE(this,e,arguments.length>1?arguments[1]:void 0)}});WE("includes")});var li=v((cD,Ph)=>{"use strict";var zE=Ht();Ph.exports=zE});var kh=v((dD,Rh)=>{"use strict";Ah();var YE=li();Rh.exports=YE("Array","includes")});var $h=v((pD,Lh)=>{"use strict";var KE=kh();Lh.exports=KE});var je=v((hD,Mh)=>{"use strict";var XE=$h();Mh.exports=XE});var Ch=v(()=>{"use strict";var ZE=Le(),ex=hu().entries;ZE({target:"Object",stat:!0},{entries:function(e){return ex(e)}})});var Vh=v((AD,Bh)=>{"use strict";Ch();var tx=Li();Bh.exports=tx.Object.entries});var Oh=v((PD,_h)=>{"use strict";var ix=Vh();_h.exports=ix});var cr=v((RD,Fh)=>{"use strict";var rx=Oh();Fh.exports=rx});var Ci=v((kD,Nh)=>{"use strict";Nh.exports={}});var Hh=v((LD,Uh)=>{"use strict";var sx=Ae(),ax=Pe(),qh=sx.WeakMap;Uh.exports=ax(qh)&&/native code/.test(String(qh))});var gu=v(($D,Wh)=>{"use strict";var nx=Hh(),Qh=Ae(),ox=Ge(),ux=nr(),fu=It(),mu=is(),lx=Ua(),cx=ja(),jh="Object already initialized",bu=Qh.TypeError,dx=Qh.WeakMap,Wa,os,Ga,px=function(s){return Ga(s)?os(s):Wa(s,{})},hx=function(s){return function(e){var t;if(!ox(e)||(t=os(e)).type!==s)throw new bu("Incompatible receiver, "+s+" required");return t}};nx||mu.state?(Et=mu.state||(mu.state=new dx),Et.get=Et.get,Et.has=Et.has,Et.set=Et.set,Wa=function(s,e){if(Et.has(s))throw new bu(jh);return e.facade=s,Et.set(s,e),e},os=function(s){return Et.get(s)||{}},Ga=function(s){return Et.has(s)}):(Bi=lx("state"),cx[Bi]=!0,Wa=function(s,e){if(fu(s,Bi))throw new bu(jh);return e.facade=s,ux(s,Bi,e),e},os=function(s){return fu(s,Bi)?s[Bi]:{}},Ga=function(s){return fu(s,Bi)});var Et,Bi;Wh.exports={set:Wa,get:os,has:Ga,enforce:px,getterFor:hx}});var yu=v((MD,zh)=>{"use strict";var vu=rt(),fx=It(),Gh=Function.prototype,mx=vu&&Object.getOwnPropertyDescriptor,Su=fx(Gh,"name"),bx=Su&&function(){}.name==="something",gx=Su&&(!vu||vu&&mx(Gh,"name").configurable);zh.exports={EXISTS:Su,PROPER:bx,CONFIGURABLE:gx}});var Kh=v(Yh=>{"use strict";var vx=rt(),Sx=iu(),yx=Mi(),Tx=Mt(),Ix=ki(),Ex=pu();Yh.f=vx&&!Sx?Object.defineProperties:function(e,t){Tx(e);for(var i=Ix(t),r=Ex(t),a=r.length,n=0,o;a>n;)yx.f(e,o=r[n++],i[o]);return e}});var Tu=v((CD,Xh)=>{"use strict";var xx=Ht();Xh.exports=xx("document","documentElement")});var wu=v((BD,af)=>{"use strict";var wx=Mt(),Ax=Kh(),Jh=du(),Px=ja(),Rx=Tu(),kx=Na(),Lx=Ua(),Zh=">",ef="<",Eu="prototype",xu="script",rf=Lx("IE_PROTO"),Iu=function(){},sf=function(s){return ef+xu+Zh+s+ef+"/"+xu+Zh},tf=function(s){s.write(sf("")),s.close();var e=s.parentWindow.Object;return s=null,e},$x=function(){var s=kx("iframe"),e="java"+xu+":",t;return s.style.display="none",Rx.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(sf("document.F=Object")),t.close(),t.F},za,Ya=function(){try{za=new ActiveXObject("htmlfile")}catch(e){}Ya=typeof document!="undefined"?document.domain&&za?tf(za):$x():tf(za);for(var s=Jh.length;s--;)delete Ya[Eu][Jh[s]];return Ya()};Px[rf]=!0;af.exports=Object.create||function(e,t){var i;return e!==null?(Iu[Eu]=wx(e),i=new Iu,Iu[Eu]=null,i[rf]=e):i=Ya(),t===void 0?i:Ax.f(i,t)}});var dr=v((VD,nf)=>{"use strict";var Mx=nr();nf.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Mx(s,e,t),s}});var ku=v((_D,lf)=>{"use strict";var Dx=Me(),Cx=Pe(),Bx=Ge(),Vx=wu(),of=Ha(),_x=dr(),Ox=Fe(),Fx=Tt(),Ru=Ox("iterator"),uf=!1,jt,Au,Pu;[].keys&&(Pu=[].keys(),"next"in Pu?(Au=of(of(Pu)),Au!==Object.prototype&&(jt=Au)):uf=!0);var Nx=!Bx(jt)||Dx(function(){var s={};return jt[Ru].call(s)!==s});Nx?jt={}:Fx&&(jt=Vx(jt));Cx(jt[Ru])||_x(jt,Ru,function(){return this});lf.exports={IteratorPrototype:jt,BUGGY_SAFARI_ITERATORS:uf}});var Ka=v((OD,df)=>{"use strict";var qx=Fe(),Ux=qx("toStringTag"),cf={};cf[Ux]="z";df.exports=String(cf)==="[object z]"});var us=v((FD,pf)=>{"use strict";var Hx=Ka(),jx=Pe(),Xa=Ri(),Qx=Fe(),Wx=Qx("toStringTag"),Gx=Object,zx=Xa(function(){return arguments}())==="Arguments",Yx=function(s,e){try{return s[e]}catch(t){}};pf.exports=Hx?Xa:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Yx(e=Gx(s),Wx))=="string"?t:zx?Xa(e):(i=Xa(e))==="Object"&&jx(e.callee)?"Arguments":i}});var ff=v((ND,hf)=>{"use strict";var Kx=Ka(),Xx=us();hf.exports=Kx?{}.toString:function(){return"[object "+Xx(this)+"]"}});var ls=v((qD,bf)=>{"use strict";var Jx=Ka(),Zx=Mi().f,ew=nr(),tw=It(),iw=ff(),rw=Fe(),mf=rw("toStringTag");bf.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(tw(r,mf)||Zx(r,mf,{configurable:!0,value:e}),i&&!Jx&&ew(r,"toString",iw))}});var vf=v((UD,gf)=>{"use strict";var sw=ku().IteratorPrototype,aw=wu(),nw=Xr(),ow=ls(),uw=Ci(),lw=function(){return this};gf.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=aw(sw,{next:nw(+!i,t)}),ow(s,r,!1,!0),uw[r]=lw,s}});var yf=v((HD,Sf)=>{"use strict";var cw=De(),dw=$t();Sf.exports=function(s,e,t){try{return cw(dw(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var If=v((jD,Tf)=>{"use strict";var pw=Ge();Tf.exports=function(s){return pw(s)||s===null}});var xf=v((QD,Ef)=>{"use strict";var hw=If(),fw=String,mw=TypeError;Ef.exports=function(s){if(hw(s))return s;throw new mw("Can't set "+fw(s)+" as a prototype")}});var Lu=v((WD,wf)=>{"use strict";var bw=yf(),gw=Ge(),vw=ui(),Sw=xf();wf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=bw(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return vw(r),Sw(a),gw(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Vf=v((GD,Bf)=>{"use strict";var yw=Le(),Tw=st(),Ja=Tt(),Df=yu(),Iw=Pe(),Ew=vf(),Af=Ha(),Pf=Lu(),xw=ls(),ww=nr(),$u=dr(),Aw=Fe(),Rf=Ci(),Cf=ku(),Pw=Df.PROPER,Rw=Df.CONFIGURABLE,kf=Cf.IteratorPrototype,Za=Cf.BUGGY_SAFARI_ITERATORS,cs=Aw("iterator"),Lf="keys",ds="values",$f="entries",Mf=function(){return this};Bf.exports=function(s,e,t,i,r,a,n){Ew(t,e,i);var o=function(g){if(g===r&&f)return f;if(!Za&&g&&g in c)return c[g];switch(g){case Lf:return function(){return new t(this,g)};case ds:return function(){return new t(this,g)};case $f:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=s.prototype,d=c[cs]||c["@@iterator"]||r&&c[r],f=!Za&&d||o(r),p=e==="Array"&&c.entries||d,h,b,S;if(p&&(h=Af(p.call(new s)),h!==Object.prototype&&h.next&&(!Ja&&Af(h)!==kf&&(Pf?Pf(h,kf):Iw(h[cs])||$u(h,cs,Mf)),xw(h,u,!0,!0),Ja&&(Rf[u]=Mf))),Pw&&r===ds&&d&&d.name!==ds&&(!Ja&&Rw?ww(c,"name",ds):(l=!0,f=function(){return Tw(d,this)})),r)if(b={values:o(ds),keys:a?f:o(Lf),entries:o($f)},n)for(S in b)(Za||l||!(S in c))&&$u(c,S,b[S]);else yw({target:e,proto:!0,forced:Za||l},b);return(!Ja||n)&&c[cs]!==f&&$u(c,cs,f,{name:r}),Rf[e]=f,b}});var Of=v((zD,_f)=>{"use strict";_f.exports=function(s,e){return{value:s,done:e}}});var Du=v((YD,Hf)=>{"use strict";var kw=ki(),Mu=ns(),Ff=Ci(),qf=gu(),Lw=Mi().f,$w=Vf(),en=Of(),Mw=Tt(),Dw=rt(),Uf="Array Iterator",Cw=qf.set,Bw=qf.getterFor(Uf);Hf.exports=$w(Array,"Array",function(s,e){Cw(this,{type:Uf,target:kw(s),index:0,kind:e})},function(){var s=Bw(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,en(void 0,!0);switch(s.kind){case"keys":return en(t,!1);case"values":return en(e[t],!1)}return en([t,e[t]],!1)},"values");var Nf=Ff.Arguments=Ff.Array;Mu("keys");Mu("values");Mu("entries");if(!Mw&&Dw&&Nf.name!=="values")try{Lw(Nf,"name",{value:"values"})}catch(s){}});var Qf=v((KD,jf)=>{"use strict";var Vw=Fe(),_w=Ci(),Ow=Vw("iterator"),Fw=Array.prototype;jf.exports=function(s){return s!==void 0&&(_w.Array===s||Fw[Ow]===s)}});var Cu=v((XD,Gf)=>{"use strict";var Nw=us(),Wf=ts(),qw=Jr(),Uw=Ci(),Hw=Fe(),jw=Hw("iterator");Gf.exports=function(s){if(!qw(s))return Wf(s,jw)||Wf(s,"@@iterator")||Uw[Nw(s)]}});var Yf=v((JD,zf)=>{"use strict";var Qw=st(),Ww=$t(),Gw=Mt(),zw=es(),Yw=Cu(),Kw=TypeError;zf.exports=function(s,e){var t=arguments.length<2?Yw(s):e;if(Ww(t))return Gw(Qw(t,s));throw new Kw(zw(s)+" is not iterable")}});var Jf=v((ZD,Xf)=>{"use strict";var Xw=st(),Kf=Mt(),Jw=ts();Xf.exports=function(s,e,t){var i,r;Kf(s);try{if(i=Jw(s,"return"),!i){if(e==="throw")throw t;return t}i=Xw(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Kf(i),t}});var rn=v((eC,im)=>{"use strict";var Zw=ar(),eA=st(),tA=Mt(),iA=es(),rA=Qf(),sA=lr(),Zf=Zr(),aA=Yf(),nA=Cu(),em=Jf(),oA=TypeError,tn=function(s,e){this.stopped=s,this.result=e},tm=tn.prototype;im.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Zw(e,i),l,c,d,f,p,h,b,S=function(y){return l&&em(l,"normal"),new tn(!0,y)},g=function(y){return r?(tA(y),o?u(y[0],y[1],S):u(y[0],y[1])):o?u(y,S):u(y)};if(a)l=s.iterator;else if(n)l=s;else{if(c=nA(s),!c)throw new oA(iA(s)+" is not iterable");if(rA(c)){for(d=0,f=sA(s);f>d;d++)if(p=g(s[d]),p&&Zf(tm,p))return p;return new tn(!1)}l=aA(s,c)}for(h=a?s.next:l.next;!(b=eA(h,l)).done;){try{p=g(b.value)}catch(y){em(l,"throw",y)}if(typeof p=="object"&&p&&Zf(tm,p))return p}return new tn(!1)}});var sm=v((tC,rm)=>{"use strict";var uA=rt(),lA=Mi(),cA=Xr();rm.exports=function(s,e,t){uA?lA.f(s,e,cA(0,t)):s[e]=t}});var am=v(()=>{"use strict";var dA=Le(),pA=rn(),hA=sm();dA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return pA(e,function(i,r){hA(t,i,r)},{AS_ENTRIES:!0}),t}})});var om=v((sC,nm)=>{"use strict";Du();am();var fA=Li();nm.exports=fA.Object.fromEntries});var lm=v((aC,um)=>{"use strict";um.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 dm=v(()=>{"use strict";Du();var mA=lm(),bA=Ae(),gA=ls(),cm=Ci();for(sn in mA)gA(bA[sn],sn),cm[sn]=cm.Array;var sn});var hm=v((uC,pm)=>{"use strict";var vA=om();dm();pm.exports=vA});var Bu=v((lC,fm)=>{"use strict";var SA=hm();fm.exports=SA});var mm=v(()=>{"use strict"});var Vu=v((pC,bm)=>{"use strict";var ps=Ae(),yA=$i(),TA=Ri(),an=function(s){return yA.slice(0,s.length)===s};bm.exports=function(){return an("Bun/")?"BUN":an("Cloudflare-Workers")?"CLOUDFLARE":an("Deno/")?"DENO":an("Node.js/")?"NODE":ps.Bun&&typeof Bun.version=="string"?"BUN":ps.Deno&&typeof Deno.version=="object"?"DENO":TA(ps.process)==="process"?"NODE":ps.window&&ps.document?"BROWSER":"REST"}()});var nn=v((hC,gm)=>{"use strict";var IA=Vu();gm.exports=IA==="NODE"});var Sm=v((fC,vm)=>{"use strict";var EA=Mi();vm.exports=function(s,e,t){return EA.f(s,e,t)}});var Im=v((mC,Tm)=>{"use strict";var xA=Ht(),wA=Sm(),AA=Fe(),PA=rt(),ym=AA("species");Tm.exports=function(s){var e=xA(s);PA&&e&&!e[ym]&&wA(e,ym,{configurable:!0,get:function(){return this}})}});var xm=v((bC,Em)=>{"use strict";var RA=Zr(),kA=TypeError;Em.exports=function(s,e){if(RA(e,s))return s;throw new kA("Incorrect invocation")}});var Ou=v((gC,wm)=>{"use strict";var LA=De(),$A=Pe(),_u=is(),MA=LA(Function.toString);$A(_u.inspectSource)||(_u.inspectSource=function(s){return MA(s)});wm.exports=_u.inspectSource});var Nu=v((vC,Lm)=>{"use strict";var DA=De(),CA=Me(),Am=Pe(),BA=us(),VA=Ht(),_A=Ou(),Pm=function(){},Rm=VA("Reflect","construct"),Fu=/^\s*(?:class|function)\b/,OA=DA(Fu.exec),FA=!Fu.test(Pm),hs=function(e){if(!Am(e))return!1;try{return Rm(Pm,[],e),!0}catch(t){return!1}},km=function(e){if(!Am(e))return!1;switch(BA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return FA||!!OA(Fu,_A(e))}catch(t){return!0}};km.sham=!0;Lm.exports=!Rm||CA(function(){var s;return hs(hs.call)||!hs(Object)||!hs(function(){s=!0})||s})?km:hs});var Mm=v((SC,$m)=>{"use strict";var NA=Nu(),qA=es(),UA=TypeError;$m.exports=function(s){if(NA(s))return s;throw new UA(qA(s)+" is not a constructor")}});var qu=v((yC,Cm)=>{"use strict";var Dm=Mt(),HA=Mm(),jA=Jr(),QA=Fe(),WA=QA("species");Cm.exports=function(s,e){var t=Dm(s).constructor,i;return t===void 0||jA(i=Dm(t)[WA])?e:HA(i)}});var Vm=v((TC,Bm)=>{"use strict";var GA=De();Bm.exports=GA([].slice)});var Om=v((IC,_m)=>{"use strict";var zA=TypeError;_m.exports=function(s,e){if(s<e)throw new zA("Not enough arguments");return s}});var Uu=v((EC,Fm)=>{"use strict";var YA=$i();Fm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(YA)});var Xu=v((xC,zm)=>{"use strict";var at=Ae(),KA=Do(),XA=ar(),Nm=Pe(),JA=It(),Gm=Me(),qm=Tu(),ZA=Vm(),Um=Na(),eP=Om(),tP=Uu(),iP=nn(),zu=at.setImmediate,Yu=at.clearImmediate,rP=at.process,Hu=at.Dispatch,sP=at.Function,Hm=at.MessageChannel,aP=at.String,ju=0,fs={},jm="onreadystatechange",ms,Vi,Qu,Wu;Gm(function(){ms=at.location});var Ku=function(s){if(JA(fs,s)){var e=fs[s];delete fs[s],e()}},Gu=function(s){return function(){Ku(s)}},Qm=function(s){Ku(s.data)},Wm=function(s){at.postMessage(aP(s),ms.protocol+"//"+ms.host)};(!zu||!Yu)&&(zu=function(e){eP(arguments.length,1);var t=Nm(e)?e:sP(e),i=ZA(arguments,1);return fs[++ju]=function(){KA(t,void 0,i)},Vi(ju),ju},Yu=function(e){delete fs[e]},iP?Vi=function(s){rP.nextTick(Gu(s))}:Hu&&Hu.now?Vi=function(s){Hu.now(Gu(s))}:Hm&&!tP?(Qu=new Hm,Wu=Qu.port2,Qu.port1.onmessage=Qm,Vi=XA(Wu.postMessage,Wu)):at.addEventListener&&Nm(at.postMessage)&&!at.importScripts&&ms&&ms.protocol!=="file:"&&!Gm(Wm)?(Vi=Wm,at.addEventListener("message",Qm,!1)):jm in Um("script")?Vi=function(s){qm.appendChild(Um("script"))[jm]=function(){qm.removeChild(this),Ku(s)}}:Vi=function(s){setTimeout(Gu(s),0)});zm.exports={set:zu,clear:Yu}});var Xm=v((wC,Km)=>{"use strict";var Ym=Ae(),nP=rt(),oP=Object.getOwnPropertyDescriptor;Km.exports=function(s){if(!nP)return Ym[s];var e=oP(Ym,s);return e&&e.value}});var Ju=v((AC,Zm)=>{"use strict";var Jm=function(){this.head=null,this.tail=null};Jm.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};Zm.exports=Jm});var tb=v((PC,eb)=>{"use strict";var uP=$i();eb.exports=/ipad|iphone|ipod/i.test(uP)&&typeof Pebble!="undefined"});var rb=v((RC,ib)=>{"use strict";var lP=$i();ib.exports=/web0s(?!.*chrome)/i.test(lP)});var cb=v((kC,lb)=>{"use strict";var hr=Ae(),cP=Xm(),sb=ar(),Zu=Xu().set,dP=Ju(),pP=Uu(),hP=tb(),fP=rb(),el=nn(),ab=hr.MutationObserver||hr.WebKitMutationObserver,nb=hr.document,ob=hr.process,on=hr.Promise,rl=cP("queueMicrotask"),pr,tl,il,un,ub;rl||(bs=new dP,gs=function(){var s,e;for(el&&(s=ob.domain)&&s.exit();e=bs.get();)try{e()}catch(t){throw bs.head&&pr(),t}s&&s.enter()},!pP&&!el&&!fP&&ab&&nb?(tl=!0,il=nb.createTextNode(""),new ab(gs).observe(il,{characterData:!0}),pr=function(){il.data=tl=!tl}):!hP&&on&&on.resolve?(un=on.resolve(void 0),un.constructor=on,ub=sb(un.then,un),pr=function(){ub(gs)}):el?pr=function(){ob.nextTick(gs)}:(Zu=sb(Zu,hr),pr=function(){Zu(gs)}),rl=function(s){bs.head||pr(),bs.add(s)});var bs,gs;lb.exports=rl});var pb=v((LC,db)=>{"use strict";db.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var ln=v(($C,hb)=>{"use strict";hb.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var _i=v((MC,fb)=>{"use strict";var mP=Ae();fb.exports=mP.Promise});var fr=v((DC,vb)=>{"use strict";var bP=Ae(),vs=_i(),gP=Pe(),vP=tu(),SP=Ou(),yP=Fe(),mb=Vu(),TP=Tt(),sl=Uo(),bb=vs&&vs.prototype,IP=yP("species"),al=!1,gb=gP(bP.PromiseRejectionEvent),EP=vP("Promise",function(){var s=SP(vs),e=s!==String(vs);if(!e&&sl===66||TP&&!(bb.catch&&bb.finally))return!0;if(!sl||sl<51||!/native code/.test(s)){var t=new vs(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[IP]=i,al=t.then(function(){})instanceof i,!al)return!0}return!e&&(mb==="BROWSER"||mb==="DENO")&&!gb});vb.exports={CONSTRUCTOR:EP,REJECTION_EVENT:gb,SUBCLASSING:al}});var mr=v((CC,yb)=>{"use strict";var Sb=$t(),xP=TypeError,wP=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new xP("Bad Promise constructor");e=i,t=r}),this.resolve=Sb(e),this.reject=Sb(t)};yb.exports.f=function(s){return new wP(s)}});var Nb=v(()=>{"use strict";var AP=Le(),PP=Tt(),hn=nn(),ci=Ae(),RP=Li(),Sr=st(),Tb=dr(),Ib=Lu(),kP=ls(),LP=Im(),$P=$t(),pn=Pe(),MP=Ge(),DP=xm(),CP=qu(),Pb=Xu().set,cl=cb(),BP=pb(),VP=ln(),_P=Ju(),Rb=gu(),fn=_i(),dl=fr(),kb=mr(),mn="Promise",Lb=dl.CONSTRUCTOR,OP=dl.REJECTION_EVENT,FP=dl.SUBCLASSING,nl=Rb.getterFor(mn),NP=Rb.set,br=fn&&fn.prototype,Oi=fn,cn=br,$b=ci.TypeError,ol=ci.document,pl=ci.process,ul=kb.f,qP=ul,UP=!!(ol&&ol.createEvent&&ci.dispatchEvent),Mb="unhandledrejection",HP="rejectionhandled",Eb=0,Db=1,jP=2,hl=1,Cb=2,dn,xb,Bb,wb,Vb=function(s){var e;return MP(s)&&pn(e=s.then)?e:!1},_b=function(s,e){var t=e.value,i=e.state===Db,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,c;try{r?(i||(e.rejection===Cb&&WP(e),e.rejection=hl),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===s.promise?n(new $b("Promise-chain cycle")):(l=Vb(u))?Sr(l,u,a,n):a(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Ob=function(s,e){s.notified||(s.notified=!0,cl(function(){for(var t=s.reactions,i;i=t.get();)_b(i,s);s.notified=!1,e&&!s.rejection&&QP(s)}))},Fb=function(s,e,t){var i,r;UP?(i=ol.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),ci.dispatchEvent(i)):i={promise:e,reason:t},!OP&&(r=ci["on"+s])?r(i):s===Mb&&BP("Unhandled promise rejection",t)},QP=function(s){Sr(Pb,ci,function(){var e=s.facade,t=s.value,i=Ab(s),r;if(i&&(r=VP(function(){hn?pl.emit("unhandledRejection",t,e):Fb(Mb,e,t)}),s.rejection=hn||Ab(s)?Cb:hl,r.error))throw r.value})},Ab=function(s){return s.rejection!==hl&&!s.parent},WP=function(s){Sr(Pb,ci,function(){var e=s.facade;hn?pl.emit("rejectionHandled",e):Fb(HP,e,s.value)})},gr=function(s,e,t){return function(i){s(e,i,t)}},vr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=jP,Ob(s,!0))},ll=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new $b("Promise can't be resolved itself");var i=Vb(e);i?cl(function(){var r={done:!1};try{Sr(i,e,gr(ll,r,s),gr(vr,r,s))}catch(a){vr(r,a,s)}}):(s.value=e,s.state=Db,Ob(s,!1))}catch(r){vr({done:!1},r,s)}}};if(Lb&&(Oi=function(e){DP(this,cn),$P(e),Sr(dn,this);var t=nl(this);try{e(gr(ll,t),gr(vr,t))}catch(i){vr(t,i)}},cn=Oi.prototype,dn=function(e){NP(this,{type:mn,done:!1,notified:!1,parent:!1,reactions:new _P,rejection:!1,state:Eb,value:null})},dn.prototype=Tb(cn,"then",function(e,t){var i=nl(this),r=ul(CP(this,Oi));return i.parent=!0,r.ok=pn(e)?e:!0,r.fail=pn(t)&&t,r.domain=hn?pl.domain:void 0,i.state===Eb?i.reactions.add(r):cl(function(){_b(r,i)}),r.promise}),xb=function(){var s=new dn,e=nl(s);this.promise=s,this.resolve=gr(ll,e),this.reject=gr(vr,e)},kb.f=ul=function(s){return s===Oi||s===Bb?new xb(s):qP(s)},!PP&&pn(fn)&&br!==Object.prototype)){wb=br.then,FP||Tb(br,"then",function(e,t){var i=this;return new Oi(function(r,a){Sr(wb,i,r,a)}).then(e,t)},{unsafe:!0});try{delete br.constructor}catch(s){}Ib&&Ib(br,cn)}AP({global:!0,constructor:!0,wrap:!0,forced:Lb},{Promise:Oi});Bb=RP.Promise;kP(Oi,mn,!1,!0);LP(mn)});var Qb=v((_C,jb)=>{"use strict";var GP=Fe(),Ub=GP("iterator"),Hb=!1;try{qb=0,fl={next:function(){return{done:!!qb++}},return:function(){Hb=!0}},fl[Ub]=function(){return this},Array.from(fl,function(){throw 2})}catch(s){}var qb,fl;jb.exports=function(s,e){try{if(!e&&!Hb)return!1}catch(r){return!1}var t=!1;try{var i={};i[Ub]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var ml=v((OC,Wb)=>{"use strict";var zP=_i(),YP=Qb(),KP=fr().CONSTRUCTOR;Wb.exports=KP||!YP(function(s){zP.all(s).then(void 0,function(){})})});var Gb=v(()=>{"use strict";var XP=Le(),JP=st(),ZP=$t(),eR=mr(),tR=ln(),iR=rn(),rR=ml();XP({target:"Promise",stat:!0,forced:rR},{all:function(e){var t=this,i=eR.f(t),r=i.resolve,a=i.reject,n=tR(function(){var o=ZP(t.resolve),u=[],l=0,c=1;iR(e,function(d){var f=l++,p=!1;c++,JP(o,t,d).then(function(h){p||(p=!0,u[f]=h,--c||r(u))},a)}),--c||r(u)});return n.error&&a(n.value),i.promise}})});var Yb=v(()=>{"use strict";var sR=Le(),aR=Tt(),nR=fr().CONSTRUCTOR,gl=_i(),oR=Ht(),uR=Pe(),lR=dr(),zb=gl&&gl.prototype;sR({target:"Promise",proto:!0,forced:nR,real:!0},{catch:function(s){return this.then(void 0,s)}});!aR&&uR(gl)&&(bl=oR("Promise").prototype.catch,zb.catch!==bl&&lR(zb,"catch",bl,{unsafe:!0}));var bl});var Kb=v(()=>{"use strict";var cR=Le(),dR=st(),pR=$t(),hR=mr(),fR=ln(),mR=rn(),bR=ml();cR({target:"Promise",stat:!0,forced:bR},{race:function(e){var t=this,i=hR.f(t),r=i.reject,a=fR(function(){var n=pR(t.resolve);mR(e,function(o){dR(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Xb=v(()=>{"use strict";var gR=Le(),vR=mr(),SR=fr().CONSTRUCTOR;gR({target:"Promise",stat:!0,forced:SR},{reject:function(e){var t=vR.f(this),i=t.reject;return i(e),t.promise}})});var vl=v((GC,Jb)=>{"use strict";var yR=Mt(),TR=Ge(),IR=mr();Jb.exports=function(s,e){if(yR(s),TR(e)&&e.constructor===s)return e;var t=IR.f(s),i=t.resolve;return i(e),t.promise}});var tg=v(()=>{"use strict";var ER=Le(),xR=Ht(),Zb=Tt(),wR=_i(),eg=fr().CONSTRUCTOR,AR=vl(),PR=xR("Promise"),RR=Zb&&!eg;ER({target:"Promise",stat:!0,forced:Zb||eg},{resolve:function(e){return AR(RR&&this===PR?wR:this,e)}})});var ig=v(()=>{"use strict";Nb();Gb();Yb();Kb();Xb();tg()});var ng=v(()=>{"use strict";var kR=Le(),LR=Tt(),bn=_i(),$R=Me(),sg=Ht(),ag=Pe(),MR=qu(),rg=vl(),DR=dr(),yl=bn&&bn.prototype,CR=!!bn&&$R(function(){yl.finally.call({then:function(){}},function(){})});kR({target:"Promise",proto:!0,real:!0,forced:CR},{finally:function(s){var e=MR(this,sg("Promise")),t=ag(s);return this.then(t?function(i){return rg(e,s()).then(function(){return i})}:s,t?function(i){return rg(e,s()).then(function(){throw i})}:s)}});!LR&&ag(bn)&&(Sl=sg("Promise").prototype.finally,yl.finally!==Sl&&DR(yl,"finally",Sl,{unsafe:!0}));var Sl});var ug=v((e0,og)=>{"use strict";mm();ig();ng();var BR=li();og.exports=BR("Promise","finally")});var cg=v((t0,lg)=>{"use strict";var VR=ug();lg.exports=VR});var gn=v((i0,dg)=>{"use strict";var _R=cg();dg.exports=_R});var Pg=v(()=>{"use strict";var XR=Le(),JR=rr(),ZR=lr(),ek=as(),tk=ns();XR({target:"Array",proto:!0},{at:function(e){var t=JR(this),i=ZR(t),r=ek(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});tk("at")});var kg=v((OB,Rg)=>{"use strict";Pg();var ik=li();Rg.exports=ik("Array","at")});var $g=v((FB,Lg)=>{"use strict";var rk=kg();Lg.exports=rk});var xt=v((NB,Mg)=>{"use strict";var sk=$g();Mg.exports=sk});var Ul=v((E_,iv)=>{"use strict";var mk=Ri();iv.exports=Array.isArray||function(e){return mk(e)==="Array"}});var sv=v((x_,rv)=>{"use strict";var bk=TypeError,gk=9007199254740991;rv.exports=function(s){if(s>gk)throw bk("Maximum allowed index exceeded");return s}});var ov=v((w_,nv)=>{"use strict";var vk=Ul(),Sk=lr(),yk=sv(),Tk=ar(),av=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,c=n?Tk(n,o):!1,d,f;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],a>0&&vk(d)?(f=Sk(d),u=av(s,e,d,f,u,a-1)-1):(yk(u+1),s[u]=d),u++),l++;return u};nv.exports=av});var dv=v((A_,cv)=>{"use strict";var uv=Ul(),Ik=Nu(),Ek=Ge(),xk=Fe(),wk=xk("species"),lv=Array;cv.exports=function(s){var e;return uv(s)&&(e=s.constructor,Ik(e)&&(e===lv||uv(e.prototype))?e=void 0:Ek(e)&&(e=e[wk],e===null&&(e=void 0))),e===void 0?lv:e}});var hv=v((P_,pv)=>{"use strict";var Ak=dv();pv.exports=function(s,e){return new(Ak(s))(e===0?0:e)}});var fv=v(()=>{"use strict";var Pk=Le(),Rk=ov(),kk=$t(),Lk=rr(),$k=lr(),Mk=hv();Pk({target:"Array",proto:!0},{flatMap:function(e){var t=Lk(this),i=$k(t),r;return kk(e),r=Mk(t,0),r.length=Rk(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var mv=v(()=>{"use strict";var Dk=ns();Dk("flatMap")});var gv=v((M_,bv)=>{"use strict";fv();mv();var Ck=li();bv.exports=Ck("Array","flatMap")});var Sv=v((D_,vv)=>{"use strict";var Bk=gv();vv.exports=Bk});var Ls=v((C_,yv)=>{"use strict";var Vk=Sv();yv.exports=Vk});var $s=v((B_,Tv)=>{"use strict";var _k=us(),Ok=String;Tv.exports=function(s){if(_k(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Ok(s)}});var Hl=v((V_,Iv)=>{"use strict";Iv.exports=`
|
|
7
|
-
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var wv=v((__,xv)=>{"use strict";var Fk=De(),Nk=ui(),qk=$s(),Ql=Hl(),Ev=Fk("".replace),Uk=RegExp("^["+Ql+"]+"),Hk=RegExp("(^|[^"+Ql+"])["+Ql+"]+$"),jl=function(s){return function(e){var t=qk(Nk(e));return s&1&&(t=Ev(t,Uk,"")),s&2&&(t=Ev(t,Hk,"$1")),t}};xv.exports={start:jl(1),end:jl(2),trim:jl(3)}});var kv=v((O_,Rv)=>{"use strict";var jk=yu().PROPER,Qk=Me(),Av=Hl(),Pv="\u200B\x85\u180E";Rv.exports=function(s){return Qk(function(){return!!Av[s]()||Pv[s]()!==Pv||jk&&Av[s].name!==s})}});var Wl=v((F_,Lv)=>{"use strict";var Wk=wv().start,Gk=kv();Lv.exports=Gk("trimStart")?function(){return Wk(this)}:"".trimStart});var Mv=v(()=>{"use strict";var zk=Le(),$v=Wl();zk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==$v},{trimLeft:$v})});var Cv=v(()=>{"use strict";Mv();var Yk=Le(),Dv=Wl();Yk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Dv},{trimStart:Dv})});var Vv=v((j_,Bv)=>{"use strict";Cv();var Kk=li();Bv.exports=Kk("String","trimLeft")});var Ov=v((Q_,_v)=>{"use strict";var Xk=Vv();_v.exports=Xk});var Nv=v((W_,Fv)=>{"use strict";var Jk=Ov();Fv.exports=Jk});var tS=v(()=>{"use strict"});var iS=v(()=>{"use strict"});var sS=v((LN,rS)=>{"use strict";var vL=Ge(),SL=Ri(),yL=Fe(),TL=yL("match");rS.exports=function(s){var e;return vL(s)&&((e=s[TL])!==void 0?!!e:SL(s)==="RegExp")}});var oS=v(($N,nS)=>{"use strict";var IL=Ae(),EL=Me(),aS=IL.RegExp,xL=!EL(function(){var s=!0;try{aS(".","d")}catch(u){s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor(aS.prototype,"flags").get.call(e);return o!==i||t!==i});nS.exports={correct:xL}});var lS=v((MN,uS)=>{"use strict";var wL=Mt();uS.exports=function(){var s=wL(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var pS=v((DN,dS)=>{"use strict";var AL=st(),PL=It(),RL=Zr(),cS=oS(),kL=lS(),LL=RegExp.prototype;dS.exports=cS.correct?function(s){return s.flags}:function(s){return!cS.correct&&RL(LL,s)&&!PL(s,"flags")?AL(kL,s):s.flags}});var fS=v((CN,hS)=>{"use strict";var Kl=De(),$L=rr(),ML=Math.floor,zl=Kl("".charAt),DL=Kl("".replace),Yl=Kl("".slice),CL=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,BL=/\$([$&'`]|\d{1,2})/g;hS.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=BL;return r!==void 0&&(r=$L(r),u=CL),DL(a,u,function(l,c){var d;switch(zl(c,0)){case"$":return"$";case"&":return s;case"`":return Yl(e,0,t);case"'":return Yl(e,n);case"<":d=r[Yl(c,1,-1)];break;default:var f=+c;if(f===0)return l;if(f>o){var p=ML(f/10);return p===0?l:p<=o?i[p-1]===void 0?zl(c,1):i[p-1]+zl(c,1):l}d=i[f-1]}return d===void 0?"":d})}});var gS=v(()=>{"use strict";var VL=Le(),_L=st(),Jl=De(),mS=ui(),OL=Pe(),FL=Ge(),NL=sS(),$r=$s(),qL=ts(),UL=pS(),HL=fS(),jL=Fe(),QL=Tt(),WL=jL("replace"),GL=TypeError,Xl=Jl("".indexOf),zL=Jl("".replace),bS=Jl("".slice),YL=Math.max;VL({target:"String",proto:!0},{replaceAll:function(e,t){var i=mS(this),r,a,n,o,u,l,c,d,f,p,h=0,b="";if(FL(e)){if(r=NL(e),r&&(a=$r(mS(UL(e))),!~Xl(a,"g")))throw new GL("`.replaceAll` does not allow non-global regexes");if(n=qL(e,WL),n)return _L(n,e,i,t);if(QL&&r)return zL($r(i),e,t)}for(o=$r(i),u=$r(e),l=OL(t),l||(t=$r(t)),c=u.length,d=YL(1,c),f=Xl(o,u);f!==-1;)p=l?$r(t(u,f,o)):HL(u,o,f,[],void 0,t),b+=bS(o,h,f)+p,h=f+c,f=f+d>o.length?-1:Xl(o,u,f+d);return h<o.length&&(b+=bS(o,h)),b}})});var SS=v((_N,vS)=>{"use strict";tS();iS();gS();var KL=li();vS.exports=KL("String","replaceAll")});var TS=v((ON,yS)=>{"use strict";var XL=SS();yS.exports=XL});var ES=v((FN,IS)=>{"use strict";var JL=TS();IS.exports=JL});var wS=v((NN,xS)=>{"use strict";var ZL=as(),e$=$s(),t$=ui(),i$=RangeError;xS.exports=function(e){var t=e$(t$(this)),i="",r=ZL(e);if(r<0||r===1/0)throw new i$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var LS=v((qN,kS)=>{"use strict";var RS=De(),r$=uu(),AS=$s(),s$=wS(),a$=ui(),n$=RS(s$),o$=RS("".slice),u$=Math.ceil,PS=function(s){return function(e,t,i){var r=AS(a$(e)),a=r$(t),n=r.length,o=i===void 0?" ":AS(i),u,l;return a<=n||o===""?r:(u=a-n,l=n$(o,u$(u/o.length)),l.length>u&&(l=o$(l,0,u)),s?r+l:l+r)}};kS.exports={start:PS(!1),end:PS(!0)}});var MS=v((UN,$S)=>{"use strict";var l$=$i();$S.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(l$)});var DS=v(()=>{"use strict";var c$=Le(),d$=LS().start,p$=MS();c$({target:"String",proto:!0,forced:p$},{padStart:function(e){return d$(this,e,arguments.length>1?arguments[1]:void 0)}})});var BS=v((QN,CS)=>{"use strict";DS();var h$=li();CS.exports=h$("String","padStart")});var _S=v((WN,VS)=>{"use strict";var f$=BS();VS.exports=f$});var FS=v((GN,OS)=>{"use strict";var m$=_S();OS.exports=m$});var j$={};iT(j$,{ChromecastState:()=>Gr,HttpConnectionType:()=>Va,Observable:()=>Nt.Observable,PlaybackState:()=>He,Player:()=>Ta,PredefinedQualityLimits:()=>zr,SDK_VERSION:()=>H$,Subject:()=>Nt.Subject,Subscription:()=>Nt.Subscription,Surface:()=>_a,VERSION:()=>$o,ValueSubject:()=>Nt.ValueSubject,VideoFormat:()=>Lt,VideoQuality:()=>Nt.VideoQuality,areValidLiveRecordSources:()=>Sg,clientChecker:()=>K,isMobile:()=>yr});module.exports=rT(j$);var $o="2.0.139";var He=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(He||{}),Lt=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_FMP4="HLS_FMP4",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(Lt||{});var Gr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Gr||{}),Va=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Va||{});var _a=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(_a||{}),zr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(zr||{});var kc=Y(Di(),1),qy=Y(je(),1);var ae=require("@vkontakte/videoplayer-shared/es2015");var Dh=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Qa=class{constructor(e){this.connection$=new ae.ValueSubject(void 0);this.castState$=new ae.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new ae.Subject;this.realCastState$=new ae.ValueSubject("NOT_AVAILABLE");this.subscription=new ae.Subscription;this.isDestroyed=!1;var a;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,ae.isNonNullable)((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Dh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ae.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,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,ae.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,ae.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,ae.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,ae.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,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=(a=i.getCurrentSession())==null?void 0:a.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,ae.assertNever)(r.sessionState)}})).add((0,ae.merge)((0,ae.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,ae.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,ae.map)(r=>r.castState)),(0,ae.observableFrom)([i.getCastState()])).pipe((0,ae.filterChanged)(),(0,ae.map)(JE),(0,ae.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=(0,ae.isNonNullable)(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();(0,ae.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,ae.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,ae.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(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:ae.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},JE=s=>{switch(s){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,ae.assertNever)(s)}};var Ac=Y(je(),1),Ry=Y(cr(),1),ky=Y(Bu(),1);var Tg=Y(gn(),1);var Tl=require("@vkontakte/videoplayer-shared/es2015");var Re=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Tl.assertNever)(t)}return s},di=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Tl.assertNever)(e)}};var N=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var Dt=require("@vkontakte/videoplayer-shared/es2015"),ne=class{constructor(e){this.transitionStarted$=new Dt.Subject;this.transitionEnded$=new Dt.Subject;this.transitionUpdated$=new Dt.Subject;this.forceChanged$=new Dt.Subject;this.stateChangeStarted$=(0,Dt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Dt.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,Dt.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 El=require("@vkontakte/videoplayer-shared/es2015");var vn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}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,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||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}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}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 pg=Y(je(),1);var yr=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Sn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,pg.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=yr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return R(this,null,function*(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/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||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var yn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var nt=()=>window.ManagedMediaSource||window.MediaSource,Tr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},hg=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Tn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var OR=document.createElement("video"),FR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',NR='video/mp4; codecs="hev1.1.6.L93.B0"',fg='video/webm; codecs="vp09.00.10.08"',mg='video/webm; codecs="av01.0.00M.08"',qR='audio/mp4; codecs="mp4a.40.2"',UR='audio/webm; codecs="opus"',bg,HR=()=>R(null,null,function*(){if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(j(C({},s),{video:j(C({},s.video),{contentType:mg})})),window.navigator.mediaCapabilities.decodingInfo(j(C({},s),{video:j(C({},s.video),{contentType:fg})}))]);bg={DASH_WEBM_AV1:e,DASH_WEBM:t}});HR().catch(s=>{console.log(OR),console.error(s)});var In=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 bg}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,c,d,f,p,h,b,S,g,y,A,E;this._video=document.createElement("video");try{this._protocols={mms:Tr(),mse:hg(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let w=!!((c=(l=nt())==null?void 0:l.isTypeSupported)!=null&&c.call(l,FR)),_=!!((f=(d=nt())==null?void 0:d.isTypeSupported)!=null&&f.call(d,NR)),W=!!((h=(p=nt())==null?void 0:p.isTypeSupported)!=null&&h.call(p,qR));this._codecs={h264:w,h265:_,vp9:!!((S=(b=nt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,fg)),av1:!!((y=(g=nt())==null?void 0:g.isTypeSupported)!=null&&y.call(g,mg)),aac:W,opus:!!((E=(A=nt())==null?void 0:A.isTypeSupported)!=null&&E.call(A,UR)),mpeg:(w||_)&&W},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(w){console.error(w)}try{this.destroyVideoElement()}catch(w){console.error("Error destroying video element:",w)}}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 gg="audio/mpeg",En=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,gg))},this._codecs={mp3:!!((r=(i=nt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,gg))}}catch(a){console.error(a)}try{this.destroyAudioElement()}catch(a){console.error("Error destroying audio element:",a)}}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 vg=require("@vkontakte/videoplayer-shared/es2015");var Il=class{constructor(){this.isInited$=new vg.ValueSubject(!1);this._displayChecker=new yn,this._deviceChecker=new Sn(this._displayChecker),this._browserChecker=new vn,this._videoChecker=new In(this._deviceChecker,this._browserChecker),this._audioChecker=new En,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 R(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},K=new Il;var xl=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=K.video,a=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return s.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&a;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&&a||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&a;case"DASH_LIVE_CMAF":return n&&e.mp4&&a&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&a;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,El.assertNever)(o)}})},wl=s=>{switch(s){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,El.assertNever)(s)}},Sg=s=>{let t=Object.keys(s).filter(i=>!wl(i));return xl(t).length>0};var G=require("@vkontakte/videoplayer-shared/es2015");var jR=5,QR=5,WR=500,yg=7e3,Ss=class{constructor(e){this.subscription=new G.Subscription;this.loadMediaTimeoutSubscription=new G.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(),a=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(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.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,G.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,G.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,G.assertNever)(e)}break}default:(0,G.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(wl(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 G.Subscription;this.subscription.add(e),this.subscription.add((0,G.merge)(this.videoState.stateChangeStarted$.pipe((0,G.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,G.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new G.Subject;e.add(r.pipe((0,G.debounce)(WR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,G.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-a)>jR)&&r.next(o),a=o})),e.add((0,G.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,G.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,G.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,G.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=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()&&a.duration-a.currentTime<QR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),N(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,G.assertNever)(n)}}),t((0,G.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,G.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,G.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.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"),N(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),N(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=this.createMediaInfo(e),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"),N(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"),N(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"&&N(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a: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()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let c=t[e];(0,G.assertNonNullable)(c);let d=(0,G.getHighestQuality)(Object.keys(c));(0,G.assertNonNullable)(d);let f=c[d];(0,G.assertNonNullable)(f),i=f,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=t[e];(0,G.assertNonNullable)(c),i=c.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,G.assertNonNullable)(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,G.assertNonNullable)(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,G.assertNonNullable)(c),i=Re(c.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:G.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,G.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,G.isNonNullable)(o)&&(n.metadata.title=o),(0,G.isNonNullable)(u)&&(n.metadata.subtitle=u),n}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,a)=>{this.loadMediaTimeoutSubscription.add((0,G.timeout)(yg).subscribe(()=>a(`timeout(${yg})`)))});(0,Tg.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 a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:G.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Nl=Y(je(),1);var kl=require("@vkontakte/videoplayer-shared/es2015");var Ig=require("@vkontakte/videoplayer-shared/es2015"),Eg=s=>{try{s.pause(),s.playbackRate=0,(0,Ig.clearVideoElement)(s),s.remove()}catch(e){console.error(e)}};var xn=require("@vkontakte/videoplayer-shared/es2015"),Al=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)}},Pl=window.WeakMap?new WeakMap:new Al,Rl=window.WeakMap?new WeakMap:new Map,GR=(s,e=20)=>{let t=0;return(0,xn.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},ze=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?(0,kl.clearVideoElement)(i):(i=document.createElement("video"),s.appendChild(i)),Pl.set(i,r);let a=new xn.Subscription;return a.add(GR(i,e)),Rl.set(i,a),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},Ye=s=>{let e=Rl.get(s);e==null||e.unsubscribe(),Rl.delete(s);let t=Pl.get(s);Pl.delete(s),t?(0,kl.clearVideoElement)(s):Eg(s)};var Ll=Y(Di(),1),z=require("@vkontakte/videoplayer-shared/es2015");var pi=require("@vkontakte/videoplayer-shared/es2015"),wn=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,pi.isNullable)(r),l=new pi.Subscription;return r&&l.add(r.subscribe(c=>{let d=s.getState();i(c,d)&&s.setState(c)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),u&&s.setState(c.to)},a)),l},Ct=(s,e,t)=>wn(e,()=>s.loop,i=>{(0,pi.isNonNullable)(i)&&(s.loop=i)},{onError:t}),Ke=(s,e,t,i)=>wn(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,pi.isNonNullable)(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),pt=(s,e,t,i)=>wn(e,()=>s.playbackRate,r=>{(0,pi.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),ys=wn;var zR=s=>["__",s.language,s.label].join("|"),YR=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},$l=class s{constructor(e){this.available$=new z.Subject;this.current$=new z.ValueSubject(void 0);this.error$=new z.Subject;this.subscription=new z.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=a=>{this.error$.next({id:"TextTracksManager",category:z.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};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(ys(t.internalTextTracks,()=>(0,Ll.default)(this.internalTracks),a=>{(0,z.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,n)=>(0,z.isNonNullable)(a)&&(0,z.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ys(t.externalTextTracks,()=>(0,Ll.default)(this.externalTracks),a=>{(0,z.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,n)=>(0,z.isNonNullable)(a)&&(0,z.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ys(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(ys(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,z.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,z.merge)((0,z.fromEvent)(e,"addtrack"),(0,z.fromEvent)(e,"removetrack"),(0,z.observableFrom)(["init"])).pipe((0,z.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,z.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add((0,z.merge)((0,z.fromEvent)(e,"change"),(0,z.observableFrom)(["init"])).pipe((0,z.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,z.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,z.filterChanged)()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,c,d,f,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((f=(d=o.target)==null?void 0:d.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,z.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,z.isNonNullable)(t.align)&&(r.align=t.align),(0,z.isNonNullable)(t.position)&&(r.position=t.position),(0,z.isNonNullable)(t.size)&&(r.size=t.size),(0,z.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,z.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:zR(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).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,z.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,z.isNullable)(e)||!YR(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,z.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,z.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)}},ht=$l;var Fi=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 xg=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Ml=s=>{let e=xg(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},wg=s=>{let e=xg(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var D=require("@vkontakte/videoplayer-shared/es2015");var KR=3,Ag=(s,e,t=KR)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var Xe=s=>{let e=M=>(0,D.fromEvent)(s,M).pipe((0,D.mapTo)(void 0),(0,D.shareReplay)(1)),t=new D.Subscription,i=()=>t.unsubscribe(),r=(0,D.merge)((0,D.fromEvent)(s,"progress"),(0,D.fromEvent)(s,"timeupdate")).pipe((0,D.map)(()=>Ag(s.buffered,s.currentTime)),(0,D.shareReplay)(1)),a=K.browser.isSafari?(0,D.combine)({play:e("play").pipe((0,D.once)()),playing:e("playing")}).pipe((0,D.mapTo)(void 0),(0,D.shareReplay)(1)):e("playing"),n=(0,D.fromEvent)(s,"volumechange").pipe((0,D.map)(()=>({muted:s.muted,volume:s.volume})),(0,D.shareReplay)(1)),o=(0,D.fromEvent)(s,"ratechange").pipe((0,D.map)(()=>s.playbackRate),(0,D.shareReplay)(1)),u=(0,D.fromEvent)(s,"error").pipe((0,D.filter)(()=>!!(s.error||s.played.length)),(0,D.map)(()=>{var Q;let M=s.error;return{id:M?`MediaError#${M.code}`:"HtmlVideoError",category:D.ErrorCategory.VIDEO_PIPELINE,message:M?M.message:"Error event from HTML video element",thrown:(Q=s.error)!=null?Q:void 0}}),(0,D.shareReplay)(1)),l=(0,D.fromEvent)(s,"timeupdate").pipe((0,D.map)(()=>s.currentTime),(0,D.shareReplay)(1)),c=["waiting","seeking","seeked","timeupdate"],d=new D.Subject,f=.3,p;t.add((0,D.merge)(...c.map(M=>(0,D.fromEvent)(s,M))).subscribe(M=>{let Q=s.currentTime;s.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(Q)&&p>=s.duration-f&&Q<=f&&d.next(p),p=Q}));let h=e("pause").pipe((0,D.filter)(()=>!s.error&&p!==s.duration),(0,D.shareReplay)(1)),b=(0,D.fromEvent)(s,"enterpictureinpicture").pipe((0,D.shareReplay)(1)),S=(0,D.fromEvent)(s,"leavepictureinpicture").pipe((0,D.shareReplay)(1)),g=new D.ValueSubject(wg(s));t.add(b.subscribe(()=>g.next(!0))),t.add(S.subscribe(()=>g.next(!1)));let y=new D.ValueSubject(Ml(s)),A=(0,D.fromEvent)(s,"fullscreenchange").pipe((0,D.shareReplay)(1));t.add(A.pipe((0,D.map)(()=>Ml(s))).subscribe(y));let E=.1,w=1e3,_=(0,D.fromEvent)(s,"timeupdate").pipe((0,D.map)(M=>s.duration-s.currentTime<E),(0,D.filterChanged)(),(0,D.shareReplay)(1)),W=(0,D.merge)(_.pipe((0,D.filter)(M=>!s.loop&&M)),(0,D.fromEvent)(s,"ended")).pipe((0,D.throttle)(w),(0,D.mapTo)(void 0),(0,D.shareReplay)(1)),U=(0,D.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(M=>(0,D.fromEvent)(s,M)),_.pipe((0,D.map)(M=>({type:M?"ended":"unknown"})))).pipe((0,D.map)(M=>K.browser.isFirefox&&M.type==="ended"?s.readyState<2:s.readyState<3),(0,D.filterChanged)(),(0,D.shareReplay)(1));return{playing$:a,pause$:h,canplay$:e("canplay"),ended$:W,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,D.fromEvent)(s,"durationchange").pipe((0,D.map)(()=>s.duration),(0,D.shareReplay)(1)),isBuffering$:U,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y,enterPip$:b,leavePip$:S,destroy:i}};var Wt=require("@vkontakte/videoplayer-shared/es2015"),hi=s=>{switch(s){case"mobile":return Wt.VideoQuality.Q_144P;case"lowest":return Wt.VideoQuality.Q_240P;case"low":return Wt.VideoQuality.Q_360P;case"sd":case"medium":return Wt.VideoQuality.Q_480P;case"hd":case"high":return Wt.VideoQuality.Q_720P;case"fullhd":case"full":return Wt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Wt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Wt.VideoQuality.Q_2160P}};var We=Y(xt(),1),Bl=Y(je(),1),Ni=Y(cr(),1),V=require("@vkontakte/videoplayer-shared/es2015");var Dl=!1,Gt={},Dg=s=>{Dl=s},Cg=()=>{Gt={}},Bg=s=>{s(Gt)},Ts=(s,e)=>{var t;Dl&&(Gt.meta=(t=Gt.meta)!=null?t:{},Gt.meta[s]=e)},Qe=class{constructor(e){this.name=e}next(e){var i,r;if(!Dl)return;Gt.series=(i=Gt.series)!=null?i:{};let t=(r=Gt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Gt.series[this.name]=t}};var $e=require("@vkontakte/videoplayer-shared/es2015");function Cl(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function An(s,e,t){return!!s&&Cl(s,e,t)==="high_quality"}function Ir(s,e,t){return(0,$e.isNullable)(s)||(0,$e.isNonNullable)(s.min)&&(0,$e.isNonNullable)(s.max)&&(0,$e.isLower)(s.max,s.min)||(0,$e.isNonNullable)(s.min)&&e&&(0,$e.isHigher)(s.min,e)||(0,$e.isNonNullable)(s.max)&&t&&(0,$e.isLower)(s.max,t)}function Vg({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Ir({max:s!=null&&s.max?(0,$e.videoHeightToQuality)(s.max):void 0,min:s!=null&&s.min?(0,$e.videoHeightToQuality)(s.min):void 0},e?(0,$e.videoHeightToQuality)(e):void 0,t?(0,$e.videoHeightToQuality)(t):void 0)}var qg=new Qe("best_bitrate"),Rn=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Er=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),fi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,V.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},kn='Assertion "ABR Tracks is empty array" failed',Pn=new WeakMap,_g=new WeakMap,Og=new WeakMap,Is=(s,e,t,i)=>{var u;let r=[...e].sort(Er(1)),a=[...t].sort(Er(1)),n=a.filter(l=>(0,V.isNonNullable)(l.bitrate)&&(0,V.isNonNullable)(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,We.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,We.default)(a,-1);return o&&(0,Bl.default)(n,o)?o:n.length?(0,We.default)(n,-1):(0,We.default)(a,0)},Es=(s,e,t,i)=>{var u;let r=Pn.get(e);r||(r=[...e].sort(Er(1)),Pn.set(e,r));let a=Pn.get(t);a||(a=[...t].sort(Er(1)),Pn.set(t,a));let n=Og.get(s);n||(n=a.filter(l=>(0,V.isNonNullable)(l.bitrate)&&(0,V.isNonNullable)(s.bitrate)?s.bitrate/l.bitrate>i:!0),Og.set(s,n));let o=(u=(0,We.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,We.default)(a,-1);return o&&(0,Bl.default)(n,o)?o:n.length?(0,We.default)(n,-1):(0,We.default)(a,0)},Fg=s=>"quality"in s,Ln=(s,e,t,i)=>{var n;let r=(0,V.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,V.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,V.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Fg(o)?"video":"audio",l=Fg(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
"use strict";var zy=Object.create;var Wr=Object.defineProperty,Yy=Object.defineProperties,Ky=Object.getOwnPropertyDescriptor,Xy=Object.getOwnPropertyDescriptors,Jy=Object.getOwnPropertyNames,Ba=Object.getOwnPropertySymbols,Zy=Object.getPrototypeOf,ko=Object.prototype.hasOwnProperty,hd=Object.prototype.propertyIsEnumerable;var eT=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var kt=Math.pow,pd=(s,e,t)=>e in s?Wr(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,C=(s,e)=>{for(var t in e||(e={}))ko.call(e,t)&&pd(s,t,e[t]);if(Ba)for(var t of Ba(e))hd.call(e,t)&&pd(s,t,e[t]);return s},j=(s,e)=>Yy(s,Xy(e));var fd=(s,e)=>{var t={};for(var i in s)ko.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&Ba)for(var i of Ba(s))e.indexOf(i)<0&&hd.call(s,i)&&(t[i]=s[i]);return t};var v=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),tT=(s,e)=>{for(var t in e)Wr(s,t,{get:e[t],enumerable:!0})},md=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jy(e))!ko.call(s,r)&&r!==t&&Wr(s,r,{get:()=>e[r],enumerable:!(i=Ky(e,r))||i.enumerable});return s};var Y=(s,e,t)=>(t=s!=null?zy(Zy(s)):{},md(e||!s||!s.__esModule?Wr(t,"default",{value:s,enumerable:!0}):t,s)),iT=s=>md(Wr({},"__esModule",{value:!0}),s);var R=(s,e,t)=>new Promise((i,r)=>{var a=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(a,n);o((t=t.apply(s,e)).next())}),Pi=function(s,e){this[0]=s,this[1]=e},oe=(s,e,t)=>{var i=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Pi,f=c.done;Promise.resolve(d?o[0]:o).then(p=>d?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:f})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>a[n]=o=>new Promise((u,l)=>i(n,o,u,l)),a={};return t=t.apply(s,e),a[eT("asyncIterator")]=()=>a,r("next"),r("throw"),r("return"),a};var Ae=v(($o,bd)=>{"use strict";var Yr=function(s){return s&&s.Math===Math&&s};bd.exports=Yr(typeof globalThis=="object"&&globalThis)||Yr(typeof window=="object"&&window)||Yr(typeof self=="object"&&self)||Yr(typeof global=="object"&&global)||Yr(typeof $o=="object"&&$o)||function(){return this}()||Function("return this")()});var Me=v((G$,gd)=>{"use strict";gd.exports=function(s){try{return!!s()}catch(e){return!0}}});var Kr=v((z$,vd)=>{"use strict";var rT=Me();vd.exports=!rT(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Mo=v((Y$,Id)=>{"use strict";var sT=Kr(),Td=Function.prototype,Sd=Td.apply,yd=Td.call;Id.exports=typeof Reflect=="object"&&Reflect.apply||(sT?yd.bind(Sd):function(){return yd.apply(Sd,arguments)})});var De=v((K$,wd)=>{"use strict";var Ed=Kr(),xd=Function.prototype,Do=xd.call,aT=Ed&&xd.bind.bind(Do,Do);wd.exports=Ed?aT:function(s){return function(){return Do.apply(s,arguments)}}});var Ri=v((X$,Pd)=>{"use strict";var Ad=De(),nT=Ad({}.toString),oT=Ad("".slice);Pd.exports=function(s){return oT(nT(s),8,-1)}});var Co=v((J$,Rd)=>{"use strict";var uT=Ri(),lT=De();Rd.exports=function(s){if(uT(s)==="Function")return lT(s)}});var Pe=v((Z$,kd)=>{"use strict";var Bo=typeof document=="object"&&document.all;kd.exports=typeof Bo=="undefined"&&Bo!==void 0?function(s){return typeof s=="function"||s===Bo}:function(s){return typeof s=="function"}});var rt=v((eM,Ld)=>{"use strict";var cT=Me();Ld.exports=!cT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var st=v((tM,$d)=>{"use strict";var dT=Kr(),Oa=Function.prototype.call;$d.exports=dT?Oa.bind(Oa):function(){return Oa.apply(Oa,arguments)}});var Vo=v(Cd=>{"use strict";var Md={}.propertyIsEnumerable,Dd=Object.getOwnPropertyDescriptor,pT=Dd&&!Md.call({1:2},1);Cd.f=pT?function(e){var t=Dd(this,e);return!!t&&t.enumerable}:Md});var Xr=v((rM,Bd)=>{"use strict";Bd.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var _d=v((sM,Vd)=>{"use strict";var hT=De(),fT=Me(),mT=Ri(),_o=Object,bT=hT("".split);Vd.exports=fT(function(){return!_o("z").propertyIsEnumerable(0)})?function(s){return mT(s)==="String"?bT(s,""):_o(s)}:_o});var Jr=v((aM,Od)=>{"use strict";Od.exports=function(s){return s==null}});var ui=v((nM,Fd)=>{"use strict";var gT=Jr(),vT=TypeError;Fd.exports=function(s){if(gT(s))throw new vT("Can't call method on "+s);return s}});var ki=v((oM,Nd)=>{"use strict";var ST=_d(),yT=ui();Nd.exports=function(s){return ST(yT(s))}});var Ge=v((uM,qd)=>{"use strict";var TT=Pe();qd.exports=function(s){return typeof s=="object"?s!==null:TT(s)}});var Li=v((lM,Ud)=>{"use strict";Ud.exports={}});var Ht=v((cM,jd)=>{"use strict";var Oo=Li(),Fo=Ae(),IT=Pe(),Hd=function(s){return IT(s)?s:void 0};jd.exports=function(s,e){return arguments.length<2?Hd(Oo[s])||Hd(Fo[s]):Oo[s]&&Oo[s][e]||Fo[s]&&Fo[s][e]}});var Zr=v((dM,Qd)=>{"use strict";var ET=De();Qd.exports=ET({}.isPrototypeOf)});var $i=v((pM,zd)=>{"use strict";var xT=Ae(),Wd=xT.navigator,Gd=Wd&&Wd.userAgent;zd.exports=Gd?String(Gd):""});var qo=v((hM,ep)=>{"use strict";var Zd=Ae(),No=$i(),Yd=Zd.process,Kd=Zd.Deno,Xd=Yd&&Yd.versions||Kd&&Kd.version,Jd=Xd&&Xd.v8,yt,Fa;Jd&&(yt=Jd.split("."),Fa=yt[0]>0&&yt[0]<4?1:+(yt[0]+yt[1]));!Fa&&No&&(yt=No.match(/Edge\/(\d+)/),(!yt||yt[1]>=74)&&(yt=No.match(/Chrome\/(\d+)/),yt&&(Fa=+yt[1])));ep.exports=Fa});var Uo=v((fM,ip)=>{"use strict";var tp=qo(),wT=Me(),AT=Ae(),PT=AT.String;ip.exports=!!Object.getOwnPropertySymbols&&!wT(function(){var s=Symbol("symbol detection");return!PT(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&tp&&tp<41})});var Ho=v((mM,rp)=>{"use strict";var RT=Uo();rp.exports=RT&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var jo=v((bM,sp)=>{"use strict";var kT=Ht(),LT=Pe(),$T=Zr(),MT=Ho(),DT=Object;sp.exports=MT?function(s){return typeof s=="symbol"}:function(s){var e=kT("Symbol");return LT(e)&&$T(e.prototype,DT(s))}});var es=v((gM,ap)=>{"use strict";var CT=String;ap.exports=function(s){try{return CT(s)}catch(e){return"Object"}}});var $t=v((vM,np)=>{"use strict";var BT=Pe(),VT=es(),_T=TypeError;np.exports=function(s){if(BT(s))return s;throw new _T(VT(s)+" is not a function")}});var ts=v((SM,op)=>{"use strict";var OT=$t(),FT=Jr();op.exports=function(s,e){var t=s[e];return FT(t)?void 0:OT(t)}});var lp=v((yM,up)=>{"use strict";var Qo=st(),Wo=Pe(),Go=Ge(),NT=TypeError;up.exports=function(s,e){var t,i;if(e==="string"&&Wo(t=s.toString)&&!Go(i=Qo(t,s))||Wo(t=s.valueOf)&&!Go(i=Qo(t,s))||e!=="string"&&Wo(t=s.toString)&&!Go(i=Qo(t,s)))return i;throw new NT("Can't convert object to primitive value")}});var Tt=v((TM,cp)=>{"use strict";cp.exports=!0});var hp=v((IM,pp)=>{"use strict";var dp=Ae(),qT=Object.defineProperty;pp.exports=function(s,e){try{qT(dp,s,{value:e,configurable:!0,writable:!0})}catch(t){dp[s]=e}return e}});var is=v((EM,bp)=>{"use strict";var UT=Tt(),HT=Ae(),jT=hp(),fp="__core-js_shared__",mp=bp.exports=HT[fp]||jT(fp,{});(mp.versions||(mp.versions=[])).push({version:"3.43.0",mode:UT?"pure":"global",copyright:"\xA9 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 zo=v((xM,vp)=>{"use strict";var gp=is();vp.exports=function(s,e){return gp[s]||(gp[s]=e||{})}});var rr=v((wM,Sp)=>{"use strict";var QT=ui(),WT=Object;Sp.exports=function(s){return WT(QT(s))}});var It=v((AM,yp)=>{"use strict";var GT=De(),zT=rr(),YT=GT({}.hasOwnProperty);yp.exports=Object.hasOwn||function(e,t){return YT(zT(e),t)}});var Yo=v((PM,Tp)=>{"use strict";var KT=De(),XT=0,JT=Math.random(),ZT=KT(1.1.toString);Tp.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+ZT(++XT+JT,36)}});var Fe=v((RM,Ep)=>{"use strict";var eI=Ae(),tI=zo(),Ip=It(),iI=Yo(),rI=Uo(),sI=Ho(),sr=eI.Symbol,Ko=tI("wks"),aI=sI?sr.for||sr:sr&&sr.withoutSetter||iI;Ep.exports=function(s){return Ip(Ko,s)||(Ko[s]=rI&&Ip(sr,s)?sr[s]:aI("Symbol."+s)),Ko[s]}});var Pp=v((kM,Ap)=>{"use strict";var nI=st(),xp=Ge(),wp=jo(),oI=ts(),uI=lp(),lI=Fe(),cI=TypeError,dI=lI("toPrimitive");Ap.exports=function(s,e){if(!xp(s)||wp(s))return s;var t=oI(s,dI),i;if(t){if(e===void 0&&(e="default"),i=nI(t,s,e),!xp(i)||wp(i))return i;throw new cI("Can't convert object to primitive value")}return e===void 0&&(e="number"),uI(s,e)}});var Xo=v((LM,Rp)=>{"use strict";var pI=Pp(),hI=jo();Rp.exports=function(s){var e=pI(s,"string");return hI(e)?e:e+""}});var Na=v(($M,Lp)=>{"use strict";var fI=Ae(),kp=Ge(),Jo=fI.document,mI=kp(Jo)&&kp(Jo.createElement);Lp.exports=function(s){return mI?Jo.createElement(s):{}}});var Zo=v((MM,$p)=>{"use strict";var bI=rt(),gI=Me(),vI=Na();$p.exports=!bI&&!gI(function(){return Object.defineProperty(vI("div"),"a",{get:function(){return 7}}).a!==7})});var Cp=v(Dp=>{"use strict";var SI=rt(),yI=st(),TI=Vo(),II=Xr(),EI=ki(),xI=Xo(),wI=It(),AI=Zo(),Mp=Object.getOwnPropertyDescriptor;Dp.f=SI?Mp:function(e,t){if(e=EI(e),t=xI(t),AI)try{return Mp(e,t)}catch(i){}if(wI(e,t))return II(!yI(TI.f,e,t),e[t])}});var eu=v((CM,Bp)=>{"use strict";var PI=Me(),RI=Pe(),kI=/#|\.prototype\./,rs=function(s,e){var t=$I[LI(s)];return t===DI?!0:t===MI?!1:RI(e)?PI(e):!!e},LI=rs.normalize=function(s){return String(s).replace(kI,".").toLowerCase()},$I=rs.data={},MI=rs.NATIVE="N",DI=rs.POLYFILL="P";Bp.exports=rs});var ar=v((BM,_p)=>{"use strict";var Vp=Co(),CI=$t(),BI=Kr(),VI=Vp(Vp.bind);_p.exports=function(s,e){return CI(s),e===void 0?s:BI?VI(s,e):function(){return s.apply(e,arguments)}}});var tu=v((VM,Op)=>{"use strict";var _I=rt(),OI=Me();Op.exports=_I&&OI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Mt=v((_M,Fp)=>{"use strict";var FI=Ge(),NI=String,qI=TypeError;Fp.exports=function(s){if(FI(s))return s;throw new qI(NI(s)+" is not an object")}});var Mi=v(qp=>{"use strict";var UI=rt(),HI=Zo(),jI=tu(),qa=Mt(),Np=Xo(),QI=TypeError,iu=Object.defineProperty,WI=Object.getOwnPropertyDescriptor,ru="enumerable",su="configurable",au="writable";qp.f=UI?jI?function(e,t,i){if(qa(e),t=Np(t),qa(i),typeof e=="function"&&t==="prototype"&&"value"in i&&au in i&&!i[au]){var r=WI(e,t);r&&r[au]&&(e[t]=i.value,i={configurable:su in i?i[su]:r[su],enumerable:ru in i?i[ru]:r[ru],writable:!1})}return iu(e,t,i)}:iu:function(e,t,i){if(qa(e),t=Np(t),qa(i),HI)try{return iu(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new QI("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var nr=v((FM,Up)=>{"use strict";var GI=rt(),zI=Mi(),YI=Xr();Up.exports=GI?function(s,e,t){return zI.f(s,e,YI(1,t))}:function(s,e,t){return s[e]=t,s}});var Le=v((NM,jp)=>{"use strict";var ss=Ae(),KI=Mo(),XI=Co(),JI=Pe(),ZI=Cp().f,eE=eu(),or=Li(),tE=ar(),ur=nr(),Hp=It();is();var iE=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return KI(s,this,arguments)};return e.prototype=s.prototype,e};jp.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ss:r?ss[t]:ss[t]&&ss[t].prototype,o=i?or:or[t]||ur(or,t,{})[t],u=o.prototype,l,c,d,f,p,h,b,S,g;for(f in e)l=eE(i?f:t+(r?".":"#")+f,s.forced),c=!l&&n&&Hp(n,f),h=o[f],c&&(s.dontCallGetSet?(g=ZI(n,f),b=g&&g.value):b=n[f]),p=c&&b?b:e[f],!(!l&&!a&&typeof h==typeof p)&&(s.bind&&c?S=tE(p,ss):s.wrap&&c?S=iE(p):a&&JI(p)?S=XI(p):S=p,(s.sham||p&&p.sham||h&&h.sham)&&ur(S,"sham",!0),ur(o,f,S),a&&(d=t+"Prototype",Hp(or,d)||ur(or,d,{}),ur(or[d],f,p),s.real&&u&&(l||!u[f])&&ur(u,f,p)))}});var Ua=v((qM,Wp)=>{"use strict";var rE=zo(),sE=Yo(),Qp=rE("keys");Wp.exports=function(s){return Qp[s]||(Qp[s]=sE(s))}});var zp=v((UM,Gp)=>{"use strict";var aE=Me();Gp.exports=!aE(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Ha=v((HM,Kp)=>{"use strict";var nE=It(),oE=Pe(),uE=rr(),lE=Ua(),cE=zp(),Yp=lE("IE_PROTO"),nu=Object,dE=nu.prototype;Kp.exports=cE?nu.getPrototypeOf:function(s){var e=uE(s);if(nE(e,Yp))return e[Yp];var t=e.constructor;return oE(t)&&e instanceof t?t.prototype:e instanceof nu?dE:null}});var Jp=v((jM,Xp)=>{"use strict";var pE=Math.ceil,hE=Math.floor;Xp.exports=Math.trunc||function(e){var t=+e;return(t>0?hE:pE)(t)}});var as=v((QM,Zp)=>{"use strict";var fE=Jp();Zp.exports=function(s){var e=+s;return e!==e||e===0?0:fE(e)}});var th=v((WM,eh)=>{"use strict";var mE=as(),bE=Math.max,gE=Math.min;eh.exports=function(s,e){var t=mE(s);return t<0?bE(t+e,0):gE(t,e)}});var ou=v((GM,ih)=>{"use strict";var vE=as(),SE=Math.min;ih.exports=function(s){var e=vE(s);return e>0?SE(e,9007199254740991):0}});var lr=v((zM,rh)=>{"use strict";var yE=ou();rh.exports=function(s){return yE(s.length)}});var uu=v((YM,ah)=>{"use strict";var TE=ki(),IE=th(),EE=lr(),sh=function(s){return function(e,t,i){var r=TE(e),a=EE(r);if(a===0)return!s&&-1;var n=IE(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};ah.exports={includes:sh(!0),indexOf:sh(!1)}});var ja=v((KM,nh)=>{"use strict";nh.exports={}});var lh=v((XM,uh)=>{"use strict";var xE=De(),lu=It(),wE=ki(),AE=uu().indexOf,PE=ja(),oh=xE([].push);uh.exports=function(s,e){var t=wE(s),i=0,r=[],a;for(a in t)!lu(PE,a)&&lu(t,a)&&oh(r,a);for(;e.length>i;)lu(t,a=e[i++])&&(~AE(r,a)||oh(r,a));return r}});var cu=v((JM,ch)=>{"use strict";ch.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var du=v((ZM,dh)=>{"use strict";var RE=lh(),kE=cu();dh.exports=Object.keys||function(e){return RE(e,kE)}});var pu=v((eD,bh)=>{"use strict";var hh=rt(),LE=Me(),fh=De(),$E=Ha(),ME=du(),DE=ki(),CE=Vo().f,mh=fh(CE),BE=fh([].push),VE=hh&&LE(function(){var s=Object.create(null);return s[2]=2,!mh(s,2)}),ph=function(s){return function(e){for(var t=DE(e),i=ME(t),r=VE&&$E(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!hh||(r?u in t:mh(t,u)))&&BE(o,s?[u,t[u]]:t[u]);return o}};bh.exports={entries:ph(!0),values:ph(!1)}});var gh=v(()=>{"use strict";var _E=Le(),OE=pu().values;_E({target:"Object",stat:!0},{values:function(e){return OE(e)}})});var Sh=v((rD,vh)=>{"use strict";gh();var FE=Li();vh.exports=FE.Object.values});var Th=v((sD,yh)=>{"use strict";var NE=Sh();yh.exports=NE});var Di=v((aD,Ih)=>{"use strict";var qE=Th();Ih.exports=qE});var ns=v((nD,Eh)=>{"use strict";Eh.exports=function(){}});var xh=v(()=>{"use strict";var UE=Le(),HE=uu().includes,jE=Me(),QE=ns(),WE=jE(function(){return!Array(1).includes()});UE({target:"Array",proto:!0,forced:WE},{includes:function(e){return HE(this,e,arguments.length>1?arguments[1]:void 0)}});QE("includes")});var li=v((lD,wh)=>{"use strict";var GE=Ht();wh.exports=GE});var Ph=v((cD,Ah)=>{"use strict";xh();var zE=li();Ah.exports=zE("Array","includes")});var kh=v((dD,Rh)=>{"use strict";var YE=Ph();Rh.exports=YE});var je=v((pD,Lh)=>{"use strict";var KE=kh();Lh.exports=KE});var Mh=v(()=>{"use strict";var JE=Le(),ZE=pu().entries;JE({target:"Object",stat:!0},{entries:function(e){return ZE(e)}})});var Ch=v((wD,Dh)=>{"use strict";Mh();var ex=Li();Dh.exports=ex.Object.entries});var Vh=v((AD,Bh)=>{"use strict";var tx=Ch();Bh.exports=tx});var cr=v((PD,_h)=>{"use strict";var ix=Vh();_h.exports=ix});var Ci=v((RD,Oh)=>{"use strict";Oh.exports={}});var qh=v((kD,Nh)=>{"use strict";var rx=Ae(),sx=Pe(),Fh=rx.WeakMap;Nh.exports=sx(Fh)&&/native code/.test(String(Fh))});var bu=v((LD,jh)=>{"use strict";var ax=qh(),Hh=Ae(),nx=Ge(),ox=nr(),hu=It(),fu=is(),ux=Ua(),lx=ja(),Uh="Object already initialized",mu=Hh.TypeError,cx=Hh.WeakMap,Wa,os,Ga,dx=function(s){return Ga(s)?os(s):Wa(s,{})},px=function(s){return function(e){var t;if(!nx(e)||(t=os(e)).type!==s)throw new mu("Incompatible receiver, "+s+" required");return t}};ax||fu.state?(Et=fu.state||(fu.state=new cx),Et.get=Et.get,Et.has=Et.has,Et.set=Et.set,Wa=function(s,e){if(Et.has(s))throw new mu(Uh);return e.facade=s,Et.set(s,e),e},os=function(s){return Et.get(s)||{}},Ga=function(s){return Et.has(s)}):(Bi=ux("state"),lx[Bi]=!0,Wa=function(s,e){if(hu(s,Bi))throw new mu(Uh);return e.facade=s,ox(s,Bi,e),e},os=function(s){return hu(s,Bi)?s[Bi]:{}},Ga=function(s){return hu(s,Bi)});var Et,Bi;jh.exports={set:Wa,get:os,has:Ga,enforce:dx,getterFor:px}});var Su=v(($D,Wh)=>{"use strict";var gu=rt(),hx=It(),Qh=Function.prototype,fx=gu&&Object.getOwnPropertyDescriptor,vu=hx(Qh,"name"),mx=vu&&function(){}.name==="something",bx=vu&&(!gu||gu&&fx(Qh,"name").configurable);Wh.exports={EXISTS:vu,PROPER:mx,CONFIGURABLE:bx}});var zh=v(Gh=>{"use strict";var gx=rt(),vx=tu(),Sx=Mi(),yx=Mt(),Tx=ki(),Ix=du();Gh.f=gx&&!vx?Object.defineProperties:function(e,t){yx(e);for(var i=Tx(t),r=Ix(t),a=r.length,n=0,o;a>n;)Sx.f(e,o=r[n++],i[o]);return e}});var yu=v((DD,Yh)=>{"use strict";var Ex=Ht();Yh.exports=Ex("document","documentElement")});var xu=v((CD,rf)=>{"use strict";var xx=Mt(),wx=zh(),Kh=cu(),Ax=ja(),Px=yu(),Rx=Na(),kx=Ua(),Xh=">",Jh="<",Iu="prototype",Eu="script",ef=kx("IE_PROTO"),Tu=function(){},tf=function(s){return Jh+Eu+Xh+s+Jh+"/"+Eu+Xh},Zh=function(s){s.write(tf("")),s.close();var e=s.parentWindow.Object;return s=null,e},Lx=function(){var s=Rx("iframe"),e="java"+Eu+":",t;return s.style.display="none",Px.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(tf("document.F=Object")),t.close(),t.F},za,Ya=function(){try{za=new ActiveXObject("htmlfile")}catch(e){}Ya=typeof document!="undefined"?document.domain&&za?Zh(za):Lx():Zh(za);for(var s=Kh.length;s--;)delete Ya[Iu][Kh[s]];return Ya()};Ax[ef]=!0;rf.exports=Object.create||function(e,t){var i;return e!==null?(Tu[Iu]=xx(e),i=new Tu,Tu[Iu]=null,i[ef]=e):i=Ya(),t===void 0?i:wx.f(i,t)}});var dr=v((BD,sf)=>{"use strict";var $x=nr();sf.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:$x(s,e,t),s}});var Ru=v((VD,of)=>{"use strict";var Mx=Me(),Dx=Pe(),Cx=Ge(),Bx=xu(),af=Ha(),Vx=dr(),_x=Fe(),Ox=Tt(),Pu=_x("iterator"),nf=!1,jt,wu,Au;[].keys&&(Au=[].keys(),"next"in Au?(wu=af(af(Au)),wu!==Object.prototype&&(jt=wu)):nf=!0);var Fx=!Cx(jt)||Mx(function(){var s={};return jt[Pu].call(s)!==s});Fx?jt={}:Ox&&(jt=Bx(jt));Dx(jt[Pu])||Vx(jt,Pu,function(){return this});of.exports={IteratorPrototype:jt,BUGGY_SAFARI_ITERATORS:nf}});var Ka=v((_D,lf)=>{"use strict";var Nx=Fe(),qx=Nx("toStringTag"),uf={};uf[qx]="z";lf.exports=String(uf)==="[object z]"});var us=v((OD,cf)=>{"use strict";var Ux=Ka(),Hx=Pe(),Xa=Ri(),jx=Fe(),Qx=jx("toStringTag"),Wx=Object,Gx=Xa(function(){return arguments}())==="Arguments",zx=function(s,e){try{return s[e]}catch(t){}};cf.exports=Ux?Xa:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=zx(e=Wx(s),Qx))=="string"?t:Gx?Xa(e):(i=Xa(e))==="Object"&&Hx(e.callee)?"Arguments":i}});var pf=v((FD,df)=>{"use strict";var Yx=Ka(),Kx=us();df.exports=Yx?{}.toString:function(){return"[object "+Kx(this)+"]"}});var ls=v((ND,ff)=>{"use strict";var Xx=Ka(),Jx=Mi().f,Zx=nr(),ew=It(),tw=pf(),iw=Fe(),hf=iw("toStringTag");ff.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(ew(r,hf)||Jx(r,hf,{configurable:!0,value:e}),i&&!Xx&&Zx(r,"toString",tw))}});var bf=v((qD,mf)=>{"use strict";var rw=Ru().IteratorPrototype,sw=xu(),aw=Xr(),nw=ls(),ow=Ci(),uw=function(){return this};mf.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=sw(rw,{next:aw(+!i,t)}),nw(s,r,!1,!0),ow[r]=uw,s}});var vf=v((UD,gf)=>{"use strict";var lw=De(),cw=$t();gf.exports=function(s,e,t){try{return lw(cw(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var yf=v((HD,Sf)=>{"use strict";var dw=Ge();Sf.exports=function(s){return dw(s)||s===null}});var If=v((jD,Tf)=>{"use strict";var pw=yf(),hw=String,fw=TypeError;Tf.exports=function(s){if(pw(s))return s;throw new fw("Can't set "+hw(s)+" as a prototype")}});var ku=v((QD,Ef)=>{"use strict";var mw=vf(),bw=Ge(),gw=ui(),vw=If();Ef.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=mw(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return gw(r),vw(a),bw(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Cf=v((WD,Df)=>{"use strict";var Sw=Le(),yw=st(),Ja=Tt(),$f=Su(),Tw=Pe(),Iw=bf(),xf=Ha(),wf=ku(),Ew=ls(),xw=nr(),Lu=dr(),ww=Fe(),Af=Ci(),Mf=Ru(),Aw=$f.PROPER,Pw=$f.CONFIGURABLE,Pf=Mf.IteratorPrototype,Za=Mf.BUGGY_SAFARI_ITERATORS,cs=ww("iterator"),Rf="keys",ds="values",kf="entries",Lf=function(){return this};Df.exports=function(s,e,t,i,r,a,n){Iw(t,e,i);var o=function(g){if(g===r&&f)return f;if(!Za&&g&&g in c)return c[g];switch(g){case Rf:return function(){return new t(this,g)};case ds:return function(){return new t(this,g)};case kf:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=s.prototype,d=c[cs]||c["@@iterator"]||r&&c[r],f=!Za&&d||o(r),p=e==="Array"&&c.entries||d,h,b,S;if(p&&(h=xf(p.call(new s)),h!==Object.prototype&&h.next&&(!Ja&&xf(h)!==Pf&&(wf?wf(h,Pf):Tw(h[cs])||Lu(h,cs,Lf)),Ew(h,u,!0,!0),Ja&&(Af[u]=Lf))),Aw&&r===ds&&d&&d.name!==ds&&(!Ja&&Pw?xw(c,"name",ds):(l=!0,f=function(){return yw(d,this)})),r)if(b={values:o(ds),keys:a?f:o(Rf),entries:o(kf)},n)for(S in b)(Za||l||!(S in c))&&Lu(c,S,b[S]);else Sw({target:e,proto:!0,forced:Za||l},b);return(!Ja||n)&&c[cs]!==f&&Lu(c,cs,f,{name:r}),Af[e]=f,b}});var Vf=v((GD,Bf)=>{"use strict";Bf.exports=function(s,e){return{value:s,done:e}}});var Mu=v((zD,qf)=>{"use strict";var Rw=ki(),$u=ns(),_f=Ci(),Ff=bu(),kw=Mi().f,Lw=Cf(),en=Vf(),$w=Tt(),Mw=rt(),Nf="Array Iterator",Dw=Ff.set,Cw=Ff.getterFor(Nf);qf.exports=Lw(Array,"Array",function(s,e){Dw(this,{type:Nf,target:Rw(s),index:0,kind:e})},function(){var s=Cw(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,en(void 0,!0);switch(s.kind){case"keys":return en(t,!1);case"values":return en(e[t],!1)}return en([t,e[t]],!1)},"values");var Of=_f.Arguments=_f.Array;$u("keys");$u("values");$u("entries");if(!$w&&Mw&&Of.name!=="values")try{kw(Of,"name",{value:"values"})}catch(s){}});var Hf=v((YD,Uf)=>{"use strict";var Bw=Fe(),Vw=Ci(),_w=Bw("iterator"),Ow=Array.prototype;Uf.exports=function(s){return s!==void 0&&(Vw.Array===s||Ow[_w]===s)}});var Du=v((KD,Qf)=>{"use strict";var Fw=us(),jf=ts(),Nw=Jr(),qw=Ci(),Uw=Fe(),Hw=Uw("iterator");Qf.exports=function(s){if(!Nw(s))return jf(s,Hw)||jf(s,"@@iterator")||qw[Fw(s)]}});var Gf=v((XD,Wf)=>{"use strict";var jw=st(),Qw=$t(),Ww=Mt(),Gw=es(),zw=Du(),Yw=TypeError;Wf.exports=function(s,e){var t=arguments.length<2?zw(s):e;if(Qw(t))return Ww(jw(t,s));throw new Yw(Gw(s)+" is not iterable")}});var Kf=v((JD,Yf)=>{"use strict";var Kw=st(),zf=Mt(),Xw=ts();Yf.exports=function(s,e,t){var i,r;zf(s);try{if(i=Xw(s,"return"),!i){if(e==="throw")throw t;return t}i=Kw(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return zf(i),t}});var rn=v((ZD,em)=>{"use strict";var Jw=ar(),Zw=st(),eA=Mt(),tA=es(),iA=Hf(),rA=lr(),Xf=Zr(),sA=Gf(),aA=Du(),Jf=Kf(),nA=TypeError,tn=function(s,e){this.stopped=s,this.result=e},Zf=tn.prototype;em.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Jw(e,i),l,c,d,f,p,h,b,S=function(y){return l&&Jf(l,"normal"),new tn(!0,y)},g=function(y){return r?(eA(y),o?u(y[0],y[1],S):u(y[0],y[1])):o?u(y,S):u(y)};if(a)l=s.iterator;else if(n)l=s;else{if(c=aA(s),!c)throw new nA(tA(s)+" is not iterable");if(iA(c)){for(d=0,f=rA(s);f>d;d++)if(p=g(s[d]),p&&Xf(Zf,p))return p;return new tn(!1)}l=sA(s,c)}for(h=a?s.next:l.next;!(b=Zw(h,l)).done;){try{p=g(b.value)}catch(y){Jf(l,"throw",y)}if(typeof p=="object"&&p&&Xf(Zf,p))return p}return new tn(!1)}});var im=v((eC,tm)=>{"use strict";var oA=rt(),uA=Mi(),lA=Xr();tm.exports=function(s,e,t){oA?uA.f(s,e,lA(0,t)):s[e]=t}});var rm=v(()=>{"use strict";var cA=Le(),dA=rn(),pA=im();cA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return dA(e,function(i,r){pA(t,i,r)},{AS_ENTRIES:!0}),t}})});var am=v((rC,sm)=>{"use strict";Mu();rm();var hA=Li();sm.exports=hA.Object.fromEntries});var om=v((sC,nm)=>{"use strict";nm.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 lm=v(()=>{"use strict";Mu();var fA=om(),mA=Ae(),bA=ls(),um=Ci();for(sn in fA)bA(mA[sn],sn),um[sn]=um.Array;var sn});var dm=v((oC,cm)=>{"use strict";var gA=am();lm();cm.exports=gA});var Cu=v((uC,pm)=>{"use strict";var vA=dm();pm.exports=vA});var hm=v(()=>{"use strict"});var Bu=v((dC,fm)=>{"use strict";var ps=Ae(),SA=$i(),yA=Ri(),an=function(s){return SA.slice(0,s.length)===s};fm.exports=function(){return an("Bun/")?"BUN":an("Cloudflare-Workers")?"CLOUDFLARE":an("Deno/")?"DENO":an("Node.js/")?"NODE":ps.Bun&&typeof Bun.version=="string"?"BUN":ps.Deno&&typeof Deno.version=="object"?"DENO":yA(ps.process)==="process"?"NODE":ps.window&&ps.document?"BROWSER":"REST"}()});var nn=v((pC,mm)=>{"use strict";var TA=Bu();mm.exports=TA==="NODE"});var gm=v((hC,bm)=>{"use strict";var IA=Mi();bm.exports=function(s,e,t){return IA.f(s,e,t)}});var ym=v((fC,Sm)=>{"use strict";var EA=Ht(),xA=gm(),wA=Fe(),AA=rt(),vm=wA("species");Sm.exports=function(s){var e=EA(s);AA&&e&&!e[vm]&&xA(e,vm,{configurable:!0,get:function(){return this}})}});var Im=v((mC,Tm)=>{"use strict";var PA=Zr(),RA=TypeError;Tm.exports=function(s,e){if(PA(e,s))return s;throw new RA("Incorrect invocation")}});var _u=v((bC,Em)=>{"use strict";var kA=De(),LA=Pe(),Vu=is(),$A=kA(Function.toString);LA(Vu.inspectSource)||(Vu.inspectSource=function(s){return $A(s)});Em.exports=Vu.inspectSource});var Fu=v((gC,Rm)=>{"use strict";var MA=De(),DA=Me(),xm=Pe(),CA=us(),BA=Ht(),VA=_u(),wm=function(){},Am=BA("Reflect","construct"),Ou=/^\s*(?:class|function)\b/,_A=MA(Ou.exec),OA=!Ou.test(wm),hs=function(e){if(!xm(e))return!1;try{return Am(wm,[],e),!0}catch(t){return!1}},Pm=function(e){if(!xm(e))return!1;switch(CA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return OA||!!_A(Ou,VA(e))}catch(t){return!0}};Pm.sham=!0;Rm.exports=!Am||DA(function(){var s;return hs(hs.call)||!hs(Object)||!hs(function(){s=!0})||s})?Pm:hs});var Lm=v((vC,km)=>{"use strict";var FA=Fu(),NA=es(),qA=TypeError;km.exports=function(s){if(FA(s))return s;throw new qA(NA(s)+" is not a constructor")}});var Nu=v((SC,Mm)=>{"use strict";var $m=Mt(),UA=Lm(),HA=Jr(),jA=Fe(),QA=jA("species");Mm.exports=function(s,e){var t=$m(s).constructor,i;return t===void 0||HA(i=$m(t)[QA])?e:UA(i)}});var Cm=v((yC,Dm)=>{"use strict";var WA=De();Dm.exports=WA([].slice)});var Vm=v((TC,Bm)=>{"use strict";var GA=TypeError;Bm.exports=function(s,e){if(s<e)throw new GA("Not enough arguments");return s}});var qu=v((IC,_m)=>{"use strict";var zA=$i();_m.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(zA)});var Ku=v((EC,Wm)=>{"use strict";var at=Ae(),YA=Mo(),KA=ar(),Om=Pe(),XA=It(),Qm=Me(),Fm=yu(),JA=Cm(),Nm=Na(),ZA=Vm(),eP=qu(),tP=nn(),Gu=at.setImmediate,zu=at.clearImmediate,iP=at.process,Uu=at.Dispatch,rP=at.Function,qm=at.MessageChannel,sP=at.String,Hu=0,fs={},Um="onreadystatechange",ms,Vi,ju,Qu;Qm(function(){ms=at.location});var Yu=function(s){if(XA(fs,s)){var e=fs[s];delete fs[s],e()}},Wu=function(s){return function(){Yu(s)}},Hm=function(s){Yu(s.data)},jm=function(s){at.postMessage(sP(s),ms.protocol+"//"+ms.host)};(!Gu||!zu)&&(Gu=function(e){ZA(arguments.length,1);var t=Om(e)?e:rP(e),i=JA(arguments,1);return fs[++Hu]=function(){YA(t,void 0,i)},Vi(Hu),Hu},zu=function(e){delete fs[e]},tP?Vi=function(s){iP.nextTick(Wu(s))}:Uu&&Uu.now?Vi=function(s){Uu.now(Wu(s))}:qm&&!eP?(ju=new qm,Qu=ju.port2,ju.port1.onmessage=Hm,Vi=KA(Qu.postMessage,Qu)):at.addEventListener&&Om(at.postMessage)&&!at.importScripts&&ms&&ms.protocol!=="file:"&&!Qm(jm)?(Vi=jm,at.addEventListener("message",Hm,!1)):Um in Nm("script")?Vi=function(s){Fm.appendChild(Nm("script"))[Um]=function(){Fm.removeChild(this),Yu(s)}}:Vi=function(s){setTimeout(Wu(s),0)});Wm.exports={set:Gu,clear:zu}});var Ym=v((xC,zm)=>{"use strict";var Gm=Ae(),aP=rt(),nP=Object.getOwnPropertyDescriptor;zm.exports=function(s){if(!aP)return Gm[s];var e=nP(Gm,s);return e&&e.value}});var Xu=v((wC,Xm)=>{"use strict";var Km=function(){this.head=null,this.tail=null};Km.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};Xm.exports=Km});var Zm=v((AC,Jm)=>{"use strict";var oP=$i();Jm.exports=/ipad|iphone|ipod/i.test(oP)&&typeof Pebble!="undefined"});var tb=v((PC,eb)=>{"use strict";var uP=$i();eb.exports=/web0s(?!.*chrome)/i.test(uP)});var ub=v((RC,ob)=>{"use strict";var hr=Ae(),lP=Ym(),ib=ar(),Ju=Ku().set,cP=Xu(),dP=qu(),pP=Zm(),hP=tb(),Zu=nn(),rb=hr.MutationObserver||hr.WebKitMutationObserver,sb=hr.document,ab=hr.process,on=hr.Promise,il=lP("queueMicrotask"),pr,el,tl,un,nb;il||(bs=new cP,gs=function(){var s,e;for(Zu&&(s=ab.domain)&&s.exit();e=bs.get();)try{e()}catch(t){throw bs.head&&pr(),t}s&&s.enter()},!dP&&!Zu&&!hP&&rb&&sb?(el=!0,tl=sb.createTextNode(""),new rb(gs).observe(tl,{characterData:!0}),pr=function(){tl.data=el=!el}):!pP&&on&&on.resolve?(un=on.resolve(void 0),un.constructor=on,nb=ib(un.then,un),pr=function(){nb(gs)}):Zu?pr=function(){ab.nextTick(gs)}:(Ju=ib(Ju,hr),pr=function(){Ju(gs)}),il=function(s){bs.head||pr(),bs.add(s)});var bs,gs;ob.exports=il});var cb=v((kC,lb)=>{"use strict";lb.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var ln=v((LC,db)=>{"use strict";db.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var _i=v(($C,pb)=>{"use strict";var fP=Ae();pb.exports=fP.Promise});var fr=v((MC,bb)=>{"use strict";var mP=Ae(),vs=_i(),bP=Pe(),gP=eu(),vP=_u(),SP=Fe(),hb=Bu(),yP=Tt(),rl=qo(),fb=vs&&vs.prototype,TP=SP("species"),sl=!1,mb=bP(mP.PromiseRejectionEvent),IP=gP("Promise",function(){var s=vP(vs),e=s!==String(vs);if(!e&&rl===66||yP&&!(fb.catch&&fb.finally))return!0;if(!rl||rl<51||!/native code/.test(s)){var t=new vs(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[TP]=i,sl=t.then(function(){})instanceof i,!sl)return!0}return!e&&(hb==="BROWSER"||hb==="DENO")&&!mb});bb.exports={CONSTRUCTOR:IP,REJECTION_EVENT:mb,SUBCLASSING:sl}});var mr=v((DC,vb)=>{"use strict";var gb=$t(),EP=TypeError,xP=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new EP("Bad Promise constructor");e=i,t=r}),this.resolve=gb(e),this.reject=gb(t)};vb.exports.f=function(s){return new xP(s)}});var Ob=v(()=>{"use strict";var wP=Le(),AP=Tt(),hn=nn(),ci=Ae(),PP=Li(),Sr=st(),Sb=dr(),yb=ku(),RP=ls(),kP=ym(),LP=$t(),pn=Pe(),$P=Ge(),MP=Im(),DP=Nu(),wb=Ku().set,ll=ub(),CP=cb(),BP=ln(),VP=Xu(),Ab=bu(),fn=_i(),cl=fr(),Pb=mr(),mn="Promise",Rb=cl.CONSTRUCTOR,_P=cl.REJECTION_EVENT,OP=cl.SUBCLASSING,al=Ab.getterFor(mn),FP=Ab.set,br=fn&&fn.prototype,Oi=fn,cn=br,kb=ci.TypeError,nl=ci.document,dl=ci.process,ol=Pb.f,NP=ol,qP=!!(nl&&nl.createEvent&&ci.dispatchEvent),Lb="unhandledrejection",UP="rejectionhandled",Tb=0,$b=1,HP=2,pl=1,Mb=2,dn,Ib,Db,Eb,Cb=function(s){var e;return $P(s)&&pn(e=s.then)?e:!1},Bb=function(s,e){var t=e.value,i=e.state===$b,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,c;try{r?(i||(e.rejection===Mb&&QP(e),e.rejection=pl),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===s.promise?n(new kb("Promise-chain cycle")):(l=Cb(u))?Sr(l,u,a,n):a(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Vb=function(s,e){s.notified||(s.notified=!0,ll(function(){for(var t=s.reactions,i;i=t.get();)Bb(i,s);s.notified=!1,e&&!s.rejection&&jP(s)}))},_b=function(s,e,t){var i,r;qP?(i=nl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),ci.dispatchEvent(i)):i={promise:e,reason:t},!_P&&(r=ci["on"+s])?r(i):s===Lb&&CP("Unhandled promise rejection",t)},jP=function(s){Sr(wb,ci,function(){var e=s.facade,t=s.value,i=xb(s),r;if(i&&(r=BP(function(){hn?dl.emit("unhandledRejection",t,e):_b(Lb,e,t)}),s.rejection=hn||xb(s)?Mb:pl,r.error))throw r.value})},xb=function(s){return s.rejection!==pl&&!s.parent},QP=function(s){Sr(wb,ci,function(){var e=s.facade;hn?dl.emit("rejectionHandled",e):_b(UP,e,s.value)})},gr=function(s,e,t){return function(i){s(e,i,t)}},vr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=HP,Vb(s,!0))},ul=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new kb("Promise can't be resolved itself");var i=Cb(e);i?ll(function(){var r={done:!1};try{Sr(i,e,gr(ul,r,s),gr(vr,r,s))}catch(a){vr(r,a,s)}}):(s.value=e,s.state=$b,Vb(s,!1))}catch(r){vr({done:!1},r,s)}}};if(Rb&&(Oi=function(e){MP(this,cn),LP(e),Sr(dn,this);var t=al(this);try{e(gr(ul,t),gr(vr,t))}catch(i){vr(t,i)}},cn=Oi.prototype,dn=function(e){FP(this,{type:mn,done:!1,notified:!1,parent:!1,reactions:new VP,rejection:!1,state:Tb,value:null})},dn.prototype=Sb(cn,"then",function(e,t){var i=al(this),r=ol(DP(this,Oi));return i.parent=!0,r.ok=pn(e)?e:!0,r.fail=pn(t)&&t,r.domain=hn?dl.domain:void 0,i.state===Tb?i.reactions.add(r):ll(function(){Bb(r,i)}),r.promise}),Ib=function(){var s=new dn,e=al(s);this.promise=s,this.resolve=gr(ul,e),this.reject=gr(vr,e)},Pb.f=ol=function(s){return s===Oi||s===Db?new Ib(s):NP(s)},!AP&&pn(fn)&&br!==Object.prototype)){Eb=br.then,OP||Sb(br,"then",function(e,t){var i=this;return new Oi(function(r,a){Sr(Eb,i,r,a)}).then(e,t)},{unsafe:!0});try{delete br.constructor}catch(s){}yb&&yb(br,cn)}wP({global:!0,constructor:!0,wrap:!0,forced:Rb},{Promise:Oi});Db=PP.Promise;RP(Oi,mn,!1,!0);kP(mn)});var Hb=v((VC,Ub)=>{"use strict";var WP=Fe(),Nb=WP("iterator"),qb=!1;try{Fb=0,hl={next:function(){return{done:!!Fb++}},return:function(){qb=!0}},hl[Nb]=function(){return this},Array.from(hl,function(){throw 2})}catch(s){}var Fb,hl;Ub.exports=function(s,e){try{if(!e&&!qb)return!1}catch(r){return!1}var t=!1;try{var i={};i[Nb]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var fl=v((_C,jb)=>{"use strict";var GP=_i(),zP=Hb(),YP=fr().CONSTRUCTOR;jb.exports=YP||!zP(function(s){GP.all(s).then(void 0,function(){})})});var Qb=v(()=>{"use strict";var KP=Le(),XP=st(),JP=$t(),ZP=mr(),eR=ln(),tR=rn(),iR=fl();KP({target:"Promise",stat:!0,forced:iR},{all:function(e){var t=this,i=ZP.f(t),r=i.resolve,a=i.reject,n=eR(function(){var o=JP(t.resolve),u=[],l=0,c=1;tR(e,function(d){var f=l++,p=!1;c++,XP(o,t,d).then(function(h){p||(p=!0,u[f]=h,--c||r(u))},a)}),--c||r(u)});return n.error&&a(n.value),i.promise}})});var Gb=v(()=>{"use strict";var rR=Le(),sR=Tt(),aR=fr().CONSTRUCTOR,bl=_i(),nR=Ht(),oR=Pe(),uR=dr(),Wb=bl&&bl.prototype;rR({target:"Promise",proto:!0,forced:aR,real:!0},{catch:function(s){return this.then(void 0,s)}});!sR&&oR(bl)&&(ml=nR("Promise").prototype.catch,Wb.catch!==ml&&uR(Wb,"catch",ml,{unsafe:!0}));var ml});var zb=v(()=>{"use strict";var lR=Le(),cR=st(),dR=$t(),pR=mr(),hR=ln(),fR=rn(),mR=fl();lR({target:"Promise",stat:!0,forced:mR},{race:function(e){var t=this,i=pR.f(t),r=i.reject,a=hR(function(){var n=dR(t.resolve);fR(e,function(o){cR(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Yb=v(()=>{"use strict";var bR=Le(),gR=mr(),vR=fr().CONSTRUCTOR;bR({target:"Promise",stat:!0,forced:vR},{reject:function(e){var t=gR.f(this),i=t.reject;return i(e),t.promise}})});var gl=v((WC,Kb)=>{"use strict";var SR=Mt(),yR=Ge(),TR=mr();Kb.exports=function(s,e){if(SR(s),yR(e)&&e.constructor===s)return e;var t=TR.f(s),i=t.resolve;return i(e),t.promise}});var Zb=v(()=>{"use strict";var IR=Le(),ER=Ht(),Xb=Tt(),xR=_i(),Jb=fr().CONSTRUCTOR,wR=gl(),AR=ER("Promise"),PR=Xb&&!Jb;IR({target:"Promise",stat:!0,forced:Xb||Jb},{resolve:function(e){return wR(PR&&this===AR?xR:this,e)}})});var eg=v(()=>{"use strict";Ob();Qb();Gb();zb();Yb();Zb()});var sg=v(()=>{"use strict";var RR=Le(),kR=Tt(),bn=_i(),LR=Me(),ig=Ht(),rg=Pe(),$R=Nu(),tg=gl(),MR=dr(),Sl=bn&&bn.prototype,DR=!!bn&&LR(function(){Sl.finally.call({then:function(){}},function(){})});RR({target:"Promise",proto:!0,real:!0,forced:DR},{finally:function(s){var e=$R(this,ig("Promise")),t=rg(s);return this.then(t?function(i){return tg(e,s()).then(function(){return i})}:s,t?function(i){return tg(e,s()).then(function(){throw i})}:s)}});!kR&&rg(bn)&&(vl=ig("Promise").prototype.finally,Sl.finally!==vl&&MR(Sl,"finally",vl,{unsafe:!0}));var vl});var ng=v((ZC,ag)=>{"use strict";hm();eg();sg();var CR=li();ag.exports=CR("Promise","finally")});var ug=v((eB,og)=>{"use strict";var BR=ng();og.exports=BR});var gn=v((tB,lg)=>{"use strict";var VR=ug();lg.exports=VR});var wg=v(()=>{"use strict";var KR=Le(),XR=rr(),JR=lr(),ZR=as(),ek=ns();KR({target:"Array",proto:!0},{at:function(e){var t=XR(this),i=JR(t),r=ZR(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});ek("at")});var Pg=v((_0,Ag)=>{"use strict";wg();var tk=li();Ag.exports=tk("Array","at")});var kg=v((O0,Rg)=>{"use strict";var ik=Pg();Rg.exports=ik});var xt=v((F0,Lg)=>{"use strict";var rk=kg();Lg.exports=rk});var Nl=v((I_,tv)=>{"use strict";var fk=Ri();tv.exports=Array.isArray||function(e){return fk(e)==="Array"}});var rv=v((E_,iv)=>{"use strict";var mk=TypeError,bk=9007199254740991;iv.exports=function(s){if(s>bk)throw mk("Maximum allowed index exceeded");return s}});var nv=v((x_,av)=>{"use strict";var gk=Nl(),vk=lr(),Sk=rv(),yk=ar(),sv=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,c=n?yk(n,o):!1,d,f;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],a>0&&gk(d)?(f=vk(d),u=sv(s,e,d,f,u,a-1)-1):(Sk(u+1),s[u]=d),u++),l++;return u};av.exports=sv});var cv=v((w_,lv)=>{"use strict";var ov=Nl(),Tk=Fu(),Ik=Ge(),Ek=Fe(),xk=Ek("species"),uv=Array;lv.exports=function(s){var e;return ov(s)&&(e=s.constructor,Tk(e)&&(e===uv||ov(e.prototype))?e=void 0:Ik(e)&&(e=e[xk],e===null&&(e=void 0))),e===void 0?uv:e}});var pv=v((A_,dv)=>{"use strict";var wk=cv();dv.exports=function(s,e){return new(wk(s))(e===0?0:e)}});var hv=v(()=>{"use strict";var Ak=Le(),Pk=nv(),Rk=$t(),kk=rr(),Lk=lr(),$k=pv();Ak({target:"Array",proto:!0},{flatMap:function(e){var t=kk(this),i=Lk(t),r;return Rk(e),r=$k(t,0),r.length=Pk(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var fv=v(()=>{"use strict";var Mk=ns();Mk("flatMap")});var bv=v(($_,mv)=>{"use strict";hv();fv();var Dk=li();mv.exports=Dk("Array","flatMap")});var vv=v((M_,gv)=>{"use strict";var Ck=bv();gv.exports=Ck});var Ls=v((D_,Sv)=>{"use strict";var Bk=vv();Sv.exports=Bk});var $s=v((C_,yv)=>{"use strict";var Vk=us(),_k=String;yv.exports=function(s){if(Vk(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return _k(s)}});var ql=v((B_,Tv)=>{"use strict";Tv.exports=`
|
|
7
|
+
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var xv=v((V_,Ev)=>{"use strict";var Ok=De(),Fk=ui(),Nk=$s(),Hl=ql(),Iv=Ok("".replace),qk=RegExp("^["+Hl+"]+"),Uk=RegExp("(^|[^"+Hl+"])["+Hl+"]+$"),Ul=function(s){return function(e){var t=Nk(Fk(e));return s&1&&(t=Iv(t,qk,"")),s&2&&(t=Iv(t,Uk,"$1")),t}};Ev.exports={start:Ul(1),end:Ul(2),trim:Ul(3)}});var Rv=v((__,Pv)=>{"use strict";var Hk=Su().PROPER,jk=Me(),wv=ql(),Av="\u200B\x85\u180E";Pv.exports=function(s){return jk(function(){return!!wv[s]()||Av[s]()!==Av||Hk&&wv[s].name!==s})}});var jl=v((O_,kv)=>{"use strict";var Qk=xv().start,Wk=Rv();kv.exports=Wk("trimStart")?function(){return Qk(this)}:"".trimStart});var $v=v(()=>{"use strict";var Gk=Le(),Lv=jl();Gk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Lv},{trimLeft:Lv})});var Dv=v(()=>{"use strict";$v();var zk=Le(),Mv=jl();zk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Mv},{trimStart:Mv})});var Bv=v((H_,Cv)=>{"use strict";Dv();var Yk=li();Cv.exports=Yk("String","trimLeft")});var _v=v((j_,Vv)=>{"use strict";var Kk=Bv();Vv.exports=Kk});var Fv=v((Q_,Ov)=>{"use strict";var Xk=_v();Ov.exports=Xk});var eS=v(()=>{"use strict"});var tS=v(()=>{"use strict"});var rS=v((kN,iS)=>{"use strict";var gL=Ge(),vL=Ri(),SL=Fe(),yL=SL("match");iS.exports=function(s){var e;return gL(s)&&((e=s[yL])!==void 0?!!e:vL(s)==="RegExp")}});var nS=v((LN,aS)=>{"use strict";var TL=Ae(),IL=Me(),sS=TL.RegExp,EL=!IL(function(){var s=!0;try{sS(".","d")}catch(u){s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor(sS.prototype,"flags").get.call(e);return o!==i||t!==i});aS.exports={correct:EL}});var uS=v(($N,oS)=>{"use strict";var xL=Mt();oS.exports=function(){var s=xL(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var dS=v((MN,cS)=>{"use strict";var wL=st(),AL=It(),PL=Zr(),lS=nS(),RL=uS(),kL=RegExp.prototype;cS.exports=lS.correct?function(s){return s.flags}:function(s){return!lS.correct&&PL(kL,s)&&!AL(s,"flags")?wL(RL,s):s.flags}});var hS=v((DN,pS)=>{"use strict";var zl=De(),LL=rr(),$L=Math.floor,Wl=zl("".charAt),ML=zl("".replace),Gl=zl("".slice),DL=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,CL=/\$([$&'`]|\d{1,2})/g;pS.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=CL;return r!==void 0&&(r=LL(r),u=DL),ML(a,u,function(l,c){var d;switch(Wl(c,0)){case"$":return"$";case"&":return s;case"`":return Gl(e,0,t);case"'":return Gl(e,n);case"<":d=r[Gl(c,1,-1)];break;default:var f=+c;if(f===0)return l;if(f>o){var p=$L(f/10);return p===0?l:p<=o?i[p-1]===void 0?Wl(c,1):i[p-1]+Wl(c,1):l}d=i[f-1]}return d===void 0?"":d})}});var bS=v(()=>{"use strict";var BL=Le(),VL=st(),Kl=De(),fS=ui(),_L=Pe(),OL=Ge(),FL=rS(),$r=$s(),NL=ts(),qL=dS(),UL=hS(),HL=Fe(),jL=Tt(),QL=HL("replace"),WL=TypeError,Yl=Kl("".indexOf),GL=Kl("".replace),mS=Kl("".slice),zL=Math.max;BL({target:"String",proto:!0},{replaceAll:function(e,t){var i=fS(this),r,a,n,o,u,l,c,d,f,p,h=0,b="";if(OL(e)){if(r=FL(e),r&&(a=$r(fS(qL(e))),!~Yl(a,"g")))throw new WL("`.replaceAll` does not allow non-global regexes");if(n=NL(e,QL),n)return VL(n,e,i,t);if(jL&&r)return GL($r(i),e,t)}for(o=$r(i),u=$r(e),l=_L(t),l||(t=$r(t)),c=u.length,d=zL(1,c),f=Yl(o,u);f!==-1;)p=l?$r(t(u,f,o)):UL(u,o,f,[],void 0,t),b+=mS(o,h,f)+p,h=f+c,f=f+d>o.length?-1:Yl(o,u,f+d);return h<o.length&&(b+=mS(o,h)),b}})});var vS=v((VN,gS)=>{"use strict";eS();tS();bS();var YL=li();gS.exports=YL("String","replaceAll")});var yS=v((_N,SS)=>{"use strict";var KL=vS();SS.exports=KL});var IS=v((ON,TS)=>{"use strict";var XL=yS();TS.exports=XL});var xS=v((FN,ES)=>{"use strict";var JL=as(),ZL=$s(),e$=ui(),t$=RangeError;ES.exports=function(e){var t=ZL(e$(this)),i="",r=JL(e);if(r<0||r===1/0)throw new t$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var kS=v((NN,RS)=>{"use strict";var PS=De(),i$=ou(),wS=$s(),r$=xS(),s$=ui(),a$=PS(r$),n$=PS("".slice),o$=Math.ceil,AS=function(s){return function(e,t,i){var r=wS(s$(e)),a=i$(t),n=r.length,o=i===void 0?" ":wS(i),u,l;return a<=n||o===""?r:(u=a-n,l=a$(o,o$(u/o.length)),l.length>u&&(l=n$(l,0,u)),s?r+l:l+r)}};RS.exports={start:AS(!1),end:AS(!0)}});var $S=v((qN,LS)=>{"use strict";var u$=$i();LS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(u$)});var MS=v(()=>{"use strict";var l$=Le(),c$=kS().start,d$=$S();l$({target:"String",proto:!0,forced:d$},{padStart:function(e){return c$(this,e,arguments.length>1?arguments[1]:void 0)}})});var CS=v((jN,DS)=>{"use strict";MS();var p$=li();DS.exports=p$("String","padStart")});var VS=v((QN,BS)=>{"use strict";var h$=CS();BS.exports=h$});var OS=v((WN,_S)=>{"use strict";var f$=VS();_S.exports=f$});var H$={};tT(H$,{ChromecastState:()=>Gr,HttpConnectionType:()=>Va,Observable:()=>Nt.Observable,PlaybackState:()=>He,Player:()=>Ta,PredefinedQualityLimits:()=>zr,SDK_VERSION:()=>U$,Subject:()=>Nt.Subject,Subscription:()=>Nt.Subscription,Surface:()=>_a,VERSION:()=>Lo,ValueSubject:()=>Nt.ValueSubject,VideoFormat:()=>Lt,VideoQuality:()=>Nt.VideoQuality,areValidLiveRecordSources:()=>gg,clientChecker:()=>K,isMobile:()=>yr});module.exports=iT(H$);var Lo="2.0.140-dev.ab9700a9.0";var He=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(He||{}),Lt=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_FMP4="HLS_FMP4",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(Lt||{});var Gr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Gr||{}),Va=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Va||{});var _a=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(_a||{}),zr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(zr||{});var Pc=Y(Di(),1),Ny=Y(je(),1);var ae=require("@vkontakte/videoplayer-shared/es2015");var $h=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Qa=class{constructor(e){this.connection$=new ae.ValueSubject(void 0);this.castState$=new ae.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new ae.Subject;this.realCastState$=new ae.ValueSubject("NOT_AVAILABLE");this.subscription=new ae.Subscription;this.isDestroyed=!1;var a;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,ae.isNonNullable)((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||$h("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ae.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,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,ae.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,ae.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,ae.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,ae.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,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=(a=i.getCurrentSession())==null?void 0:a.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,ae.assertNever)(r.sessionState)}})).add((0,ae.merge)((0,ae.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,ae.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,ae.map)(r=>r.castState)),(0,ae.observableFrom)([i.getCastState()])).pipe((0,ae.filterChanged)(),(0,ae.map)(XE),(0,ae.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=(0,ae.isNonNullable)(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();(0,ae.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,ae.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,ae.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(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:ae.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},XE=s=>{switch(s){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,ae.assertNever)(s)}};var xc=Y(je(),1),Py=Y(cr(),1),Ry=Y(Cu(),1);var Sg=Y(gn(),1);var yl=require("@vkontakte/videoplayer-shared/es2015");var Re=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,yl.assertNever)(t)}return s},di=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,yl.assertNever)(e)}};var N=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var Dt=require("@vkontakte/videoplayer-shared/es2015"),ne=class{constructor(e){this.transitionStarted$=new Dt.Subject;this.transitionEnded$=new Dt.Subject;this.transitionUpdated$=new Dt.Subject;this.forceChanged$=new Dt.Subject;this.stateChangeStarted$=(0,Dt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Dt.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,Dt.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 Il=require("@vkontakte/videoplayer-shared/es2015");var vn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}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,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||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}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}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 cg=Y(je(),1);var yr=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Sn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,cg.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=yr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return R(this,null,function*(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/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||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var yn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var nt=()=>window.ManagedMediaSource||window.MediaSource,Tr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},dg=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Tn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var _R=document.createElement("video"),OR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',FR='video/mp4; codecs="hev1.1.6.L93.B0"',pg='video/webm; codecs="vp09.00.10.08"',hg='video/webm; codecs="av01.0.00M.08"',NR='audio/mp4; codecs="mp4a.40.2"',qR='audio/webm; codecs="opus"',fg,UR=()=>R(null,null,function*(){if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(j(C({},s),{video:j(C({},s.video),{contentType:hg})})),window.navigator.mediaCapabilities.decodingInfo(j(C({},s),{video:j(C({},s.video),{contentType:pg})}))]);fg={DASH_WEBM_AV1:e,DASH_WEBM:t}});UR().catch(s=>{console.log(_R),console.error(s)});var In=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 fg}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,c,d,f,p,h,b,S,g,y,A,E;this._video=document.createElement("video");try{this._protocols={mms:Tr(),mse:dg(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let w=!!((c=(l=nt())==null?void 0:l.isTypeSupported)!=null&&c.call(l,OR)),_=!!((f=(d=nt())==null?void 0:d.isTypeSupported)!=null&&f.call(d,FR)),W=!!((h=(p=nt())==null?void 0:p.isTypeSupported)!=null&&h.call(p,NR));this._codecs={h264:w,h265:_,vp9:!!((S=(b=nt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,pg)),av1:!!((y=(g=nt())==null?void 0:g.isTypeSupported)!=null&&y.call(g,hg)),aac:W,opus:!!((E=(A=nt())==null?void 0:A.isTypeSupported)!=null&&E.call(A,qR)),mpeg:(w||_)&&W},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(w){console.error(w)}try{this.destroyVideoElement()}catch(w){console.error("Error destroying video element:",w)}}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 mg="audio/mpeg",En=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,mg))},this._codecs={mp3:!!((r=(i=nt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,mg))}}catch(a){console.error(a)}try{this.destroyAudioElement()}catch(a){console.error("Error destroying audio element:",a)}}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 bg=require("@vkontakte/videoplayer-shared/es2015");var Tl=class{constructor(){this.isInited$=new bg.ValueSubject(!1);this._displayChecker=new yn,this._deviceChecker=new Sn(this._displayChecker),this._browserChecker=new vn,this._videoChecker=new In(this._deviceChecker,this._browserChecker),this._audioChecker=new En,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 R(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},K=new Tl;var El=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=K.video,a=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return s.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&a;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&&a||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&a;case"DASH_LIVE_CMAF":return n&&e.mp4&&a&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&a;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,Il.assertNever)(o)}})},xl=s=>{switch(s){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,Il.assertNever)(s)}},gg=s=>{let t=Object.keys(s).filter(i=>!xl(i));return El(t).length>0};var G=require("@vkontakte/videoplayer-shared/es2015");var HR=5,jR=5,QR=500,vg=7e3,Ss=class{constructor(e){this.subscription=new G.Subscription;this.loadMediaTimeoutSubscription=new G.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(),a=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(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.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,G.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,G.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,G.assertNever)(e)}break}default:(0,G.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(xl(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 G.Subscription;this.subscription.add(e),this.subscription.add((0,G.merge)(this.videoState.stateChangeStarted$.pipe((0,G.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,G.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new G.Subject;e.add(r.pipe((0,G.debounce)(QR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,G.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-a)>HR)&&r.next(o),a=o})),e.add((0,G.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,G.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,G.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,G.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=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()&&a.duration-a.currentTime<jR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),N(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,G.assertNever)(n)}}),t((0,G.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,G.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,G.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.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"),N(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),N(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=this.createMediaInfo(e),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"),N(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"),N(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"&&N(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a: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()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let c=t[e];(0,G.assertNonNullable)(c);let d=(0,G.getHighestQuality)(Object.keys(c));(0,G.assertNonNullable)(d);let f=c[d];(0,G.assertNonNullable)(f),i=f,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=t[e];(0,G.assertNonNullable)(c),i=c.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,G.assertNonNullable)(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,G.assertNonNullable)(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,G.assertNonNullable)(c),i=Re(c.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:G.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,G.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,G.isNonNullable)(o)&&(n.metadata.title=o),(0,G.isNonNullable)(u)&&(n.metadata.subtitle=u),n}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,a)=>{this.loadMediaTimeoutSubscription.add((0,G.timeout)(vg).subscribe(()=>a(`timeout(${vg})`)))});(0,Sg.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 a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:G.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Ol=Y(je(),1);var Rl=require("@vkontakte/videoplayer-shared/es2015");var yg=require("@vkontakte/videoplayer-shared/es2015"),Tg=s=>{try{s.pause(),s.playbackRate=0,(0,yg.clearVideoElement)(s),s.remove()}catch(e){console.error(e)}};var xn=require("@vkontakte/videoplayer-shared/es2015"),wl=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)}},Al=window.WeakMap?new WeakMap:new wl,Pl=window.WeakMap?new WeakMap:new Map,WR=(s,e=20)=>{let t=0;return(0,xn.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},ze=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?(0,Rl.clearVideoElement)(i):(i=document.createElement("video"),s.appendChild(i)),Al.set(i,r);let a=new xn.Subscription;return a.add(WR(i,e)),Pl.set(i,a),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},Ye=s=>{let e=Pl.get(s);e==null||e.unsubscribe(),Pl.delete(s);let t=Al.get(s);Al.delete(s),t?(0,Rl.clearVideoElement)(s):Tg(s)};var kl=Y(Di(),1),z=require("@vkontakte/videoplayer-shared/es2015");var pi=require("@vkontakte/videoplayer-shared/es2015"),wn=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,pi.isNullable)(r),l=new pi.Subscription;return r&&l.add(r.subscribe(c=>{let d=s.getState();i(c,d)&&s.setState(c)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),u&&s.setState(c.to)},a)),l},Ct=(s,e,t)=>wn(e,()=>s.loop,i=>{(0,pi.isNonNullable)(i)&&(s.loop=i)},{onError:t}),Ke=(s,e,t,i)=>wn(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,pi.isNonNullable)(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),pt=(s,e,t,i)=>wn(e,()=>s.playbackRate,r=>{(0,pi.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),ys=wn;var GR=s=>["__",s.language,s.label].join("|"),zR=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Ll=class s{constructor(e){this.available$=new z.Subject;this.current$=new z.ValueSubject(void 0);this.error$=new z.Subject;this.subscription=new z.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=a=>{this.error$.next({id:"TextTracksManager",category:z.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};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(ys(t.internalTextTracks,()=>(0,kl.default)(this.internalTracks),a=>{(0,z.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,n)=>(0,z.isNonNullable)(a)&&(0,z.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ys(t.externalTextTracks,()=>(0,kl.default)(this.externalTracks),a=>{(0,z.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,n)=>(0,z.isNonNullable)(a)&&(0,z.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ys(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(ys(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,z.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,z.merge)((0,z.fromEvent)(e,"addtrack"),(0,z.fromEvent)(e,"removetrack"),(0,z.observableFrom)(["init"])).pipe((0,z.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,z.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add((0,z.merge)((0,z.fromEvent)(e,"change"),(0,z.observableFrom)(["init"])).pipe((0,z.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,z.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,z.filterChanged)()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,c,d,f,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((f=(d=o.target)==null?void 0:d.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,z.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,z.isNonNullable)(t.align)&&(r.align=t.align),(0,z.isNonNullable)(t.position)&&(r.position=t.position),(0,z.isNonNullable)(t.size)&&(r.size=t.size),(0,z.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,z.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:GR(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).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,z.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,z.isNullable)(e)||!zR(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,z.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,z.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)}},ht=Ll;var Fi=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Ig=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},$l=s=>{let e=Ig(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Eg=s=>{let e=Ig(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var D=require("@vkontakte/videoplayer-shared/es2015");var YR=3,xg=(s,e,t=YR)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var Xe=s=>{let e=M=>(0,D.fromEvent)(s,M).pipe((0,D.mapTo)(void 0),(0,D.shareReplay)(1)),t=new D.Subscription,i=()=>t.unsubscribe(),r=(0,D.merge)((0,D.fromEvent)(s,"progress"),(0,D.fromEvent)(s,"timeupdate")).pipe((0,D.map)(()=>xg(s.buffered,s.currentTime)),(0,D.shareReplay)(1)),a=K.browser.isSafari?(0,D.combine)({play:e("play").pipe((0,D.once)()),playing:e("playing")}).pipe((0,D.mapTo)(void 0),(0,D.shareReplay)(1)):e("playing"),n=(0,D.fromEvent)(s,"volumechange").pipe((0,D.map)(()=>({muted:s.muted,volume:s.volume})),(0,D.shareReplay)(1)),o=(0,D.fromEvent)(s,"ratechange").pipe((0,D.map)(()=>s.playbackRate),(0,D.shareReplay)(1)),u=(0,D.fromEvent)(s,"error").pipe((0,D.filter)(()=>!!(s.error||s.played.length)),(0,D.map)(()=>{var Q;let M=s.error;return{id:M?`MediaError#${M.code}`:"HtmlVideoError",category:D.ErrorCategory.VIDEO_PIPELINE,message:M?M.message:"Error event from HTML video element",thrown:(Q=s.error)!=null?Q:void 0}}),(0,D.shareReplay)(1)),l=(0,D.fromEvent)(s,"timeupdate").pipe((0,D.map)(()=>s.currentTime),(0,D.shareReplay)(1)),c=["waiting","seeking","seeked","timeupdate"],d=new D.Subject,f=.3,p;t.add((0,D.merge)(...c.map(M=>(0,D.fromEvent)(s,M))).subscribe(M=>{let Q=s.currentTime;s.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(Q)&&p>=s.duration-f&&Q<=f&&d.next(p),p=Q}));let h=e("pause").pipe((0,D.filter)(()=>!s.error&&p!==s.duration),(0,D.shareReplay)(1)),b=(0,D.fromEvent)(s,"enterpictureinpicture").pipe((0,D.shareReplay)(1)),S=(0,D.fromEvent)(s,"leavepictureinpicture").pipe((0,D.shareReplay)(1)),g=new D.ValueSubject(Eg(s));t.add(b.subscribe(()=>g.next(!0))),t.add(S.subscribe(()=>g.next(!1)));let y=new D.ValueSubject($l(s)),A=(0,D.fromEvent)(s,"fullscreenchange").pipe((0,D.shareReplay)(1));t.add(A.pipe((0,D.map)(()=>$l(s))).subscribe(y));let E=.1,w=1e3,_=(0,D.fromEvent)(s,"timeupdate").pipe((0,D.map)(M=>s.duration-s.currentTime<E),(0,D.filterChanged)(),(0,D.shareReplay)(1)),W=(0,D.merge)(_.pipe((0,D.filter)(M=>!s.loop&&M)),(0,D.fromEvent)(s,"ended")).pipe((0,D.throttle)(w),(0,D.mapTo)(void 0),(0,D.shareReplay)(1)),U=(0,D.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(M=>(0,D.fromEvent)(s,M)),_.pipe((0,D.map)(M=>({type:M?"ended":"unknown"})))).pipe((0,D.map)(M=>K.browser.isFirefox&&M.type==="ended"?s.readyState<2:s.readyState<3),(0,D.filterChanged)(),(0,D.shareReplay)(1));return{playing$:a,pause$:h,canplay$:e("canplay"),ended$:W,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,D.fromEvent)(s,"durationchange").pipe((0,D.map)(()=>s.duration),(0,D.shareReplay)(1)),isBuffering$:U,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y,enterPip$:b,leavePip$:S,destroy:i}};var Wt=require("@vkontakte/videoplayer-shared/es2015"),hi=s=>{switch(s){case"mobile":return Wt.VideoQuality.Q_144P;case"lowest":return Wt.VideoQuality.Q_240P;case"low":return Wt.VideoQuality.Q_360P;case"sd":case"medium":return Wt.VideoQuality.Q_480P;case"hd":case"high":return Wt.VideoQuality.Q_720P;case"fullhd":case"full":return Wt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Wt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Wt.VideoQuality.Q_2160P}};var We=Y(xt(),1),Dl=Y(je(),1),Ni=Y(cr(),1),B=require("@vkontakte/videoplayer-shared/es2015");var Ml=!1,Gt={},$g=s=>{Ml=s},Mg=()=>{Gt={}},Dg=s=>{s(Gt)},Ts=(s,e)=>{var t;Ml&&(Gt.meta=(t=Gt.meta)!=null?t:{},Gt.meta[s]=e)},Qe=class{constructor(e){this.name=e}next(e){var i,r;if(!Ml)return;Gt.series=(i=Gt.series)!=null?i:{};let t=(r=Gt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Gt.series[this.name]=t}};var $e=require("@vkontakte/videoplayer-shared/es2015");function Cg(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Ir(s,e,t){return(0,$e.isNullable)(s)||(0,$e.isNonNullable)(s.min)&&(0,$e.isNonNullable)(s.max)&&(0,$e.isLower)(s.max,s.min)||(0,$e.isNonNullable)(s.min)&&e&&(0,$e.isHigher)(s.min,e)||(0,$e.isNonNullable)(s.max)&&t&&(0,$e.isLower)(s.max,t)}function Bg({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Ir({max:s!=null&&s.max?(0,$e.videoHeightToQuality)(s.max):void 0,min:s!=null&&s.min?(0,$e.videoHeightToQuality)(s.min):void 0},e?(0,$e.videoHeightToQuality)(e):void 0,t?(0,$e.videoHeightToQuality)(t):void 0)}var Ng=new Qe("best_bitrate"),Pn=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Er=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),fi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,B.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Rn='Assertion "ABR Tracks is empty array" failed',An=new WeakMap,Vg=new WeakMap,_g=new WeakMap,Is=(s,e,t,i)=>{var u;let r=[...e].sort(Er(1)),a=[...t].sort(Er(1)),n=a.filter(l=>(0,B.isNonNullable)(l.bitrate)&&(0,B.isNonNullable)(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,We.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,We.default)(a,-1);return o&&(0,Dl.default)(n,o)?o:n.length?(0,We.default)(n,-1):(0,We.default)(a,0)},Es=(s,e,t,i)=>{var u;let r=An.get(e);r||(r=[...e].sort(Er(1)),An.set(e,r));let a=An.get(t);a||(a=[...t].sort(Er(1)),An.set(t,a));let n=_g.get(s);n||(n=a.filter(l=>(0,B.isNonNullable)(l.bitrate)&&(0,B.isNonNullable)(s.bitrate)?s.bitrate/l.bitrate>i:!0),_g.set(s,n));let o=(u=(0,We.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,We.default)(a,-1);return o&&(0,Dl.default)(n,o)?o:n.length?(0,We.default)(n,-1):(0,We.default)(a,0)},Og=s=>"quality"in s,kn=(s,e,t,i)=>{var n;let r=(0,B.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,B.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,B.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Og(o)?"video":"audio",l=Og(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t},
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},sk=(s,e)=>Math.log(e)/Math.log(s),qg=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&K.display.pixelRatio){let a=K.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,c=sk(n,o*a+u)+l;Number.isFinite(c)&&(r*=c)}}return(0,B.isNonNullable)(t==null?void 0:t.min)&&(0,B.isHigherOrEqual)(t.min,s.highQualityLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Fg=new WeakMap,Bt=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:b})=>{var Z,le,he,F,$;(0,B.assertNotEmptyArray)(s,Rn);let{containerSizeFactor:S,containerSizeLimit:g}=qg({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,B.isNonNullable)(o)?o:1,A=Fg.get(s);A||(A=s.filter(P=>!(0,B.isInvariantQuality)(P.quality)).sort((P,V)=>(0,B.isHigher)(P.quality,V.quality)?-1:1),Fg.set(s,A));let E=(Z=(0,We.default)(A,-1))==null?void 0:Z.quality,w=(le=(0,We.default)(A,0))==null?void 0:le.quality,_=Ir(r,w,E),W=y*Pn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),O={},U=null;for(let P of A){let V=!0;if(g)if(P.size)V=P.size.width<=g.width&&P.size.height<=g.height;else{let it=g&&(0,B.videoSizeToQuality)(g);V=it?(0,B.isLowerOrEqual)(P.quality,it):!0}if(!V){O[P.quality]="FitsContainer";continue}let q=p||t,we=(0,B.isNonNullable)(q)&&isFinite(q)&&(0,B.isNonNullable)(P.bitrate)?q-a>=P.bitrate*W:!0,tt=(r==null?void 0:r.min)===P.quality;if(!we&&!tt){O[P.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,B.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,B.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,B.isHigher)(P.quality,u.quality)){O[P.quality]="Buffer";continue}if(!!d&&(0,B.isHigherOrEqual)(P.quality,d)&&!tt){O[P.quality]="DroppedFramesLimit";continue}if(!!f&&(0,B.isHigherOrEqual)(P.quality,f)&&!tt){O[P.quality]="StallsLimit";continue}let _e=_||((0,B.isNullable)(r==null?void 0:r.max)||(0,B.isLowerOrEqual)(P.quality,r.max))&&((0,B.isNullable)(r==null?void 0:r.min)||(0,B.isHigherOrEqual)(P.quality,r.min)),Oe=(0,B.isNonNullable)(c)&&!c?(0,B.isLowerOrEqual)(P.quality,i.backgroundVideoQualityLimit):!0;if(!_e||!Oe){O[P.quality]="FitsQualityLimits";continue}U||(U=P)}U&&U.bitrate&&Ng.next(U.bitrate);let M=(he=U!=null?U:(0,We.default)(A,-1))!=null?he:s[0],Q=l==null?void 0:l.last,H=kn(i,h,M,l);return(0,B.isNonNullable)(l)&&H.quality!==(Q==null?void 0:Q.quality)&&h({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${s.map(P=>{var
|
|
12
|
+
${s.map(P=>{var V,q;return`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate}, size: ${(V=P.size)==null?void 0:V.width}:${(q=P.size)==null?void 0:q.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,Ni.default)(i!=null?i:{}).map(([P,
|
|
16
|
+
${(0,Ni.default)(i!=null?i:{}).map(([P,V])=>`${P}: ${V}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
@@ -34,19 +34,19 @@
|
|
|
34
34
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,Ni.default)(O).map(([P,
|
|
37
|
+
${(0,Ni.default)(O).map(([P,V])=>`${P}: ${V}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
40
|
[best video track] ${U==null?void 0:U.quality}
|
|
41
41
|
[selected video track] ${H==null?void 0:H.quality}
|
|
42
|
-
`}),H}
|
|
42
|
+
`}),H},Ln=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:b})=>{var le,he,F,$,P;(0,B.assertNotEmptyArray)(s,Rn);let{containerSizeFactor:S,containerSizeLimit:g}=qg({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,B.isNonNullable)(o)?o:1,A=s.filter(V=>!(0,B.isInvariantQuality)(V.quality)).sort((V,q)=>(0,B.isHigher)(V.quality,q.quality)?-1:1),E=(le=(0,We.default)(A,-1))==null?void 0:le.quality,w=(he=(0,We.default)(A,0))==null?void 0:he.quality,_=Ir(r,w,E),W=y*Pn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),O={},M=A.filter(V=>{let q=!0;if(g)if(V.size)q=V.size.width<=g.width&&V.size.height<=g.height;else{let qt=g&&(0,B.videoSizeToQuality)(g);q=qt?(0,B.isLowerOrEqual)(V.quality,qt):!0}if(!q)return O[V.quality]="FitsContainer",!1;let we=p||t,tt=(0,B.isNonNullable)(we)&&isFinite(we)&&(0,B.isNonNullable)(V.bitrate)?we-a>=V.bitrate*W:!0,Se=(r==null?void 0:r.min)===V.quality;if(!tt&&!Se)return O[V.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,B.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,B.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,B.isHigher)(V.quality,u.quality))return O[V.quality]="Buffer",!1;if(!!d&&(0,B.isHigherOrEqual)(V.quality,d)&&!Se)return O[V.quality]="DroppedFramesLimit",!1;if(!!f&&(0,B.isHigherOrEqual)(V.quality,f)&&!Se)return O[V.quality]="StallsLimit",!1;let Oe=_||((0,B.isNullable)(r==null?void 0:r.max)||(0,B.isLowerOrEqual)(V.quality,r.max))&&((0,B.isNullable)(r==null?void 0:r.min)||(0,B.isHigherOrEqual)(V.quality,r.min)),it=(0,B.isNonNullable)(c)&&!c?(0,B.isLowerOrEqual)(V.quality,i.backgroundVideoQualityLimit):!0;return!Oe||!it?(O[V.quality]="FitsQualityLimits",!1):!0})[0];M&&M.bitrate&&Ng.next(M.bitrate);let Q=(F=M!=null?M:(0,We.default)(A,-1))!=null?F:s[0],H=l==null?void 0:l.last,Z=kn(i,h,Q,l);return(0,B.isNonNullable)(l)&&Z.quality!==(H==null?void 0:H.quality)&&h({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${s.map(
|
|
45
|
+
${s.map(V=>{var q,we;return`{ id: ${V.id}, quality: ${V.quality}, bitrate: ${V.bitrate}, size: ${(q=V.size)==null?void 0:q.width}:${(we=V.size)==null?void 0:we.height} }`}).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,Ni.default)(i!=null?i:{}).map(([
|
|
49
|
+
${(0,Ni.default)(i!=null?i:{}).map(([V,q])=>`${V}: ${q}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
@@ -67,12 +67,12 @@
|
|
|
67
67
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
68
68
|
|
|
69
69
|
[limited video tracks]
|
|
70
|
-
${(0,Ni.default)(O).map(([
|
|
70
|
+
${(0,Ni.default)(O).map(([V,q])=>`${V}: ${q}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
73
|
[best video track] ${M==null?void 0:M.quality}
|
|
74
74
|
[selected video track] ${Z==null?void 0:Z.quality}
|
|
75
|
-
`}),Z}
|
|
75
|
+
`}),Z},$n=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,B.assertNotEmptyArray)(t,Rn);let c=r.considerPlaybackRate&&(0,B.isNonNullable)(a)?a:1,d=[...t].sort(Er(-1)),f=s.bitrate;(0,B.assertNonNullable)(f);let p=c*Pn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,b=Is(s,e,t,r.minVideoAudioRatio),S=l||i;(0,B.isNonNullable)(S)&&isFinite(S)&&(h=d.find(A=>(0,B.isNonNullable)(A.bitrate)&&(0,B.isNonNullable)(b==null?void 0:b.bitrate)?S-f>=A.bitrate*p&&A.bitrate>=b.bitrate:!1)),h||(h=b);let g=o==null?void 0:o.last,y=h&&kn(r,u,h,o);return(0,B.isNonNullable)(o)&&(y==null?void 0:y.bitrate)!==(g==null?void 0:g.bitrate)&&u({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
78
|
${t.map(A=>`{ id: ${A.id}, bitrate: ${A.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},Mn=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,B.assertNotEmptyArray)(t,Rn);let c=r.considerPlaybackRate&&(0,B.isNonNullable)(a)?a:1,d=Vg.get(t);d||(d=[...t].sort(Er(-1)),Vg.set(t,d));let f=s.bitrate;(0,B.assertNonNullable)(f);let p=c*Pn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,b=Es(s,e,t,r.minVideoAudioRatio),S=l||i;(0,B.isNonNullable)(S)&&isFinite(S)&&(h=d.find(A=>(0,B.isNonNullable)(A.bitrate)&&(0,B.isNonNullable)(b==null?void 0:b.bitrate)?S-f>=A.bitrate*p&&A.bitrate>=b.bitrate:!1)),h||(h=b);let g=o==null?void 0:o.last,y=h&&kn(r,u,h,o);return(0,B.isNonNullable)(o)&&(y==null?void 0:y.bitrate)!==(g==null?void 0:g.bitrate)&&u({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
99
|
${t.map(A=>`{ id: ${A.id}, bitrate: ${A.bitrate} }`).join(`
|
|
@@ -114,14 +114,14 @@
|
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
116
|
[selected audio track] ${y==null?void 0:y.id}
|
|
117
|
-
`}),y};var Ne=s=>new URL(s).hostname;var ee=require("@vkontakte/videoplayer-shared/es2015");var zg=Y(xt(),1);var jg=Y(je(),1);var Hg=s=>{if(s instanceof DOMException&&(0,jg.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},Je=(s,e)=>R(null,null,function*(){let t=s.muted;try{yield s.play()}catch(i){if(!Hg(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{yield s.play()}catch(r){return Hg(r)&&(s.muted=!1,console.warn(r)),!1}}return!0});var ot=require("@vkontakte/videoplayer-shared/es2015");var Qg=Y(Di(),1),Vt=require("@vkontakte/videoplayer-shared/es2015");function Ce(){return(0,Vt.now)()}function Vl(s){return Ce()-s}function _l(s){let e=s.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 l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Wg(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function xr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,c,d,f=!1,p="arraybuffer",h=7e3,b=2e3,S=()=>{if(u)return;(0,Vt.assertNonNullable)(c);let H=Vl(c),Z;if(H<b){Z=b-H,setTimeout(S,Z);return}b*=2,b>h&&(b=h),n&&n.abort(),n=new r,_()},g=H=>(a=H,Q),y=H=>(d=H,Q),A=()=>(p="json",Q),E=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,d&&d(),t&&t()}},w=H=>(f=H,Q),_=()=>{c=Ce(),n=new r,n.open("get",s);let H=0,Z,le=0,he=()=>((0,Vt.assertNonNullable)(c),Math.max(c,Math.max(Z||0,le||0)));if(a&&n.addEventListener("progress",F=>{let $=Ce();a.updateChunk&&F.loaded>H&&(a.updateChunk(he(),F.loaded-H),H=F.loaded,Z=$)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;(0,Vt.assertNonNullable)(n);let F=n.status;if(F>=200&&F<300){let{response:$,responseType:P}=n,B=$==null?void 0:$.byteLength;if(typeof B=="number"&&a){let q=B-H;q&&a.updateChunk&&a.updateChunk(he(),q)}P==="json"&&(!$||!(0,Qg.default)($).length)?E():(d&&d(),e($))}else E()}),n.addEventListener("error",()=>{E()}),f){let F=()=>{(0,Vt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(le=Ce(),n.removeEventListener("readystatechange",F))};n.addEventListener("readystatechange",F)}return n.responseType=p,n.send(),Q},Q={withBitrateReporting:g,withParallel:w,withJSONResponse:A,withRetryCount:H=>(l=H,Q),withRetryInterval:(H,Z)=>((0,Vt.isNonNullable)(H)&&(b=H),(0,Vt.isNonNullable)(Z)&&(h=Z),Q),withTimeout:H=>(o=H,Q),withFinally:y,send:_,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Q}var xs=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 a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/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 Gg=Y(Di(),1);var ws=class{constructor(e,t,i,r,a){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=a}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=Ce(),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)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Ce()-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=xr(t,a,()=>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=Ce()}_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=Ce();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,Gg.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._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)),a._finallyCB&&a._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(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}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 Yg=require("@vkontakte/videoplayer-shared/es2015");var Cn=1e4,Ol=3;var ok=6e4,uk=10,lk=1,ck=500,As=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 Yg.Subject,this.chunkRateEstimator=new xs(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=_l(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&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=_l(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;e.addEventListener("error",()=>{var r,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.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"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(K.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Vg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,zg.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,ot.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Wg(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({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 ws(Ol,Cn,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,a=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let E=a&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,w,_)=>{u&&u.abort(),u=xr(this.urlResolver.resolve(E,!1),w,_,()=>this._retryCallback()).withTimeout(Cn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ol).withFinally(()=>{u=null}).send()},p=(E,w,_)=>{(0,ot.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),w,_,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=E=>{let w=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${w}=>${E}`),i.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let _=Ce()-1e4,W=0;for(let U=0;U<this.bufferStates.length;U++){let M=this.bufferStates[U];E=Math.min(E,M.buf),M.ts<_&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${E} drop=${W} jitter=${this.sourceJitter}`);let O=E-lk;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?h(1.15):O>1?h(1.1):O>.3?h(1.05):h(1)}},g=E=>{let w,_=()=>w&&w.start?w.start.length:0,W=F=>w.start[F]/1e3,O=F=>w.dur[F]/1e3,U=F=>w.fragIndex+F,M=(F,$)=>({chunkIdx:U(F),startTS:W(F),dur:O(F),discontinuity:$}),Q=()=>{let F=0;if(w&&w.dur){let $=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,P=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,B=$;this.sourceJitter>1&&(B+=this.sourceJitter-1);let q=w.dur.length-1;for(;q>=0&&(B-=w.dur[q],!(B<=0));--q);F=Math.min(q,w.dur.length-1-P),F=Math.max(F,0)}return M(F,!0)},H=F=>{let $=_();if(!($<=0)){if((0,ot.isNonNullable)(F)){for(let P=0;P<$;P++)if(W(P)>F)return M(P)}return Q()}},Z=F=>{let $=_(),P=F?F.chunkIdx+1:0,B=P-w.fragIndex;if(!($<=0)){if(!F||B<0||B-$>uk)return t(`Resync: offset=${B} bChunks=${$} chunk=`+JSON.stringify(F)),Q();if(!(B>=$))return M(P-w.fragIndex,!1)}},le=(F,$,P)=>{l&&l.abort(),l=xr(this.urlResolver.resolve(F,!0,this.lowLatency),$,P,()=>this._retryCallback()).withTimeout(Cn).withRetryCount(Ol).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(F,$)=>{le(E,P=>{if(!d())return;w=P;let B=!!w.lowLatency;B!==this.lowLatency&&b(B);let q=0;for(let we=0;we<w.dur.length;++we)q+=w.dur[we];q>0&&((0,ot.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(q/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,F(H($))},()=>this._handleNetworkError())},nextChunk:Z}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,ot.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:w,logger:_}=this.params,W=g(e.jidxUrl),O,U,M,Q,H=0,Z,le,he,F=()=>{Z&&(clearTimeout(Z),Z=void 0);let de=Math.max(ck,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ve=H+de,_e=Ce(),Oe=Math.min(1e4,Ve-_e);H=_e;let it=()=>{l||d()&&W.seek(()=>{d()&&(H=Ce(),$(),F())})};Oe>0?Z=window.setTimeout(()=>{this.paused?F():it()},Oe):it()},$=()=>{let de;for(;de=W.nextChunk(Q);)Q=de,tt(de);let Ve=W.nextChunk(M);if(Ve){if(M&&Ve.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?F():(y(),this._initPlayerWith(e));return}we(Ve)}else F()},P=(de,Ve)=>{if(!d()||!this.sourceBuffer)return;let _e,Oe,it,qt=ti=>{window.setTimeout(()=>{d()&&P(de,Ve)},ti)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),qt(100);else{let ti=Ce(),yi=w.currentTime;!this.paused&&w.buffered.length>1&&le===yi&&ti-he>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),le!==yi&&(le=yi,he=ti);let Ki=this._getBufferSizeSec();if(Ki>30)_(`Buffered ${Ki} seconds; delaying appendBuffer`),qt(2e3);else try{this.sourceBuffer.appendBuffer(de),this.videoPlayStarted?(this.bufferStates.push({ts:ti,buf:Ki}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ve&&Ve()}catch(Fr){if(Fr.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),it=this.sourceBuffer.buffered.length,it!==0&&(_e=this.sourceBuffer.buffered.start(0),Oe=yi,Oe-_e>4&&this.sourceBuffer.remove(_e,Oe-3)),qt(1e3);else throw Fr}}},B=()=>{U&&O&&(_([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(M)]),P(U,function(){U=null,$()}))},q=de=>e.fragUrlTemplate.replace("%%id%%",de.chunkIdx),we=de=>{d()&&p(q(de),(Ve,_e)=>{if(d()){if(_e/=1e3,U=Ve,M=de,n=de.startTS,_e){let Oe=Math.min(10,de.dur/_e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Oe:Oe}B()}},()=>this._handleNetworkError())},tt=de=>{d()&&((0,ot.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(q(de),!1)))},Se=de=>{d()&&(e.cachedHeader=de,P(de,()=>{O=!0,B()}))};a=!0,W.seek(de=>{if(d()){if(H=Ce(),!de){F();return}Q=de,!(0,ot.isNullable)(E)||de.startTS>E?we(de):(M=de,$())}},E),e.cachedHeader?Se(e.cachedHeader):f(e.headerUrl,Se,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,ot.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,ot.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,ot.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),h=d/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},a={updateChunk:(f,p)=>{let h=Ce();if(this.chunkRateEstimator.addInterval(f,h,p)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:S}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=a.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Vl(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,f)=>{let p=a.updateChunk(d,f);return p&&l(),p},notifySwitch:d=>{let f=Ce();d<o&&(n=f),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=xr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Cn).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;Je(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(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))},ok))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Kg=Y(cr(),1),xe=require("@vkontakte/videoplayer-shared/es2015"),Fl=class{constructor(){this.onDroopedVideoFramesLimit$=new xe.Subject;this.subscription=new xe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new xe.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,xe.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,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&(0,xe.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,xe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,xe.interval)(this.droppedFramesChecker.checkTime).pipe((0,xe.filter)(()=>this.playing),(0,xe.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,xe.debounce)(this.droppedFramesChecker.checkTime)),i=(0,xe.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,Kg.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>(0,xe.isLower)(a,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}},wr=Fl;var Bn=require("@vkontakte/videoplayer-shared/es2015"),Xg=require("@vkontakte/videoplayer-shared/es2015");var Ps=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var dk=(s,e)=>new Bn.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ps()))},C(C({},i),e));r.observe(s);let a=(0,Xg.fromEvent)(document,"visibilitychange").pipe((0,Bn.map)(n=>!document.hidden||Ps())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),ft=dk;var pk=["paused","playing","ready"],hk=["paused","playing","ready"],Rs=class{constructor(e){this.subscription=new ee.Subscription;this.videoState=new ne("stopped");this.representations$=new ee.ValueSubject([]);this.droppedFramesManager=new wr;this.maxSeekBackTime$=new ee.ValueSubject(1/0);this.zeroTime$=new ee.ValueSubject(void 0);this.liveOffset=new Fi;this._dashCb=e=>{var t,i,r,a;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:ee.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=hi(u.name))!=null?i:(0,ee.videoSizeToQuality)(u.video),d=u.bitrate/1e3,f=C({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:f};o.push({track:p,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=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,ee.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(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),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,Nl.default)(hk,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,Nl.default)(pk,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Re(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"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),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(Re(this.params.source.url,u))}return;default:return(0,ee.assertNever)(e)}};this.textTracksManager=new ht(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:ee.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,ee.merge)(this.videoState.stateChangeStarted$.pipe((0,ee.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ee.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=ze(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(Ne(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=Xe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,ee.map)(r=>r.map(({track:a})=>a)),(0,ee.filter)(r=>!!r.length),(0,ee.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,ee.filterChanged)(),(0,ee.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,ee.combine)({zeroTime:this.zeroTime$.pipe((0,ee.filter)(ee.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ct(this.video,this.params.desiredState.isLooped,t)).add(Ke(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(pt(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(ft(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&(0,ee.videoQualityToHeight)(r),min:a&&(0,ee.videoQualityToHeight)(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,ee.assertNever)(r.to)}},t)).add((0,ee.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,ee.observableFrom)(["init"])).pipe((0,ee.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ye(this.video)}createLiveDashPlayer(){let e=new As({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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,f,p,h;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(f=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,ee.isNonNullable)(t)?t:Bt(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}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let b=(h=e.find(({track:S})=>S.id===a))==null?void 0:h.representation;(0,ee.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,ee.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",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Re(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Jg=Rs;var uy=Y(je(),1);var Be=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var ie=require("@vkontakte/videoplayer-shared/es2015");var{NativeAbortSignal:l_,NativeAbortController:c_}=function(s){return{NativeAbortSignal:s.AbortSignal,NativeAbortController:s.AbortController}}(typeof self!="undefined"?self:global);function Zg(s){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=s,e}function ev(s){if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason"),Object.defineProperty(s,"name",{value:"AbortError"})}catch(e){s=new Error("This operation was aborted"),s.name="AbortError"}return s}var Vn=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,a=i.length;r<a;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,a=i.length;r<a;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}},Ar=class extends Vn{constructor(){super(),this.listeners||Vn.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 qi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new qi;function i(){t.abort(this.reason),r()}function r(){for(let a of e)a.removeEventListener("abort",i)}for(let a of e)if(a.aborted){t.abort(a.reason);break}else a.addEventListener("abort",i);return t.signal}},qi=class{constructor(){Object.defineProperty(this,"signal",{value:new Ar,writable:!0,configurable:!0})}abort(e){let t=ev(e),i=Zg(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(qi.prototype[Symbol.toStringTag]="AbortController",Ar.prototype[Symbol.toStringTag]="AbortSignal");function _n(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function ql(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!_n({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let f=new t(l,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let f=new Promise((p,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:a}}var fk=()=>"fetch"in window,ks=fk()&&_n({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),tv=ks?ql({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,mt=ks?tv.fetch:window.fetch,y_=ks?tv.Request:window.Request,fe=ks?qi:window.AbortController,T_=ks?Ar:window.AbortSignal;var sy=Y(je(),1),dc=Y(Ls(),1);var qv=Y(Nv(),1),Pr=require("@vkontakte/videoplayer-shared/es2015"),On=s=>{if(!s)return{id:"EmptyResponse",category:Pr.ErrorCategory.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Pr.ErrorCategory.NETWORK,message:`UV Error ${s}`};let e=(0,qv.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Pr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Pr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Pr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var qe=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};var I=require("@vkontakte/videoplayer-shared/es2015");var qn=Y(je(),1),ji=Y(xt(),1),Un=Y(Ls(),1);var Zk=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},eL=s=>window.clearTimeout(s),Uv=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),Hv=!Uv(window.requestIdleCallback)||!Uv(window.cancelIdleCallback),Rr=Hv?Zk:window.requestIdleCallback,_t=Hv?eL:window.cancelIdleCallback;var JS=Y(gn(),1);var mi=require("@vkontakte/videoplayer-shared/es2015");var tL=18,jv=!1;try{jv=K.browser.isSafari&&!!K.browser.safariVersion&&K.browser.safariVersion<=tL}catch(s){console.error(s)}var Gl=class{constructor(e){this.bufferFull$=new mi.Subject;this.error$=new mi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(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 R(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};jv&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!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.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(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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,mi.assertNever)(t)}}},Qv=Gl;var kr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var k=require("@vkontakte/videoplayer-shared/es2015");var Gv=Y(xt(),1);var Fn=s=>s.valid,ce=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,a;i===0?(this.size=void 0,this.valid=!1,a=void 0):i===1?(this.size=void 0,this.valid=!1,a=void 0):i>e.byteLength?(this.size=i,this.valid=!1,a=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,a=i-this.cursor),this.content=new DataView(e.buffer,r,a)}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 Lr=class extends ce{};var Wv=require("@vkontakte/videoplayer-shared/es2015");var Ms=class extends ce{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,Wv.assertNever)(e)}}};var Ds=class extends ce{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 a=this.readString(4);this.compatibleBrands.push(a)}}};var Cs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ye=class extends ce{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 Bs=class extends ye{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 Vs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _s=class extends ce{constructor(e,t){super(e,t),this.data=this.content}};var Ui=class extends ye{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(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var Os=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ns=class extends ye{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 qs=class extends ye{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Us=class extends ye{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 Hs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var js=class extends ye{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 Qs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ws=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gs=class extends ye{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var zs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ys=class extends ye{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 Ks=class extends ye{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 Xs=class extends ye{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 Js=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zs=class extends ye{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 ea=class extends ce{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 rL={ftyp:Ds,moov:Cs,mvhd:Bs,moof:Vs,mdat:_s,sidx:Ui,trak:Os,mdia:Hs,mfhd:Gs,tkhd:js,traf:zs,tfhd:Ys,tfdt:Ks,trun:Xs,minf:Qs,sv3d:Fs,st3d:Ns,prhd:qs,proj:Ws,equi:Us,uuid:Ms,stbl:Js,stsd:Zs,avc1:ea,unknown:Lr},zt=class s{constructor(e={}){this.options=C({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!Fn(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=rL[e];return i?new i(t,new s):new Lr(t,new s)}};var bi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;Fn(t)&&((a=(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 aL=new TextDecoder("ascii"),nL=s=>aL.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",oL=s=>{let e=new Ui(s,new zt),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},uL=(s,e)=>{let i=new zt().parse(s),r=new bi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,d)},lL=s=>{let t=new zt().parse(s),i=new bi(t),r={},a=i.findAll("uuid"),n=(0,Gv.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},cL=s=>{var r;let t=new zt().parse(s);return(r=new bi(t).find("sidx"))==null?void 0:r.timescale},dL=(s,e)=>{let i=new zt().parse(s),a=new bi(i).findAll("traf"),n=a[a.length-1].children.find(d=>d.type==="tfhd"),o=a[a.length-1].children.find(d=>d.type==="tfdt"),u=a[a.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,f)=>d+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},pL=s=>{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 zt().parse(s),r=new bi(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},zv={validateData:nL,parseInit:pL,getIndexRange:()=>{},parseSegments:oL,parseFeedableSegmentChunk:uL,getChunkEndTime:dL,getServerLatencyTimestamps:lL,getTimescaleFromIndex:cL};var ra=Y(je(),1),Yt=require("@vkontakte/videoplayer-shared/es2015");var Kv=require("@vkontakte/videoplayer-shared/es2015");var Yv={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"}},Xv=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ia(s,t),r=i in Yv,a=r?Yv[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,c=ia(u),d=l*kt(2,(o-1)*8)+c,f=t+o,p;return f+d>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},ia=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*kt(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*kt(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*kt(2,32)+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},wt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return ia(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:(0,Kv.assertNever)(e)}},Hi=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Xv(i);if(!e(r))return;r.type==="master"&&Hi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Jv=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Xv(s);return Hi(r.value,({tag:a,type:n,value:o})=>(a===17143?e=wt(o,n):a===17026?t=wt(o,n):a===17029&&(i=wt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Zv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],hL=[231,22612,22743,167,171,163,160,175],fL=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,c=!1,d=0;return Hi(s,({tag:f,type:p,value:h,valueSize:b})=>{if(f===21419){let S=wt(h,p);l=ia(S)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+b):f===357149030?a=!0:f===290298740?n=!0:f===2807729?i=wt(h,p):f===17545?r=wt(h,p):f===21420&&l===475249515?u=wt(h,p):f===374648427?Hi(h,({tag:S,type:g,value:y})=>S===30321?(c=wt(y,g)===1,!1):!0):a&&n&&(0,ra.default)(Zv,f)&&(o=!0),!o}),(0,Yt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Yt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Yt.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:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},mL=s=>{if((0,Yt.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},bL=(s,e)=>{let t=!1,i=!1,r=o=>(0,Yt.isNonNullable)(o.time)&&(0,Yt.isNonNullable)(o.position),a=[],n;return Hi(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=wt(l,u));break;case 183:break;case 241:n&&(n.position=wt(l,u));break;default:t&&(0,ra.default)(Zv,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:c}=o,d=a[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},gL=s=>{let e=0,t=!1;try{Hi(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ra.default)(hL,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,ra.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},eS={validateData:Jv,parseInit:fL,getIndexRange:mL,parseSegments:bL,parseFeedableSegmentChunk:gL};var Ot=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return eS;case"mp4":return zv}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Ft=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var ec=Y(ES(),1),jS=Y(cr(),1),QS=Y(FS(),1),WS=Y(xt(),1),tc=Y(Di(),1);var NS=Y(je(),1),Zl=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,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[a,n]=r.toUpperCase(),o=a+n;return(0,NS.default)(["6E","7A","F4"],o)}}return!1};var sa=require("@vkontakte/videoplayer-shared/es2015");var qS=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var US=s=>{var e;try{let t=b$(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.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:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function b$(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
117
|
+
`}),y};var Ne=s=>new URL(s).hostname;var ee=require("@vkontakte/videoplayer-shared/es2015");var Gg=Y(xt(),1);var Hg=Y(je(),1);var Ug=s=>{if(s instanceof DOMException&&(0,Hg.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},Je=(s,e)=>R(null,null,function*(){let t=s.muted;try{yield s.play()}catch(i){if(!Ug(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{yield s.play()}catch(r){return Ug(r)&&(s.muted=!1,console.warn(r)),!1}}return!0});var ot=require("@vkontakte/videoplayer-shared/es2015");var jg=Y(Di(),1),Vt=require("@vkontakte/videoplayer-shared/es2015");function Ce(){return(0,Vt.now)()}function Cl(s){return Ce()-s}function Bl(s){let e=s.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 l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Qg(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function xr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,c,d,f=!1,p="arraybuffer",h=7e3,b=2e3,S=()=>{if(u)return;(0,Vt.assertNonNullable)(c);let H=Cl(c),Z;if(H<b){Z=b-H,setTimeout(S,Z);return}b*=2,b>h&&(b=h),n&&n.abort(),n=new r,_()},g=H=>(a=H,Q),y=H=>(d=H,Q),A=()=>(p="json",Q),E=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,d&&d(),t&&t()}},w=H=>(f=H,Q),_=()=>{c=Ce(),n=new r,n.open("get",s);let H=0,Z,le=0,he=()=>((0,Vt.assertNonNullable)(c),Math.max(c,Math.max(Z||0,le||0)));if(a&&n.addEventListener("progress",F=>{let $=Ce();a.updateChunk&&F.loaded>H&&(a.updateChunk(he(),F.loaded-H),H=F.loaded,Z=$)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;(0,Vt.assertNonNullable)(n);let F=n.status;if(F>=200&&F<300){let{response:$,responseType:P}=n,V=$==null?void 0:$.byteLength;if(typeof V=="number"&&a){let q=V-H;q&&a.updateChunk&&a.updateChunk(he(),q)}P==="json"&&(!$||!(0,jg.default)($).length)?E():(d&&d(),e($))}else E()}),n.addEventListener("error",()=>{E()}),f){let F=()=>{(0,Vt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(le=Ce(),n.removeEventListener("readystatechange",F))};n.addEventListener("readystatechange",F)}return n.responseType=p,n.send(),Q},Q={withBitrateReporting:g,withParallel:w,withJSONResponse:A,withRetryCount:H=>(l=H,Q),withRetryInterval:(H,Z)=>((0,Vt.isNonNullable)(H)&&(b=H),(0,Vt.isNonNullable)(Z)&&(h=Z),Q),withTimeout:H=>(o=H,Q),withFinally:y,send:_,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Q}var xs=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 a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/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 Wg=Y(Di(),1);var ws=class{constructor(e,t,i,r,a){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=a}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=Ce(),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)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Ce()-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=xr(t,a,()=>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=Ce()}_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=Ce();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,Wg.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._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)),a._finallyCB&&a._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(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}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 zg=require("@vkontakte/videoplayer-shared/es2015");var Dn=1e4,Vl=3;var nk=6e4,ok=10,uk=1,lk=500,As=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 zg.Subject,this.chunkRateEstimator=new xs(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Bl(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&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Bl(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;e.addEventListener("error",()=>{var r,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.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"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(K.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Bg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Gg.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,ot.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Qg(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({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 ws(Vl,Dn,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,a=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let E=a&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,w,_)=>{u&&u.abort(),u=xr(this.urlResolver.resolve(E,!1),w,_,()=>this._retryCallback()).withTimeout(Dn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Vl).withFinally(()=>{u=null}).send()},p=(E,w,_)=>{(0,ot.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),w,_,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=E=>{let w=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${w}=>${E}`),i.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let _=Ce()-1e4,W=0;for(let U=0;U<this.bufferStates.length;U++){let M=this.bufferStates[U];E=Math.min(E,M.buf),M.ts<_&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${E} drop=${W} jitter=${this.sourceJitter}`);let O=E-uk;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?h(1.15):O>1?h(1.1):O>.3?h(1.05):h(1)}},g=E=>{let w,_=()=>w&&w.start?w.start.length:0,W=F=>w.start[F]/1e3,O=F=>w.dur[F]/1e3,U=F=>w.fragIndex+F,M=(F,$)=>({chunkIdx:U(F),startTS:W(F),dur:O(F),discontinuity:$}),Q=()=>{let F=0;if(w&&w.dur){let $=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,P=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,V=$;this.sourceJitter>1&&(V+=this.sourceJitter-1);let q=w.dur.length-1;for(;q>=0&&(V-=w.dur[q],!(V<=0));--q);F=Math.min(q,w.dur.length-1-P),F=Math.max(F,0)}return M(F,!0)},H=F=>{let $=_();if(!($<=0)){if((0,ot.isNonNullable)(F)){for(let P=0;P<$;P++)if(W(P)>F)return M(P)}return Q()}},Z=F=>{let $=_(),P=F?F.chunkIdx+1:0,V=P-w.fragIndex;if(!($<=0)){if(!F||V<0||V-$>ok)return t(`Resync: offset=${V} bChunks=${$} chunk=`+JSON.stringify(F)),Q();if(!(V>=$))return M(P-w.fragIndex,!1)}},le=(F,$,P)=>{l&&l.abort(),l=xr(this.urlResolver.resolve(F,!0,this.lowLatency),$,P,()=>this._retryCallback()).withTimeout(Dn).withRetryCount(Vl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(F,$)=>{le(E,P=>{if(!d())return;w=P;let V=!!w.lowLatency;V!==this.lowLatency&&b(V);let q=0;for(let we=0;we<w.dur.length;++we)q+=w.dur[we];q>0&&((0,ot.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(q/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,F(H($))},()=>this._handleNetworkError())},nextChunk:Z}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,ot.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:w,logger:_}=this.params,W=g(e.jidxUrl),O,U,M,Q,H=0,Z,le,he,F=()=>{Z&&(clearTimeout(Z),Z=void 0);let de=Math.max(lk,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ve=H+de,_e=Ce(),Oe=Math.min(1e4,Ve-_e);H=_e;let it=()=>{l||d()&&W.seek(()=>{d()&&(H=Ce(),$(),F())})};Oe>0?Z=window.setTimeout(()=>{this.paused?F():it()},Oe):it()},$=()=>{let de;for(;de=W.nextChunk(Q);)Q=de,tt(de);let Ve=W.nextChunk(M);if(Ve){if(M&&Ve.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?F():(y(),this._initPlayerWith(e));return}we(Ve)}else F()},P=(de,Ve)=>{if(!d()||!this.sourceBuffer)return;let _e,Oe,it,qt=ti=>{window.setTimeout(()=>{d()&&P(de,Ve)},ti)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),qt(100);else{let ti=Ce(),yi=w.currentTime;!this.paused&&w.buffered.length>1&&le===yi&&ti-he>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),le!==yi&&(le=yi,he=ti);let Ki=this._getBufferSizeSec();if(Ki>30)_(`Buffered ${Ki} seconds; delaying appendBuffer`),qt(2e3);else try{this.sourceBuffer.appendBuffer(de),this.videoPlayStarted?(this.bufferStates.push({ts:ti,buf:Ki}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ve&&Ve()}catch(Fr){if(Fr.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),it=this.sourceBuffer.buffered.length,it!==0&&(_e=this.sourceBuffer.buffered.start(0),Oe=yi,Oe-_e>4&&this.sourceBuffer.remove(_e,Oe-3)),qt(1e3);else throw Fr}}},V=()=>{U&&O&&(_([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(M)]),P(U,function(){U=null,$()}))},q=de=>e.fragUrlTemplate.replace("%%id%%",de.chunkIdx),we=de=>{d()&&p(q(de),(Ve,_e)=>{if(d()){if(_e/=1e3,U=Ve,M=de,n=de.startTS,_e){let Oe=Math.min(10,de.dur/_e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Oe:Oe}V()}},()=>this._handleNetworkError())},tt=de=>{d()&&((0,ot.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(q(de),!1)))},Se=de=>{d()&&(e.cachedHeader=de,P(de,()=>{O=!0,V()}))};a=!0,W.seek(de=>{if(d()){if(H=Ce(),!de){F();return}Q=de,!(0,ot.isNullable)(E)||de.startTS>E?we(de):(M=de,$())}},E),e.cachedHeader?Se(e.cachedHeader):f(e.headerUrl,Se,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,ot.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,ot.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,ot.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),h=d/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},a={updateChunk:(f,p)=>{let h=Ce();if(this.chunkRateEstimator.addInterval(f,h,p)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:S}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=a.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Cl(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,f)=>{let p=a.updateChunk(d,f);return p&&l(),p},notifySwitch:d=>{let f=Ce();d<o&&(n=f),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=xr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Dn).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;Je(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(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))},nk))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Yg=Y(cr(),1),xe=require("@vkontakte/videoplayer-shared/es2015"),_l=class{constructor(){this.onDroopedVideoFramesLimit$=new xe.Subject;this.subscription=new xe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new xe.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,xe.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,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&(0,xe.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,xe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,xe.interval)(this.droppedFramesChecker.checkTime).pipe((0,xe.filter)(()=>this.playing),(0,xe.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,xe.debounce)(this.droppedFramesChecker.checkTime)),i=(0,xe.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,Yg.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>(0,xe.isLower)(a,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}},wr=_l;var Cn=require("@vkontakte/videoplayer-shared/es2015"),Kg=require("@vkontakte/videoplayer-shared/es2015");var Ps=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var ck=(s,e)=>new Cn.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ps()))},C(C({},i),e));r.observe(s);let a=(0,Kg.fromEvent)(document,"visibilitychange").pipe((0,Cn.map)(n=>!document.hidden||Ps())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),ft=ck;var dk=["paused","playing","ready"],pk=["paused","playing","ready"],Rs=class{constructor(e){this.subscription=new ee.Subscription;this.videoState=new ne("stopped");this.representations$=new ee.ValueSubject([]);this.droppedFramesManager=new wr;this.maxSeekBackTime$=new ee.ValueSubject(1/0);this.zeroTime$=new ee.ValueSubject(void 0);this.liveOffset=new Fi;this._dashCb=e=>{var t,i,r,a;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:ee.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=hi(u.name))!=null?i:(0,ee.videoSizeToQuality)(u.video),d=u.bitrate/1e3,f=C({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:f};o.push({track:p,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=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,ee.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(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),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,Ol.default)(pk,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,Ol.default)(dk,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Re(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"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),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(Re(this.params.source.url,u))}return;default:return(0,ee.assertNever)(e)}};this.textTracksManager=new ht(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:ee.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,ee.merge)(this.videoState.stateChangeStarted$.pipe((0,ee.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ee.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=ze(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(Ne(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=Xe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,ee.map)(r=>r.map(({track:a})=>a)),(0,ee.filter)(r=>!!r.length),(0,ee.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,ee.filterChanged)(),(0,ee.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,ee.combine)({zeroTime:this.zeroTime$.pipe((0,ee.filter)(ee.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ct(this.video,this.params.desiredState.isLooped,t)).add(Ke(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(pt(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(ft(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&(0,ee.videoQualityToHeight)(r),min:a&&(0,ee.videoQualityToHeight)(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,ee.assertNever)(r.to)}},t)).add((0,ee.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,ee.observableFrom)(["init"])).pipe((0,ee.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ye(this.video)}createLiveDashPlayer(){let e=new As({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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,f,p,h;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(f=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,ee.isNonNullable)(t)?t:Bt(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}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let b=(h=e.find(({track:S})=>S.id===a))==null?void 0:h.representation;(0,ee.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,ee.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",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Re(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Xg=Rs;var oy=Y(je(),1);var Be=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var ie=require("@vkontakte/videoplayer-shared/es2015");var{NativeAbortSignal:u_,NativeAbortController:l_}=function(s){return{NativeAbortSignal:s.AbortSignal,NativeAbortController:s.AbortController}}(typeof self!="undefined"?self:global);function Jg(s){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=s,e}function Zg(s){if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason"),Object.defineProperty(s,"name",{value:"AbortError"})}catch(e){s=new Error("This operation was aborted"),s.name="AbortError"}return s}var Bn=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,a=i.length;r<a;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,a=i.length;r<a;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}},Ar=class extends Bn{constructor(){super(),this.listeners||Bn.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 qi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new qi;function i(){t.abort(this.reason),r()}function r(){for(let a of e)a.removeEventListener("abort",i)}for(let a of e)if(a.aborted){t.abort(a.reason);break}else a.addEventListener("abort",i);return t.signal}},qi=class{constructor(){Object.defineProperty(this,"signal",{value:new Ar,writable:!0,configurable:!0})}abort(e){let t=Zg(e),i=Jg(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(qi.prototype[Symbol.toStringTag]="AbortController",Ar.prototype[Symbol.toStringTag]="AbortSignal");function Vn(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Fl(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Vn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let f=new t(l,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let f=new Promise((p,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:a}}var hk=()=>"fetch"in window,ks=hk()&&Vn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ev=ks?Fl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,mt=ks?ev.fetch:window.fetch,S_=ks?ev.Request:window.Request,fe=ks?qi:window.AbortController,y_=ks?Ar:window.AbortSignal;var ry=Y(je(),1),lc=Y(Ls(),1);var Nv=Y(Fv(),1),Pr=require("@vkontakte/videoplayer-shared/es2015"),_n=s=>{if(!s)return{id:"EmptyResponse",category:Pr.ErrorCategory.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Pr.ErrorCategory.NETWORK,message:`UV Error ${s}`};let e=(0,Nv.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Pr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Pr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Pr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var qe=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};var I=require("@vkontakte/videoplayer-shared/es2015");var Nn=Y(je(),1),ji=Y(xt(),1),qn=Y(Ls(),1);var Jk=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Zk=s=>window.clearTimeout(s),qv=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),Uv=!qv(window.requestIdleCallback)||!qv(window.cancelIdleCallback),Rr=Uv?Jk:window.requestIdleCallback,_t=Uv?Zk:window.cancelIdleCallback;var XS=Y(gn(),1);var mi=require("@vkontakte/videoplayer-shared/es2015");var eL=18,Hv=!1;try{Hv=K.browser.isSafari&&!!K.browser.safariVersion&&K.browser.safariVersion<=eL}catch(s){console.error(s)}var Ql=class{constructor(e){this.bufferFull$=new mi.Subject;this.error$=new mi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(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 R(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Hv&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!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.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(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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,mi.assertNever)(t)}}},jv=Ql;var kr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var k=require("@vkontakte/videoplayer-shared/es2015");var Wv=Y(xt(),1);var On=s=>s.valid,ce=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,a;i===0?(this.size=void 0,this.valid=!1,a=void 0):i===1?(this.size=void 0,this.valid=!1,a=void 0):i>e.byteLength?(this.size=i,this.valid=!1,a=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,a=i-this.cursor),this.content=new DataView(e.buffer,r,a)}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 Lr=class extends ce{};var Qv=require("@vkontakte/videoplayer-shared/es2015");var Ms=class extends ce{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,Qv.assertNever)(e)}}};var Ds=class extends ce{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 a=this.readString(4);this.compatibleBrands.push(a)}}};var Cs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ye=class extends ce{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 Bs=class extends ye{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 Vs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _s=class extends ce{constructor(e,t){super(e,t),this.data=this.content}};var Ui=class extends ye{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(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var Os=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ns=class extends ye{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 qs=class extends ye{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Us=class extends ye{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 Hs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var js=class extends ye{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 Qs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ws=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gs=class extends ye{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var zs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ys=class extends ye{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 Ks=class extends ye{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 Xs=class extends ye{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 Js=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zs=class extends ye{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 ea=class extends ce{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 iL={ftyp:Ds,moov:Cs,mvhd:Bs,moof:Vs,mdat:_s,sidx:Ui,trak:Os,mdia:Hs,mfhd:Gs,tkhd:js,traf:zs,tfhd:Ys,tfdt:Ks,trun:Xs,minf:Qs,sv3d:Fs,st3d:Ns,prhd:qs,proj:Ws,equi:Us,uuid:Ms,stbl:Js,stsd:Zs,avc1:ea,unknown:Lr},zt=class s{constructor(e={}){this.options=C({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!On(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=iL[e];return i?new i(t,new s):new Lr(t,new s)}};var bi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;On(t)&&((a=(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 sL=new TextDecoder("ascii"),aL=s=>sL.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",nL=s=>{let e=new Ui(s,new zt),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},oL=(s,e)=>{let i=new zt().parse(s),r=new bi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,d)},uL=s=>{let t=new zt().parse(s),i=new bi(t),r={},a=i.findAll("uuid"),n=(0,Wv.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},lL=s=>{var r;let t=new zt().parse(s);return(r=new bi(t).find("sidx"))==null?void 0:r.timescale},cL=(s,e)=>{let i=new zt().parse(s),a=new bi(i).findAll("traf"),n=a[a.length-1].children.find(d=>d.type==="tfhd"),o=a[a.length-1].children.find(d=>d.type==="tfdt"),u=a[a.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,f)=>d+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},dL=s=>{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 zt().parse(s),r=new bi(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},Gv={validateData:aL,parseInit:dL,getIndexRange:()=>{},parseSegments:nL,parseFeedableSegmentChunk:oL,getChunkEndTime:cL,getServerLatencyTimestamps:uL,getTimescaleFromIndex:lL};var ra=Y(je(),1),Yt=require("@vkontakte/videoplayer-shared/es2015");var Yv=require("@vkontakte/videoplayer-shared/es2015");var zv={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"}},Kv=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ia(s,t),r=i in zv,a=r?zv[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,c=ia(u),d=l*kt(2,(o-1)*8)+c,f=t+o,p;return f+d>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},ia=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*kt(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*kt(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*kt(2,32)+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},wt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return ia(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:(0,Yv.assertNever)(e)}},Hi=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Kv(i);if(!e(r))return;r.type==="master"&&Hi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Xv=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Kv(s);return Hi(r.value,({tag:a,type:n,value:o})=>(a===17143?e=wt(o,n):a===17026?t=wt(o,n):a===17029&&(i=wt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Jv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],pL=[231,22612,22743,167,171,163,160,175],hL=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,c=!1,d=0;return Hi(s,({tag:f,type:p,value:h,valueSize:b})=>{if(f===21419){let S=wt(h,p);l=ia(S)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+b):f===357149030?a=!0:f===290298740?n=!0:f===2807729?i=wt(h,p):f===17545?r=wt(h,p):f===21420&&l===475249515?u=wt(h,p):f===374648427?Hi(h,({tag:S,type:g,value:y})=>S===30321?(c=wt(y,g)===1,!1):!0):a&&n&&(0,ra.default)(Jv,f)&&(o=!0),!o}),(0,Yt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Yt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Yt.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:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},fL=s=>{if((0,Yt.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},mL=(s,e)=>{let t=!1,i=!1,r=o=>(0,Yt.isNonNullable)(o.time)&&(0,Yt.isNonNullable)(o.position),a=[],n;return Hi(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=wt(l,u));break;case 183:break;case 241:n&&(n.position=wt(l,u));break;default:t&&(0,ra.default)(Jv,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:c}=o,d=a[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},bL=s=>{let e=0,t=!1;try{Hi(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ra.default)(pL,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,ra.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Zv={validateData:Xv,parseInit:hL,getIndexRange:fL,parseSegments:mL,parseFeedableSegmentChunk:bL};var Ot=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Zv;case"mp4":return Gv}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Ft=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Jl=Y(IS(),1),HS=Y(cr(),1),jS=Y(OS(),1),QS=Y(xt(),1),Zl=Y(Di(),1);var FS=Y(je(),1),Xl=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,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[a,n]=r.toUpperCase(),o=a+n;return(0,FS.default)(["6E","7A","F4"],o)}}return!1};var sa=require("@vkontakte/videoplayer-shared/es2015");var NS=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var qS=s=>{var e;try{let t=m$(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.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:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function m$(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
118
118
|
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
119
119
|
(-(?<script>[a-z]{4}))?
|
|
120
120
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
121
121
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
122
122
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
123
123
|
(?:-(?<privateuse>(?:${e})))?
|
|
124
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var HS=s=>{if(!(s!=null&&s.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(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={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 a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},At=(s,e)=>{let t=s;t=(0,ec.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,jS.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,ec.default)(t,n,(o,u)=>(0,sa.isNullable)(a)?o:(0,sa.isNullable)(u)?a:(0,QS.default)(a,parseInt(u,10),"0"))}return t},Nn=(s,e)=>{var U,M,Q,H,Z,le,he,F,$,P,B,q,we,tt,Se,de,Ve,_e,Oe,it,qt,ti,yi,Ki,Fr,Lc,$c,Mc,Dc,Cc,Bc,Vc,_c,Oc,Fc,Nc,qc,Uc,Hc,jc,Qc,Wc,Gc,zc,Yc,Kc,Xc,Jc,Zc,ed,td,id,rd,sd,ad,nd,od,ud,ld,cd,dd;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(gt=>{var ve,Ti;return(Ti=(ve=gt.textContent)==null?void 0:ve.trim())!=null?Ti:""}),o=(U=(0,WS.default)(n,0))!=null?U:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=a.getAttribute("publishTime"),d=a.getElementsByTagName("vk:Attrs")[0],f=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let g,y=a.getAttribute("mediaPresentationDuration"),A=[...a.getElementsByTagName("Period")],E=A.reduce((gt,ve)=>j(C({},gt),{[ve.id]:ve.children}),{}),w=A.reduce((gt,ve)=>j(C({},gt),{[ve.id]:ve.getAttribute("duration")}),{});y?g=HS(y):(0,tc.default)(w).filter(gt=>gt).length&&!u?g=(0,tc.default)(w).reduce((gt,ve)=>{var Ti;return gt+((Ti=HS(ve))!=null?Ti:0)},0):b&&(g=parseInt(b,10));let _=0,W=(Q=(M=a.getAttribute("profiles"))==null?void 0:M.split(","))!=null?Q:[];for(let gt of A.map(ve=>ve.id))for(let ve of E[gt]){let Ti=(H=ve.getAttribute("id"))!=null?H:"id"+(_++).toString(10),Nr=(Z=ve.getAttribute("mimeType"))!=null?Z:"",wo=(le=ve.getAttribute("codecs"))!=null?le:"",Ao=(he=ve.getAttribute("contentType"))!=null?he:Nr==null?void 0:Nr.split("/")[0],Uy=($=(F=ve.getAttribute("profiles"))==null?void 0:F.split(","))!=null?$:[],pd=(B=US((P=ve.getAttribute("lang"))!=null?P:""))!=null?B:{},Ia=(tt=(we=(q=ve.querySelector("Label"))==null?void 0:q.textContent)==null?void 0:we.trim())!=null?tt:void 0,Hy=ve.querySelectorAll("Representation"),jy=ve.querySelector("SegmentTemplate"),Qy=(de=(Se=ve.querySelector("Role"))==null?void 0:Se.getAttribute("value"))!=null?de:void 0,Xi=Ao,ke={id:Ti,language:pd.language,isDefault:Qy==="main",label:Ia,codecs:wo,hdr:Xi==="video"&&Zl(wo),mime:Nr,representations:[]};for(let me of Hy){let ii=(Ve=me.getAttribute("lang"))!=null?Ve:void 0,qr=(Oe=(_e=Ia!=null?Ia:ve.getAttribute("label"))!=null?_e:me.getAttribute("label"))!=null?Oe:void 0,Ea=(ti=(qt=(it=me.querySelector("BaseURL"))==null?void 0:it.textContent)==null?void 0:qt.trim())!=null?ti:"",Ii=new URL(Ea||o,e).toString(),ri=(yi=me.getAttribute("mimeType"))!=null?yi:Nr,xa=(Fr=(Ki=me.getAttribute("codecs"))!=null?Ki:wo)!=null?Fr:"",wa;if(Ao==="text"){let si=me.getAttribute("id")||"",Aa=((Lc=pd.privateuse)==null?void 0:Lc.includes("x-auto"))||si.includes("_auto"),Ei=me.querySelector("SegmentTemplate");if(Ei){let Ur={representationId:($c=me.getAttribute("id"))!=null?$c:void 0,bandwidth:(Mc=me.getAttribute("bandwidth"))!=null?Mc:void 0},Pa=parseInt((Dc=me.getAttribute("bandwidth"))!=null?Dc:"",10)/1e3,Ra=(Bc=parseInt((Cc=Ei.getAttribute("startNumber"))!=null?Cc:"",10))!=null?Bc:1,Ji=parseInt((Vc=Ei.getAttribute("timescale"))!=null?Vc:"",10),Po=(_c=Ei.querySelectorAll("SegmentTimeline S"))!=null?_c:[],Zi=Ei.getAttribute("media");if(!Zi)continue;let ka=[],La=0,$a="",er=0,Hr=Ra,Ue=0;for(let vt of Po){let xi=parseInt((Oc=vt.getAttribute("d"))!=null?Oc:"",10),dt=parseInt((Fc=vt.getAttribute("r"))!=null?Fc:"",10)||0,ai=parseInt((Nc=vt.getAttribute("t"))!=null?Nc:"",10);Ue=Number.isFinite(ai)?ai:Ue;let wi=xi/Ji*1e3,ni=Ue/Ji*1e3;for(let Pt=0;Pt<dt+1;Pt++){let oi=At(Zi,j(C({},Ur),{segmentNumber:Hr.toString(10),segmentTime:(Ue+Pt*xi).toString(10)})),tr=(ni!=null?ni:0)+Pt*wi,Qr=tr+wi;Hr++,ka.push({time:{from:tr,to:Qr},url:oi})}Ue+=(dt+1)*xi,La+=(dt+1)*wi}er=Ue/Ji*1e3,$a=At(Zi,j(C({},Ur),{segmentNumber:Hr.toString(10),segmentTime:Ue.toString(10)}));let jr={time:{from:er,to:1/0},url:$a},Ut={type:"template",baseUrl:Ii,segmentTemplateUrl:Zi,initUrl:"",totalSegmentsDurationMs:La,segments:ka,nextSegmentBeyondManifest:jr,timescale:Ji};wa={id:si,kind:"text",segmentReference:Ut,profiles:[],duration:g,bitrate:Pa,mime:"",codecs:"",width:0,height:0,isAuto:Aa}}else wa={id:si,isAuto:Aa,kind:"text",url:Ii}}else{let si=(Uc=(qc=me.getAttribute("contentType"))!=null?qc:ri==null?void 0:ri.split("/")[0])!=null?Uc:Ao,Aa=(jc=(Hc=ve.getAttribute("profiles"))==null?void 0:Hc.split(","))!=null?jc:[],Ei=parseInt((Qc=me.getAttribute("width"))!=null?Qc:"",10),Ur=parseInt((Wc=me.getAttribute("height"))!=null?Wc:"",10),Pa=parseInt((Gc=me.getAttribute("bandwidth"))!=null?Gc:"",10)/1e3,Ra=(zc=me.getAttribute("frameRate"))!=null?zc:"",Ji=(Yc=me.getAttribute("quality"))!=null?Yc:void 0,Po=Ra?qS(Ra):void 0,Zi=(Kc=me.getAttribute("id"))!=null?Kc:"id"+(_++).toString(10),ka=si==="video"?`${Ur}p`:si==="audio"?`${Pa}Kbps`:xa,La=`${Zi}@${ka}`,$a=[...W,...Uy,...Aa],er,Hr=me.querySelector("SegmentBase"),Ue=(Xc=me.querySelector("SegmentTemplate"))!=null?Xc:jy;if(Hr){let Ut=(Zc=(Jc=me.querySelector("SegmentBase Initialization"))==null?void 0:Jc.getAttribute("range"))!=null?Zc:"",[vt,xi]=Ut.split("-").map(oi=>parseInt(oi,10)),dt={from:vt,to:xi},ai=(ed=me.querySelector("SegmentBase"))==null?void 0:ed.getAttribute("indexRange"),[wi,ni]=ai?ai.split("-").map(oi=>parseInt(oi,10)):[],Pt=ai?{from:wi,to:ni}:void 0;er={type:"byteRange",url:Ii,initRange:dt,indexRange:Pt}}else if(Ue){let Ut={representationId:(td=me.getAttribute("id"))!=null?td:void 0,bandwidth:(id=me.getAttribute("bandwidth"))!=null?id:void 0},vt=parseInt((rd=Ue.getAttribute("timescale"))!=null?rd:"",10),xi=(sd=Ue.getAttribute("initialization"))!=null?sd:"",dt=Ue.getAttribute("media"),ai=(nd=parseInt((ad=Ue.getAttribute("startNumber"))!=null?ad:"",10))!=null?nd:1,wi=At(xi,Ut);if(!dt)throw new ReferenceError("No media attribute in SegmentTemplate");let ni=(od=Ue.querySelectorAll("SegmentTimeline S"))!=null?od:[],Pt=[],oi=0,tr="",Qr=0;if(ni.length){let Ma=ai,St=0;for(let ir of ni){let Rt=parseInt((ud=ir.getAttribute("d"))!=null?ud:"",10),Ai=parseInt((ld=ir.getAttribute("r"))!=null?ld:"",10)||0,Da=parseInt((cd=ir.getAttribute("t"))!=null?cd:"",10);St=Number.isFinite(Da)?Da:St;let Ro=Rt/vt*1e3,ko=St/vt*1e3;for(let Ca=0;Ca<Ai+1;Ca++){let Gy=At(dt,j(C({},Ut),{segmentNumber:Ma.toString(10),segmentTime:(St+Ca*Rt).toString(10)})),hd=(ko!=null?ko:0)+Ca*Ro,zy=hd+Ro;Ma++,Pt.push({time:{from:hd,to:zy},url:Gy})}St+=(Ai+1)*Rt,oi+=(Ai+1)*Ro}Qr=St/vt*1e3,tr=At(dt,j(C({},Ut),{segmentNumber:Ma.toString(10),segmentTime:St.toString(10)}))}else if((0,sa.isNonNullable)(g)){let St=parseInt((dd=Ue.getAttribute("duration"))!=null?dd:"",10)/vt*1e3,ir=Math.ceil(g/St),Rt=0;for(let Ai=1;Ai<ir;Ai++){let Da=At(dt,j(C({},Ut),{segmentNumber:Ai.toString(10),segmentTime:Rt.toString(10)}));Pt.push({time:{from:Rt,to:Rt+St},url:Da}),Rt+=St}Qr=Rt,tr=At(dt,j(C({},Ut),{segmentNumber:ir.toString(10),segmentTime:Rt.toString(10)}))}let Wy={time:{from:Qr,to:1/0},url:tr};er={type:"template",baseUrl:Ii,segmentTemplateUrl:dt,initUrl:wi,totalSegmentsDurationMs:oi,segments:Pt,nextSegmentBeyondManifest:Wy,timescale:vt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!si||!ri)continue;let jr={video:"video",audio:"audio",text:"text"}[si];if(!jr)continue;Xi||(Xi=jr),wa={id:La,kind:jr,segmentReference:er,profiles:$a,duration:g,bitrate:Pa,mime:ri,codecs:xa,width:Ei,height:Ur,fps:Po,quality:Ji}}ke.language||(ke.language=ii),ke.label||(ke.label=qr),ke.mime||(ke.mime=ri),ke.codecs||(ke.codecs=xa),ke.hdr||(ke.hdr=Xi==="video"&&Zl(xa)),ke.representations.push(wa)}if(Xi){let me=r[Xi].find(ii=>ii.id===ke.id);if(me&&ke.representations.every(ii=>ii.segmentReference.type==="template"))for(let ii of me.representations){let qr=ke.representations.find(ri=>ri.id===ii.id),Ea=qr==null?void 0:qr.segmentReference,Ii=ii.segmentReference;Ii.segments.push(...Ea.segments),Ii.nextSegmentBeyondManifest=Ea.nextSegmentBeyondManifest}else r[Xi].push(ke)}}return{duration:g,streams:r,baseUrls:n,live:S}};var ic=Y(xt(),1);var GS=require("@vkontakte/videoplayer-shared/es2015"),zS=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?hi(a):void 0)!=null?u:(0,GS.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},YS=({id:s,bitrate:e})=>({id:s,bitrate:e}),KS=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),XS=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),rc=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,ic.default)(i.split("."),0),isDefault:r}),sc=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,ic.default)(r.split("."),0)}),ac=s=>"url"in s,ut=s=>s.type==="template";var nc=require("@vkontakte/videoplayer-shared/es2015"),te=(s,e)=>(0,nc.isNonNullable)(s)&&(0,nc.isNonNullable)(e)&&s.readyState==="open"&&g$(s,e);function g$(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var aa=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new k.ValueSubject(0);this.currentLowLatencySegmentLength$=new k.ValueSubject(0);this.currentSegmentLength$=new k.ValueSubject(0);this.onLastSegment$=new k.ValueSubject(!1);this.fullyBuffered$=new k.ValueSubject(!1);this.playingRepresentation$=new k.ValueSubject(void 0);this.playingRepresentationInit$=new k.ValueSubject(void 0);this.error$=new k.Subject;this.gaps=[];this.subscription=new k.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new fe;this.switchAbortController=new fe;this.destroyAbortController=new fe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,k.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){let t=this.representations.get(e);(0,k.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 Qv(this.sourceBuffer),this.subscription.add((0,k.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,k.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:k.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,kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,k.assertNonNullable)(i,"No init buffer for starting representation"),(0,k.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(a))})}.bind(this));this.switchTo=(0,k.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(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,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,k.isNullable)(a)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,k.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,k.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(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,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,k.isNullable)(a)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,k.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,k.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){var u,l;let t=(u=(0,Un.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!ut(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,k.assertNonNullable)(r);let a=this.segments.get(i);(0,k.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,k.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),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 fe,(0,k.abortable)(this.switchAbortController.signal,function(i,r=!1){return oe(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,k.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,k.isNullable)(o)||(0,k.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,k.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,k.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,k.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return R(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new fe,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,k.isNullable)(e)||(0,k.isNullable)(this.downloadingRepresentationId)||(0,k.isNullable)(this.playingRepresentationId)||(0,k.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||(0,k.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,k.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);(0,k.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(a=d)}if(isFinite(this.bufferLimit)&&kr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,qn.default)(u,r))c="high";else{let d=(0,ji.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ji.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),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 a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;(0,k.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Un.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,Un.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!ut(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>j(C({},p),{status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(a=(0,ji.default)(c,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,k.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,ji.default)(e,-1))==null?void 0:t.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!ut(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),c=At(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a: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&&_t&&_t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_t&&_t(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),a=e.findIndex(({status:f,time:{from:p,to:h}},b)=>{let S=p<=i&&h>=i,g=p>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&g&&A&&this.sourceBuffer&&te(this.mediaSource,this.sourceBuffer)&&!(qe(this.sourceBuffer.buffered,p)&&qe(this.sourceBuffer.buffered,h)))&&g&&A});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=a;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}loadSegments(e,t,i="auto"){return R(this,null,function*(){ut(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return R(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:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,k.abortable)(o,function(){return oe(this,null,function*(){let c=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,k.now)(),!c)return;let d=new DataView(c),f=Ot(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ft(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ut(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return R(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:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,k.abortable)(n,function(){return oe(this,null,function*(){let u=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,k.fromEvent)(window,"online").pipe((0,k.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,k.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ft(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ut(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ji.default)(e,0).byte.from,to:(0,ji.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>R(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,k.now)(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!ut(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:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,k.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,qn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){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:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ot(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!te(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let d=c.byte.from-i,f=c.byte.to-i,p=f-d+1,h=d<r,b=f<=r;if(!h)continue;let S=Ot(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(g,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-d),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),y=l.loadedBytes===p?g:S.parseFeedableSegmentChunk(g);y!=null&&y.byteLength&&(c.status="partially_fed",l.feedingBytes+=y.byteLength,(yield this.sourceBufferTaskQueue.append(y,a))&&!a.aborted?(l.fedBytes+=y.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!((0,k.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer))){!this.isLive&&K.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qe(this.sourceBuffer.buffered,e.segment.time.from,100)&&qe(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ac(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.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,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Rr(()=>(0,JS.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return R(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,k.abortable)(this.destroyAbortController.signal,function(){return oe(this,null,function*(){let o=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ot(e.mime),r)).then(o=>R(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&ut(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:k.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(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 R(this,null,function*(){if(!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,k.isNullable)(e))return!1;let r=[],a=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:f}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,f):l.push(u[c])}return l},o=u=>{var c;if(a>=t)return r;r.push(C({},u.time)),r=n(r);let l=ac(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let f of this.segments.values())for(let p of f)(0,qn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let f={time:{from:l,to:c},url:"",status:"none"};o(f)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return R(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,k.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:k.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,k.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||(0,k.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),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:k.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var gi=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Hn=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};var X=require("@vkontakte/videoplayer-shared/es2015");var jn=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Wn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new X.Subject;this.manifestReceived=new X.Subject;this.firstBytesRequested=new X.Subject;this.firstBytesReceived=new X.Subject;this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.recoverableError$=new X.Subject;this.error$=new X.Subject;this.abortAllController=new fe;this.subscription=new X.Subscription;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,function(e){return oe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=gi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=jn(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Qn);return r?(t.log("success",(0,X.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,X.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,X.abortable)(this.abortAllController.signal,function(c){return oe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var le,he,F;let d=e,f=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{f.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(d,location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),d=$.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(d=gi(d));let h=this.abortAllController.signal,b;if(n){let $=new fe;if(b=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(P){Qn(P)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(P){Qn(P)}h=$.signal}let S=0,g=(0,X.now)();p.log("startRequest",(0,X.flattenObject)({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let y=yield this.doFetch(d,{priority:a,headers:f,signal:h}),A=(0,X.now)();if(!y)return p.error("error",{message:"No response in request"}),p.end(),b==null||b.unsubscribe(),null;if((le=this.throughputEstimator)==null||le.addRawRtt(A-g),!y.ok||!y.body){b==null||b.unsubscribe();let $=`Fetch error ${y.status}: ${y.statusText}`;return p.error("error",{message:$}),p.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){b==null||b.unsubscribe();let $=(0,X.now)(),P={requestStartedAt:g,requestEndedAt:$,duration:$-g};return p.log("endRequest",(0,X.flattenObject)(P)),p.end(),y.arrayBuffer()}let E=y.body;if(o){let $;[E,$]=y.body.tee(),(he=this.throughputEstimator)==null||he.trackStream($,u)}let w=E.getReader(),_,W=parseInt((F=y.headers.get("content-length"))!=null?F:"",10);Number.isFinite(W)&&(_=W),!_&&i&&(_=i.to-i.from+1);let O=_?new Uint8Array(_):new Uint8Array(0),U=!1,M=$=>{b==null||b.unsubscribe(),U=!0,Qn($)},Q=(0,X.abortable)(h,function(B){return oe(this,arguments,function*({done:$,value:P}){if(S===0&&(this.lastRequestFirstBytes$.next((0,X.now)()-g),this.firstBytesReceived.next()),h.aborted){b==null||b.unsubscribe();return}if(!$&&P){if(l&&_)O.set(P,S),S+=P.byteLength;else{let q=new Uint8Array(O.length+P.length);q.set(O),q.set(P,O.length),O=q,S+=P.byteLength}r==null||r(new DataView(O.buffer),S),yield w==null?void 0:w.read().then(Q,M)}})}.bind(this));yield w==null?void 0:w.read().then(Q,M),b==null||b.unsubscribe();let H=(0,X.now)(),Z={failed:U,requestStartedAt:g,requestEndedAt:H,duration:H-g};return U?(p.error("endRequest",(0,X.flattenObject)(Z)),p.end(),null):(p.log("endRequest",(0,X.flattenObject)(Z)),p.end(),O.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,function(e,t,i){return oe(this,null,function*(){var g;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(c,a))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(g=e.indexRange)!=null?g:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,p,h);return{init:p,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,X.abortable)(this.abortAllController.signal,function(e,t){return oe(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});return r?{init:null,segments:e.segments.map(n=>j(C({},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=a}onHeadersReceived(e){let{type:t,reused:i}=Hn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return R(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,X.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return R(this,null,function*(){let i=yield mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:X.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:X.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:X.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:X.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:X.ErrorCategory.FATAL})}})}},Qn=s=>{if(!Ft(s))throw s};var Kt=(s,e,t)=>t*e+(1-t)*s,oc=(s,e)=>s.reduce((t,i)=>t+i,0)/e,ZS=(s,e,t,i)=>{let r=0,a=t,n=oc(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};var na=require("@vkontakte/videoplayer-shared/es2015");var vi=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 na.ValueSubject(e.initial),this.debounced$=new na.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Qe(`raw_${t}`),this.smoothedSeries$=new Qe(`smoothed_${t}`),this.reportedSeries$=new Qe(`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+=kt(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=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>a||this.smoothed<n)&&((0,na.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 Gn=class extends vi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Kt(this.slow,e,this.params.emaAlphaSlow),this.fast=Kt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var zn=class extends vi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=oc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Kt(this.emaSmoothed,e,this.params.emaAlpha);let i=ZS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Yn=class extends vi{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?Kt(this.smoothed,t,this.params.emaAlpha):t}};var Xt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Gn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new zn({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 Yn(C({initial:e,label:"liveEdgeDelay"},t))}};var Cr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var Kn=require("@vkontakte/videoplayer-shared/es2015");var oa=class s{constructor(e,t){this.currentRepresentation$=new Kn.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,Kn.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(j(C({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.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=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ut(t.segmentReference))}};var Jn=Y(xt(),1),uc=Y(je(),1),ua=require("@vkontakte/videoplayer-shared/es2015");var Xn=s=>{let{webmDecodingInfo:e}=K.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){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,ua.assertNever)(s)}return[t,i]},ey=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Xn(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(K.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[...a,"MPEG",...Xn(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Xn(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Xn(s),...a,"HLS","HLS_ONDEMAND"];default:(0,ua.assertNever)(e)}if(K.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,ua.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},ty=({androidPreferredFormat:s,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"],a=[...i,...r],n=[...r,...i],o,u=K.device.isMac&&K.browser.isSafari;if(K.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:(0,ua.assertNever)(s)}else K.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},lc=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Zn=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Jn.default)(t.value.split("."),0)}for(let t of s){let i=(0,Jn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Jn.default)(e.value.split("."),0)},eo=s=>{let e=s.map(i=>Br(i)),{codecs:t}=K.video;return T$().filter(i=>{if((0,uc.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})},to=s=>{let e=s.map(i=>Br(i)),{codecs:t}=K.video;return I$().filter(i=>{if((0,uc.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Br=s=>s.split(".")[0].replace("0",""),T$=()=>["av1","vp9","hev1","avc1"],I$=()=>["opus","mp4a"];var w$=["timeupdate","progress","play","seeked","stalled","waiting"],A$=["timeupdate","progress","loadeddata","playing","seeked"];var io=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new I.Subscription;this.representationSubscription=new I.Subscription;this.state$=new ne("none");this.currentVideoRepresentation$=new I.ValueSubject(void 0);this.currentVideoRepresentationInit$=new I.ValueSubject(void 0);this.currentAudioRepresentation$=new I.ValueSubject(void 0);this.currentVideoSegmentLength$=new I.ValueSubject(0);this.currentAudioSegmentLength$=new I.ValueSubject(0);this.error$=new I.Subject;this.manifestRequested=new I.Subject;this.manifestReceived=new I.Subject;this.firstBytesRequested=new I.Subject;this.firstBytesReceived=new I.Subject;this.lastConnectionType$=new I.ValueSubject(void 0);this.lastConnectionReused$=new I.ValueSubject(void 0);this.lastRequestFirstBytes$=new I.ValueSubject(void 0);this.currentLiveTextRepresentation$=new I.ValueSubject(null);this.isLive$=new I.ValueSubject(!1);this.isActiveLive$=new I.ValueSubject(!1);this.isLowLatency$=new I.ValueSubject(!1);this.liveDuration$=new I.ValueSubject(0);this.liveSeekableDuration$=new I.ValueSubject(0);this.liveAvailabilityStartTime$=new I.ValueSubject(0);this.liveStreamStatus$=new I.ValueSubject(void 0);this.bufferLength$=new I.ValueSubject(0);this.liveLatency$=new I.ValueSubject(void 0);this.liveLoadBufferLength$=new I.ValueSubject(0);this.livePositionFromPlayer$=new I.ValueSubject(0);this.currentStallDuration$=new I.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new I.ValueSubject(0);this.fetcherRecoverableError$=new I.Subject;this.fetcherError$=new I.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new I.Subject;this.gapWatchdogActive=!1;this.destroyController=new fe;this.initManifest=(0,I.abortable)(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Re(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:I.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,I.abortable)(this.destroyController.signal,function(){return oe(this,null,function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=Nn(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=On(e))!=null?u:{id:"ManifestParsing",category:I.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,b,S;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((S=(b=nt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let b="active";p||(b=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(b)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:b})=>i(c,h,b));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:b})=>b);c==="audio"&&(n=to(h),p=n[0]),c==="video"&&(a=eo(h),this.forceVideoCodec&&(0,sy.default)(a,this.forceVideoCodec)?p=this.forceVideoCodec:p=a[0]),p&&(r[c]=f.filter(({codecs:b})=>Br(b)===p))}else{let h=new Set(f.map(({codecs:b})=>b));p=Zn(h),p&&(r[c]=f.filter(({codecs:b})=>b.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,b=r.video.some(g=>g.hdr),S=r.video.some(g=>!g.hdr);K.display.isHDR&&h&&b?r.video=r.video.filter(g=>g.hdr):S&&(r.video=r.video.filter(g=>!g.hdr))}}let o=j(C({},t),{streams:r});return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",(0,I.flattenObject)(o)),o})}.bind(this));this.initRepresentations=(0,I.abortable)(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var f;this.tracer.log("initRepresentationsStart",(0,I.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,I.assertNonNullable)(this.manifest),(0,I.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,I.fromEvent)(p,"error").pipe((0,I.filter)(h=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Tn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),Tr())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 aa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,I.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,b)=>[...h,...b.representations],[]);this.audioBufferManager=new aa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}oa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new oa(this.manifest.streams.text,n)),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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,I.merge)(...A$.map(p=>(0,I.fromEvent)(this.element,p))).pipe((0,I.map)(p=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),(0,I.filterChanged)(),(0,I.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,I.merge)((0,I.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,I.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,I.now)())),this.subscription.add((0,I.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,I.interval)(1e3).subscribe(h=>{let b=di(this.manifestUrlString,2);this.manifestUrlString=Re(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,I.fromEvent)(this.element,"play").subscribe(h=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add((0,I.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.map)(({isActiveLive:h,isLowLatency:b})=>h&&b),(0,I.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Cr(this.element,1)})),this.representationSubscription.add((0,I.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.filter)(({bufferLength:h,isActiveLive:b,isLowLatency:S})=>b&&S&&!!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 b=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,I.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,I.filter)(({isLive:h})=>h),(0,I.filterChanged)((h,b)=>b.bufferLength<h.bufferLength),(0,I.map)(({rtt:h,bufferLength:b,segmentServerLatency:S})=>{let g=di(this.manifestUrlString,2);return(h/2+b+S+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,I.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:b,isLowLatency:S})=>{if(!S||!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=h-g;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(E)>y&&(w=1+Math.sign(E)*A),Cr(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var S,g;let b=0;if(h){let y=((g=(S=this.element)==null?void 0:S.currentTime)!=null?g:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var w,_;return(_=(w=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?_:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add((0,I.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,I.throttle)(1e3)).subscribe(S=>R(this,[S],function*({liveLoadBufferLength:h,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,y=di(this.manifestUrlString,2),A=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(A,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,_=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,W=isFinite(h)?h:b,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),U=A<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(U);let M="none";if(O?M="active_low_latency":this.isLowLatency$.getValue()&&U?(this.bufferManagers.forEach(Q=>Q.proceedLowLatencyLive()),M="active_low_latency"):y!==0&&W<E?M="live_forward_buffering":W<E+_&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let Q=p-(E+w),H=this.normolizeLiveOffset(Math.trunc(y+Q/g)),Z=Math.abs(H-y),le=0;!h||Z<=this.tuning.dashCmafLive.offsetCalculationError?le=y:H>0&&Z>this.tuning.dashCmafLive.offsetCalculationError&&(le=H),this.manifestUrlString=Re(this.manifestUrlString,le,2)}(M==="live_with_target_offset"||M==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:I.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,I.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,I.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,I.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,I.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=(0,I.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,I.filterChanged)(),(0,I.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,I.filter)(p=>p));if(this.representationSubscription.add((0,I.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:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,I.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 b;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(b=this.source)==null||b.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,dc.default)((0,dc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let b=[];return h.duration&&b.push(h.duration),ut(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&b.push(h.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,I.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,a;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||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,I.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:I.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 Wn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Xt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,C({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,a,n;(0,I.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,I.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Re(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){(0,I.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,I.merge)(...w$.map(e=>(0,I.fromEvent)(this.element,e)),(0,I.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,I.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,I.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qe(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,b,S,g,y,A,E,w,_,W;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=(0,I.now)(),n=100,o=(b=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?g:0,l=(A=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?A:0,c=(w=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?w:0,d=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&c<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||f)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let O=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(O).catch(U=>{this.error$.next({id:"stallIntervalCallback",category:I.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:U})}),r.liveLastOffset=O}else{let O=this.element.currentTime*1e3;(_=this.videoBufferManager)==null||_.maintain(O),(W=this.audioBufferManager)==null||W.maintain(O),r.position=O}this.tracer.log("stallIntervalCallback",(0,I.flattenObject)(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,I.interval)(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:I.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return R(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 R(this,null,function*(){var r,a,n,o,u;(0,I.assertNonNullable)(this.element),(0,I.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=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),qe(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,I.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,I.isNonNullable)(this.element)&&(0,I.isNonNullable)(this.source)&&(0,I.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.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,I.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))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(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};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i=j(C({},i),{gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,I.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 ro=class{constructor(e,t){this.fov=e,this.orientation=t}};var so=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/kt(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,a=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:a,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=C({},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*kt(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 ay=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var US=s=>{if(!(s!=null&&s.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(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={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 a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},At=(s,e)=>{let t=s;t=(0,Jl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,HS.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Jl.default)(t,n,(o,u)=>(0,sa.isNullable)(a)?o:(0,sa.isNullable)(u)?a:(0,jS.default)(a,parseInt(u,10),"0"))}return t},Fn=(s,e)=>{var U,M,Q,H,Z,le,he,F,$,P,V,q,we,tt,Se,de,Ve,_e,Oe,it,qt,ti,yi,Ki,Fr,Rc,kc,Lc,$c,Mc,Dc,Cc,Bc,Vc,_c,Oc,Fc,Nc,qc,Uc,Hc,jc,Qc,Wc,Gc,zc,Yc,Kc,Xc,Jc,Zc,ed,td,id,rd,sd,ad,nd,od,ud,ld;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(gt=>{var ve,Ti;return(Ti=(ve=gt.textContent)==null?void 0:ve.trim())!=null?Ti:""}),o=(U=(0,QS.default)(n,0))!=null?U:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=a.getAttribute("publishTime"),d=a.getElementsByTagName("vk:Attrs")[0],f=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let g,y=a.getAttribute("mediaPresentationDuration"),A=[...a.getElementsByTagName("Period")],E=A.reduce((gt,ve)=>j(C({},gt),{[ve.id]:ve.children}),{}),w=A.reduce((gt,ve)=>j(C({},gt),{[ve.id]:ve.getAttribute("duration")}),{});y?g=US(y):(0,Zl.default)(w).filter(gt=>gt).length&&!u?g=(0,Zl.default)(w).reduce((gt,ve)=>{var Ti;return gt+((Ti=US(ve))!=null?Ti:0)},0):b&&(g=parseInt(b,10));let _=0,W=(Q=(M=a.getAttribute("profiles"))==null?void 0:M.split(","))!=null?Q:[];for(let gt of A.map(ve=>ve.id))for(let ve of E[gt]){let Ti=(H=ve.getAttribute("id"))!=null?H:"id"+(_++).toString(10),Nr=(Z=ve.getAttribute("mimeType"))!=null?Z:"",xo=(le=ve.getAttribute("codecs"))!=null?le:"",wo=(he=ve.getAttribute("contentType"))!=null?he:Nr==null?void 0:Nr.split("/")[0],qy=($=(F=ve.getAttribute("profiles"))==null?void 0:F.split(","))!=null?$:[],cd=(V=qS((P=ve.getAttribute("lang"))!=null?P:""))!=null?V:{},Ia=(tt=(we=(q=ve.querySelector("Label"))==null?void 0:q.textContent)==null?void 0:we.trim())!=null?tt:void 0,Uy=ve.querySelectorAll("Representation"),Hy=ve.querySelector("SegmentTemplate"),jy=(de=(Se=ve.querySelector("Role"))==null?void 0:Se.getAttribute("value"))!=null?de:void 0,Xi=wo,ke={id:Ti,language:cd.language,isDefault:jy==="main",label:Ia,codecs:xo,hdr:Xi==="video"&&Xl(xo),mime:Nr,representations:[]};for(let me of Uy){let ii=(Ve=me.getAttribute("lang"))!=null?Ve:void 0,qr=(Oe=(_e=Ia!=null?Ia:ve.getAttribute("label"))!=null?_e:me.getAttribute("label"))!=null?Oe:void 0,Ea=(ti=(qt=(it=me.querySelector("BaseURL"))==null?void 0:it.textContent)==null?void 0:qt.trim())!=null?ti:"",Ii=new URL(Ea||o,e).toString(),ri=(yi=me.getAttribute("mimeType"))!=null?yi:Nr,xa=(Fr=(Ki=me.getAttribute("codecs"))!=null?Ki:xo)!=null?Fr:"",wa;if(wo==="text"){let si=me.getAttribute("id")||"",Aa=((Rc=cd.privateuse)==null?void 0:Rc.includes("x-auto"))||si.includes("_auto"),Ei=me.querySelector("SegmentTemplate");if(Ei){let Ur={representationId:(kc=me.getAttribute("id"))!=null?kc:void 0,bandwidth:(Lc=me.getAttribute("bandwidth"))!=null?Lc:void 0},Pa=parseInt(($c=me.getAttribute("bandwidth"))!=null?$c:"",10)/1e3,Ra=(Dc=parseInt((Mc=Ei.getAttribute("startNumber"))!=null?Mc:"",10))!=null?Dc:1,Ji=parseInt((Cc=Ei.getAttribute("timescale"))!=null?Cc:"",10),Ao=(Bc=Ei.querySelectorAll("SegmentTimeline S"))!=null?Bc:[],Zi=Ei.getAttribute("media");if(!Zi)continue;let ka=[],La=0,$a="",er=0,Hr=Ra,Ue=0;for(let vt of Ao){let xi=parseInt((Vc=vt.getAttribute("d"))!=null?Vc:"",10),dt=parseInt((_c=vt.getAttribute("r"))!=null?_c:"",10)||0,ai=parseInt((Oc=vt.getAttribute("t"))!=null?Oc:"",10);Ue=Number.isFinite(ai)?ai:Ue;let wi=xi/Ji*1e3,ni=Ue/Ji*1e3;for(let Pt=0;Pt<dt+1;Pt++){let oi=At(Zi,j(C({},Ur),{segmentNumber:Hr.toString(10),segmentTime:(Ue+Pt*xi).toString(10)})),tr=(ni!=null?ni:0)+Pt*wi,Qr=tr+wi;Hr++,ka.push({time:{from:tr,to:Qr},url:oi})}Ue+=(dt+1)*xi,La+=(dt+1)*wi}er=Ue/Ji*1e3,$a=At(Zi,j(C({},Ur),{segmentNumber:Hr.toString(10),segmentTime:Ue.toString(10)}));let jr={time:{from:er,to:1/0},url:$a},Ut={type:"template",baseUrl:Ii,segmentTemplateUrl:Zi,initUrl:"",totalSegmentsDurationMs:La,segments:ka,nextSegmentBeyondManifest:jr,timescale:Ji};wa={id:si,kind:"text",segmentReference:Ut,profiles:[],duration:g,bitrate:Pa,mime:"",codecs:"",width:0,height:0,isAuto:Aa}}else wa={id:si,isAuto:Aa,kind:"text",url:Ii}}else{let si=(Nc=(Fc=me.getAttribute("contentType"))!=null?Fc:ri==null?void 0:ri.split("/")[0])!=null?Nc:wo,Aa=(Uc=(qc=ve.getAttribute("profiles"))==null?void 0:qc.split(","))!=null?Uc:[],Ei=parseInt((Hc=me.getAttribute("width"))!=null?Hc:"",10),Ur=parseInt((jc=me.getAttribute("height"))!=null?jc:"",10),Pa=parseInt((Qc=me.getAttribute("bandwidth"))!=null?Qc:"",10)/1e3,Ra=(Wc=me.getAttribute("frameRate"))!=null?Wc:"",Ji=(Gc=me.getAttribute("quality"))!=null?Gc:void 0,Ao=Ra?NS(Ra):void 0,Zi=(zc=me.getAttribute("id"))!=null?zc:"id"+(_++).toString(10),ka=si==="video"?`${Ur}p`:si==="audio"?`${Pa}Kbps`:xa,La=`${Zi}@${ka}`,$a=[...W,...qy,...Aa],er,Hr=me.querySelector("SegmentBase"),Ue=(Yc=me.querySelector("SegmentTemplate"))!=null?Yc:Hy;if(Hr){let Ut=(Xc=(Kc=me.querySelector("SegmentBase Initialization"))==null?void 0:Kc.getAttribute("range"))!=null?Xc:"",[vt,xi]=Ut.split("-").map(oi=>parseInt(oi,10)),dt={from:vt,to:xi},ai=(Jc=me.querySelector("SegmentBase"))==null?void 0:Jc.getAttribute("indexRange"),[wi,ni]=ai?ai.split("-").map(oi=>parseInt(oi,10)):[],Pt=ai?{from:wi,to:ni}:void 0;er={type:"byteRange",url:Ii,initRange:dt,indexRange:Pt}}else if(Ue){let Ut={representationId:(Zc=me.getAttribute("id"))!=null?Zc:void 0,bandwidth:(ed=me.getAttribute("bandwidth"))!=null?ed:void 0},vt=parseInt((td=Ue.getAttribute("timescale"))!=null?td:"",10),xi=(id=Ue.getAttribute("initialization"))!=null?id:"",dt=Ue.getAttribute("media"),ai=(sd=parseInt((rd=Ue.getAttribute("startNumber"))!=null?rd:"",10))!=null?sd:1,wi=At(xi,Ut);if(!dt)throw new ReferenceError("No media attribute in SegmentTemplate");let ni=(ad=Ue.querySelectorAll("SegmentTimeline S"))!=null?ad:[],Pt=[],oi=0,tr="",Qr=0;if(ni.length){let Ma=ai,St=0;for(let ir of ni){let Rt=parseInt((nd=ir.getAttribute("d"))!=null?nd:"",10),Ai=parseInt((od=ir.getAttribute("r"))!=null?od:"",10)||0,Da=parseInt((ud=ir.getAttribute("t"))!=null?ud:"",10);St=Number.isFinite(Da)?Da:St;let Po=Rt/vt*1e3,Ro=St/vt*1e3;for(let Ca=0;Ca<Ai+1;Ca++){let Wy=At(dt,j(C({},Ut),{segmentNumber:Ma.toString(10),segmentTime:(St+Ca*Rt).toString(10)})),dd=(Ro!=null?Ro:0)+Ca*Po,Gy=dd+Po;Ma++,Pt.push({time:{from:dd,to:Gy},url:Wy})}St+=(Ai+1)*Rt,oi+=(Ai+1)*Po}Qr=St/vt*1e3,tr=At(dt,j(C({},Ut),{segmentNumber:Ma.toString(10),segmentTime:St.toString(10)}))}else if((0,sa.isNonNullable)(g)){let St=parseInt((ld=Ue.getAttribute("duration"))!=null?ld:"",10)/vt*1e3,ir=Math.ceil(g/St),Rt=0;for(let Ai=1;Ai<ir;Ai++){let Da=At(dt,j(C({},Ut),{segmentNumber:Ai.toString(10),segmentTime:Rt.toString(10)}));Pt.push({time:{from:Rt,to:Rt+St},url:Da}),Rt+=St}Qr=Rt,tr=At(dt,j(C({},Ut),{segmentNumber:ir.toString(10),segmentTime:Rt.toString(10)}))}let Qy={time:{from:Qr,to:1/0},url:tr};er={type:"template",baseUrl:Ii,segmentTemplateUrl:dt,initUrl:wi,totalSegmentsDurationMs:oi,segments:Pt,nextSegmentBeyondManifest:Qy,timescale:vt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!si||!ri)continue;let jr={video:"video",audio:"audio",text:"text"}[si];if(!jr)continue;Xi||(Xi=jr),wa={id:La,kind:jr,segmentReference:er,profiles:$a,duration:g,bitrate:Pa,mime:ri,codecs:xa,width:Ei,height:Ur,fps:Ao,quality:Ji}}ke.language||(ke.language=ii),ke.label||(ke.label=qr),ke.mime||(ke.mime=ri),ke.codecs||(ke.codecs=xa),ke.hdr||(ke.hdr=Xi==="video"&&Xl(xa)),ke.representations.push(wa)}if(Xi){let me=r[Xi].find(ii=>ii.id===ke.id);if(me&&ke.representations.every(ii=>ii.segmentReference.type==="template"))for(let ii of me.representations){let qr=ke.representations.find(ri=>ri.id===ii.id),Ea=qr==null?void 0:qr.segmentReference,Ii=ii.segmentReference;Ii.segments.push(...Ea.segments),Ii.nextSegmentBeyondManifest=Ea.nextSegmentBeyondManifest}else r[Xi].push(ke)}}return{duration:g,streams:r,baseUrls:n,live:S}};var ec=Y(xt(),1);var WS=require("@vkontakte/videoplayer-shared/es2015"),GS=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?hi(a):void 0)!=null?u:(0,WS.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},zS=({id:s,bitrate:e})=>({id:s,bitrate:e}),YS=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),KS=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),tc=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,ec.default)(i.split("."),0),isDefault:r}),ic=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,ec.default)(r.split("."),0)}),rc=s=>"url"in s,ut=s=>s.type==="template";var sc=require("@vkontakte/videoplayer-shared/es2015"),te=(s,e)=>(0,sc.isNonNullable)(s)&&(0,sc.isNonNullable)(e)&&s.readyState==="open"&&b$(s,e);function b$(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var aa=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new k.ValueSubject(0);this.currentLowLatencySegmentLength$=new k.ValueSubject(0);this.currentSegmentLength$=new k.ValueSubject(0);this.onLastSegment$=new k.ValueSubject(!1);this.fullyBuffered$=new k.ValueSubject(!1);this.playingRepresentation$=new k.ValueSubject(void 0);this.playingRepresentationInit$=new k.ValueSubject(void 0);this.error$=new k.Subject;this.gaps=[];this.subscription=new k.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new fe;this.switchAbortController=new fe;this.destroyAbortController=new fe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,k.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){let t=this.representations.get(e);(0,k.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 jv(this.sourceBuffer),this.subscription.add((0,k.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,k.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:k.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,kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,k.assertNonNullable)(i,"No init buffer for starting representation"),(0,k.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(a))})}.bind(this));this.switchTo=(0,k.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(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,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,k.isNullable)(a)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,k.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,k.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(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,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,k.isNullable)(a)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,k.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,k.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){var u,l;let t=(u=(0,qn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!ut(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,k.assertNonNullable)(r);let a=this.segments.get(i);(0,k.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,k.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),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 fe,(0,k.abortable)(this.switchAbortController.signal,function(i,r=!1){return oe(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,k.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,k.isNullable)(o)||(0,k.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,k.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,k.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,k.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return R(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new fe,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,k.isNullable)(e)||(0,k.isNullable)(this.downloadingRepresentationId)||(0,k.isNullable)(this.playingRepresentationId)||(0,k.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||(0,k.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,k.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);(0,k.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(a=d)}if(isFinite(this.bufferLimit)&&kr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Nn.default)(u,r))c="high";else{let d=(0,ji.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ji.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),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 a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;(0,k.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,qn.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,qn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!ut(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>j(C({},p),{status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(a=(0,ji.default)(c,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,k.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,ji.default)(e,-1))==null?void 0:t.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!ut(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),c=At(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a: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&&_t&&_t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_t&&_t(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),a=e.findIndex(({status:f,time:{from:p,to:h}},b)=>{let S=p<=i&&h>=i,g=p>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&g&&A&&this.sourceBuffer&&te(this.mediaSource,this.sourceBuffer)&&!(qe(this.sourceBuffer.buffered,p)&&qe(this.sourceBuffer.buffered,h)))&&g&&A});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=a;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}loadSegments(e,t,i="auto"){return R(this,null,function*(){ut(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return R(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:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,k.abortable)(o,function(){return oe(this,null,function*(){let c=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,k.now)(),!c)return;let d=new DataView(c),f=Ot(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ft(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ut(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return R(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:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,k.abortable)(n,function(){return oe(this,null,function*(){let u=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,k.fromEvent)(window,"online").pipe((0,k.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,k.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ft(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ut(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ji.default)(e,0).byte.from,to:(0,ji.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>R(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,k.now)(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!ut(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:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,k.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Nn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){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:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ot(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!te(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let d=c.byte.from-i,f=c.byte.to-i,p=f-d+1,h=d<r,b=f<=r;if(!h)continue;let S=Ot(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(g,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-d),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),y=l.loadedBytes===p?g:S.parseFeedableSegmentChunk(g);y!=null&&y.byteLength&&(c.status="partially_fed",l.feedingBytes+=y.byteLength,(yield this.sourceBufferTaskQueue.append(y,a))&&!a.aborted?(l.fedBytes+=y.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!((0,k.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer))){!this.isLive&&K.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qe(this.sourceBuffer.buffered,e.segment.time.from,100)&&qe(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:k.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",rc(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.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,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Rr(()=>(0,XS.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return R(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,k.abortable)(this.destroyAbortController.signal,function(){return oe(this,null,function*(){let o=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ot(e.mime),r)).then(o=>R(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&ut(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:k.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(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 R(this,null,function*(){if(!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,k.isNullable)(e))return!1;let r=[],a=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:f}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,f):l.push(u[c])}return l},o=u=>{var c;if(a>=t)return r;r.push(C({},u.time)),r=n(r);let l=rc(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let f of this.segments.values())for(let p of f)(0,Nn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let f={time:{from:l,to:c},url:"",status:"none"};o(f)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return R(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,k.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:k.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,k.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||(0,k.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),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:k.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var gi=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Un=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};var X=require("@vkontakte/videoplayer-shared/es2015");var Hn=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Qn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new X.Subject;this.manifestReceived=new X.Subject;this.firstBytesRequested=new X.Subject;this.firstBytesReceived=new X.Subject;this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.recoverableError$=new X.Subject;this.error$=new X.Subject;this.abortAllController=new fe;this.subscription=new X.SubscriptionRemovable;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,function(e){return oe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=gi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Hn(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(jn);return r?(t.log("success",(0,X.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,X.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,X.abortable)(this.abortAllController.signal,function(c){return oe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var le,he,F;let d=e,f=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{f.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(d,location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),d=$.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(d=gi(d));let h=this.abortAllController.signal,b;if(n){let $=new fe;if(b=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(P){jn(P)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(P){jn(P)}h=$.signal}let S=0,g=(0,X.now)();p.log("startRequest",(0,X.flattenObject)({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let y=yield this.doFetch(d,{priority:a,headers:f,signal:h}),A=(0,X.now)();if(!y)return p.error("error",{message:"No response in request"}),p.end(),this.unsubscribeAbortSubscription(b),null;if((le=this.throughputEstimator)==null||le.addRawRtt(A-g),!y.ok||!y.body){this.unsubscribeAbortSubscription(b);let $=`Fetch error ${y.status}: ${y.statusText}`;return p.error("error",{message:$}),p.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){this.unsubscribeAbortSubscription(b);let $=(0,X.now)(),P={requestStartedAt:g,requestEndedAt:$,duration:$-g};return p.log("endRequest",(0,X.flattenObject)(P)),p.end(),y.arrayBuffer()}let E=y.body;if(o){let $;[E,$]=y.body.tee(),(he=this.throughputEstimator)==null||he.trackStream($,u)}let w=E.getReader(),_,W=parseInt((F=y.headers.get("content-length"))!=null?F:"",10);Number.isFinite(W)&&(_=W),!_&&i&&(_=i.to-i.from+1);let O=_?new Uint8Array(_):new Uint8Array(0),U=!1,M=$=>{this.unsubscribeAbortSubscription(b),U=!0,jn($)},Q=(0,X.abortable)(h,function(V){return oe(this,arguments,function*({done:$,value:P}){if(S===0&&(this.lastRequestFirstBytes$.next((0,X.now)()-g),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(b);return}if(!$&&P){if(l&&_)O.set(P,S),S+=P.byteLength;else{let q=new Uint8Array(O.length+P.length);q.set(O),q.set(P,O.length),O=q,S+=P.byteLength}r==null||r(new DataView(O.buffer),S),yield w==null?void 0:w.read().then(Q,M)}})}.bind(this));yield w==null?void 0:w.read().then(Q,M),this.unsubscribeAbortSubscription(b);let H=(0,X.now)(),Z={failed:U,requestStartedAt:g,requestEndedAt:H,duration:H-g};return U?(p.error("endRequest",(0,X.flattenObject)(Z)),p.end(),null):(p.log("endRequest",(0,X.flattenObject)(Z)),p.end(),O.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,function(e,t,i){return oe(this,null,function*(){var g;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(c,a))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(g=e.indexRange)!=null?g:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,p,h);return{init:p,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,X.abortable)(this.abortAllController.signal,function(e,t){return oe(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});return r?{init:null,segments:e.segments.map(n=>j(C({},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=a}onHeadersReceived(e){let{type:t,reused:i}=Un(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return R(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,X.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return R(this,null,function*(){let i=yield mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:X.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:X.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:X.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:X.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:X.ErrorCategory.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},jn=s=>{if(!Ft(s))throw s};var Kt=(s,e,t)=>t*e+(1-t)*s,ac=(s,e)=>s.reduce((t,i)=>t+i,0)/e,JS=(s,e,t,i)=>{let r=0,a=t,n=ac(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};var na=require("@vkontakte/videoplayer-shared/es2015");var vi=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 na.ValueSubject(e.initial),this.debounced$=new na.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Qe(`raw_${t}`),this.smoothedSeries$=new Qe(`smoothed_${t}`),this.reportedSeries$=new Qe(`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+=kt(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=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>a||this.smoothed<n)&&((0,na.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 Wn=class extends vi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Kt(this.slow,e,this.params.emaAlphaSlow),this.fast=Kt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Gn=class extends vi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ac(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Kt(this.emaSmoothed,e,this.params.emaAlpha);let i=JS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var zn=class extends vi{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?Kt(this.smoothed,t,this.params.emaAlpha):t}};var Xt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Wn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Gn({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 zn(C({initial:e,label:"liveEdgeDelay"},t))}};var Cr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var Yn=require("@vkontakte/videoplayer-shared/es2015");var oa=class s{constructor(e,t){this.currentRepresentation$=new Yn.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,Yn.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(j(C({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.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=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ut(t.segmentReference))}};var Xn=Y(xt(),1),nc=Y(je(),1),ua=require("@vkontakte/videoplayer-shared/es2015");var Kn=s=>{let{webmDecodingInfo:e}=K.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){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,ua.assertNever)(s)}return[t,i]},ZS=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Kn(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(K.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[...a,"MPEG",...Kn(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Kn(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Kn(s),...a,"HLS","HLS_ONDEMAND"];default:(0,ua.assertNever)(e)}if(K.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,ua.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},ey=({androidPreferredFormat:s,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"],a=[...i,...r],n=[...r,...i],o,u=K.device.isMac&&K.browser.isSafari;if(K.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:(0,ua.assertNever)(s)}else K.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},oc=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Jn=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Xn.default)(t.value.split("."),0)}for(let t of s){let i=(0,Xn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Xn.default)(e.value.split("."),0)},Zn=s=>{let e=s.map(i=>Br(i)),{codecs:t}=K.video;return y$().filter(i=>{if((0,nc.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})},eo=s=>{let e=s.map(i=>Br(i)),{codecs:t}=K.video;return T$().filter(i=>{if((0,nc.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Br=s=>s.split(".")[0].replace("0",""),y$=()=>["av1","vp9","hev1","avc1"],T$=()=>["opus","mp4a"];var x$=["timeupdate","progress","play","seeked","stalled","waiting"],w$=["timeupdate","progress","loadeddata","playing","seeked"];var to=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new I.Subscription;this.representationSubscription=new I.Subscription;this.state$=new ne("none");this.currentVideoRepresentation$=new I.ValueSubject(void 0);this.currentVideoRepresentationInit$=new I.ValueSubject(void 0);this.currentAudioRepresentation$=new I.ValueSubject(void 0);this.currentVideoSegmentLength$=new I.ValueSubject(0);this.currentAudioSegmentLength$=new I.ValueSubject(0);this.error$=new I.Subject;this.manifestRequested=new I.Subject;this.manifestReceived=new I.Subject;this.firstBytesRequested=new I.Subject;this.firstBytesReceived=new I.Subject;this.lastConnectionType$=new I.ValueSubject(void 0);this.lastConnectionReused$=new I.ValueSubject(void 0);this.lastRequestFirstBytes$=new I.ValueSubject(void 0);this.currentLiveTextRepresentation$=new I.ValueSubject(null);this.isLive$=new I.ValueSubject(!1);this.isActiveLive$=new I.ValueSubject(!1);this.isLowLatency$=new I.ValueSubject(!1);this.liveDuration$=new I.ValueSubject(0);this.liveSeekableDuration$=new I.ValueSubject(0);this.liveAvailabilityStartTime$=new I.ValueSubject(0);this.liveStreamStatus$=new I.ValueSubject(void 0);this.bufferLength$=new I.ValueSubject(0);this.liveLatency$=new I.ValueSubject(void 0);this.liveLoadBufferLength$=new I.ValueSubject(0);this.livePositionFromPlayer$=new I.ValueSubject(0);this.currentStallDuration$=new I.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new I.ValueSubject(0);this.fetcherRecoverableError$=new I.Subject;this.fetcherError$=new I.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new I.Subject;this.gapWatchdogActive=!1;this.destroyController=new fe;this.initManifest=(0,I.abortable)(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Re(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:I.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,I.abortable)(this.destroyController.signal,function(){return oe(this,null,function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=Fn(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=_n(e))!=null?u:{id:"ManifestParsing",category:I.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,b,S;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((S=(b=nt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let b="active";p||(b=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(b)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:b})=>i(c,h,b));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:b})=>b);c==="audio"&&(n=eo(h),p=n[0]),c==="video"&&(a=Zn(h),this.forceVideoCodec&&(0,ry.default)(a,this.forceVideoCodec)?p=this.forceVideoCodec:p=a[0]),p&&(r[c]=f.filter(({codecs:b})=>Br(b)===p))}else{let h=new Set(f.map(({codecs:b})=>b));p=Jn(h),p&&(r[c]=f.filter(({codecs:b})=>b.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,b=r.video.some(g=>g.hdr),S=r.video.some(g=>!g.hdr);K.display.isHDR&&h&&b?r.video=r.video.filter(g=>g.hdr):S&&(r.video=r.video.filter(g=>!g.hdr))}}let o=j(C({},t),{streams:r});return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",(0,I.flattenObject)(o)),o})}.bind(this));this.initRepresentations=(0,I.abortable)(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var f;this.tracer.log("initRepresentationsStart",(0,I.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,I.assertNonNullable)(this.manifest),(0,I.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,I.fromEvent)(p,"error").pipe((0,I.filter)(h=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Tn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),Tr())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 aa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,I.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,b)=>[...h,...b.representations],[]);this.audioBufferManager=new aa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}oa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new oa(this.manifest.streams.text,n)),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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,I.merge)(...w$.map(p=>(0,I.fromEvent)(this.element,p))).pipe((0,I.map)(p=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),(0,I.filterChanged)(),(0,I.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,I.merge)((0,I.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,I.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,I.now)())),this.subscription.add((0,I.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,I.interval)(1e3).subscribe(h=>{let b=di(this.manifestUrlString,2);this.manifestUrlString=Re(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,I.fromEvent)(this.element,"play").subscribe(h=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add((0,I.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.map)(({isActiveLive:h,isLowLatency:b})=>h&&b),(0,I.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Cr(this.element,1)})),this.representationSubscription.add((0,I.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.filter)(({bufferLength:h,isActiveLive:b,isLowLatency:S})=>b&&S&&!!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 b=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,I.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,I.filter)(({isLive:h})=>h),(0,I.filterChanged)((h,b)=>b.bufferLength<h.bufferLength),(0,I.map)(({rtt:h,bufferLength:b,segmentServerLatency:S})=>{let g=di(this.manifestUrlString,2);return(h/2+b+S+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,I.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:b,isLowLatency:S})=>{if(!S||!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=h-g;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(E)>y&&(w=1+Math.sign(E)*A),Cr(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var S,g;let b=0;if(h){let y=((g=(S=this.element)==null?void 0:S.currentTime)!=null?g:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var w,_;return(_=(w=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?_:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add((0,I.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,I.throttle)(1e3)).subscribe(S=>R(this,[S],function*({liveLoadBufferLength:h,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,y=di(this.manifestUrlString,2),A=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(A,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,_=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,W=isFinite(h)?h:b,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),U=A<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(U);let M="none";if(O?M="active_low_latency":this.isLowLatency$.getValue()&&U?(this.bufferManagers.forEach(Q=>Q.proceedLowLatencyLive()),M="active_low_latency"):y!==0&&W<E?M="live_forward_buffering":W<E+_&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let Q=p-(E+w),H=this.normolizeLiveOffset(Math.trunc(y+Q/g)),Z=Math.abs(H-y),le=0;!h||Z<=this.tuning.dashCmafLive.offsetCalculationError?le=y:H>0&&Z>this.tuning.dashCmafLive.offsetCalculationError&&(le=H),this.manifestUrlString=Re(this.manifestUrlString,le,2)}(M==="live_with_target_offset"||M==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:I.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,I.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,I.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,I.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,I.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=(0,I.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,I.filterChanged)(),(0,I.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,I.filter)(p=>p));if(this.representationSubscription.add((0,I.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:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,I.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 b;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(b=this.source)==null||b.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,lc.default)((0,lc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let b=[];return h.duration&&b.push(h.duration),ut(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&b.push(h.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,I.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,a;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||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,I.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:I.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 Qn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Xt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,C({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,a,n;(0,I.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,I.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Re(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){(0,I.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,I.merge)(...x$.map(e=>(0,I.fromEvent)(this.element,e)),(0,I.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,I.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,I.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qe(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,b,S,g,y,A,E,w,_,W;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=(0,I.now)(),n=100,o=(b=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?g:0,l=(A=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?A:0,c=(w=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?w:0,d=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&c<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||f)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let O=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(O).catch(U=>{this.error$.next({id:"stallIntervalCallback",category:I.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:U})}),r.liveLastOffset=O}else{let O=this.element.currentTime*1e3;(_=this.videoBufferManager)==null||_.maintain(O),(W=this.audioBufferManager)==null||W.maintain(O),r.position=O}this.tracer.log("stallIntervalCallback",(0,I.flattenObject)(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,I.interval)(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:I.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return R(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 R(this,null,function*(){var r,a,n,o,u;(0,I.assertNonNullable)(this.element),(0,I.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=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),qe(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,I.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,I.isNonNullable)(this.element)&&(0,I.isNonNullable)(this.source)&&(0,I.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.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,I.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))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(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};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i=j(C({},i),{gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,I.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 io=class{constructor(e,t){this.fov=e,this.orientation=t}};var ro=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/kt(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,a=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:a,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=C({},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*kt(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 sy=`attribute vec2 a_vertex;
|
|
125
125
|
attribute vec2 a_texel;
|
|
126
126
|
|
|
127
127
|
varying vec2 v_texel;
|
|
@@ -132,7 +132,7 @@ void main(void) {
|
|
|
132
132
|
// save texel vector to pass to fragment shader
|
|
133
133
|
v_texel = a_texel;
|
|
134
134
|
}
|
|
135
|
-
`;var
|
|
135
|
+
`;var ay=`#ifdef GL_ES
|
|
136
136
|
precision highp float;
|
|
137
137
|
precision highp int;
|
|
138
138
|
#else
|
|
@@ -175,6 +175,6 @@ void main(void) {
|
|
|
175
175
|
// sample using new coordinates
|
|
176
176
|
gl_FragColor = texture2D(u_texture, tc);
|
|
177
177
|
}
|
|
178
|
-
`;var Vr=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 ro(this.params.fov,this.params.orientation),this.cameraRotationManager=new so(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"),a=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(a,-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(ay,this.gl.VERTEX_SHADER),i=this.createShader(ny,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,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,f=t+r;return[a,n,o,u,l,c,d,f]}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 Te=require("@vkontakte/videoplayer-shared/es2015");var ao="stalls_manager_metrics",pc="stalls_manager_abr_params",oy="stalls_manager_default_tuning_abr_params",hc=class{constructor(){this.isSeeked$=new Te.ValueSubject(!1);this.isBuffering$=new Te.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 Te.Subscription;this.severeStallOccurred$=new Te.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.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(pc):{};return C(C({},this.abrParams),e)}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Te.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,Te.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}=C({},this.getStoredData(oy)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}=C({},this.abrParams);this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(pc),this.setStoredData(oy,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(ao,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+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 a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(ao,[]),this.setStoredData(pc,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(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=Te.safeStorage.get(e))!=null?i:t)}setStoredData(e,t){Te.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){Te.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(ao,"[]"),r=t/e,a=i.length?Kt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(ao,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,Te.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,Te.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,Te.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if((0,Te.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=(0,Te.now)(),d=r&&this.currentStallsCount>=r,f=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Te.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,Te.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},a)),this.lastStallDuration=t}))}},no=hc;var Ze=require("@vkontakte/videoplayer-shared/es2015"),oo=class{constructor(){this.subscription=new Ze.Subscription;this.pipSize$=new Ze.ValueSubject(void 0);this.videoSize$=new Ze.ValueSubject(void 0);this.elementSize$=new Ze.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Ze.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,Ze.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,Ze.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Ze.map)(({videoSize:r,inPip:a,pipSize:n})=>a?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 Qi=class{constructor(e){this.subscription=new ie.Subscription;this.videoState=new ne("stopped");this.observableVideo=null;this.droppedFramesManager=new wr;this.stallsManager=new no;this.elementSizeManager=new oo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new fi;this.audioTrackSwitchHistory=new fi;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.hostname$.next(void 0),this.videoState.setState("stopped"),N(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"),N(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&N(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"&&N(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&N(this.params.desiredState.playbackState,"paused");return;default:return(0,ie.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Vr(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:((a=e.projectionData)==null?void 0:a.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 ht(e.source.url),this.params=e,this.video=ze(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(Ne(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 io({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,ie.isNullable)(this.observableVideo)&&(this.observableVideo=Xe(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:ie.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,ie.filter)(l=>!!l.length),(0,ie.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,ie.map)(l=>l.to.state!=="none"),(0,ie.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$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,ie.filter)(ie.isNonNullable),(0,ie.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,ie.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(Ct(this.video,t.isLooped,r)),this.subscription.add(Ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ft(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),N(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),N(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"),N(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 c=this.player.getStreams(),d=this.player.getCodecs();if((0,ie.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(rc(h));let b=[];for(let S of h.representations){let g=YS(S);b.push(g),this.audioTracksMap.set(g,{stream:h,representation:S})}this.audioStreamsMap.set(h,b)}this.params.output.availableAudioStreams$.next(p)}let f=[];for(let p of c.video){f.push(sc(p));let h=[];for(let b of p.representations){let S=zS(j(C({},b),{streamId:p.id}));S&&(h.push(S),this.videoTracksMap.set(S,{stream:p,representation:b}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(f);for(let p of c.text)for(let h of p.representations){let b=KS(p,h);this.textTracksMap.set(b,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),d!=null&&d.video&&this.params.output.availableVideoCodecs$.next(d.video),d!=null&&d.audio&&this.params.output.availableAudioCodecs$.next(d.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)),this.subscription.add((0,ie.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,ie.fromEvent)(this.video,"progress")).pipe((0,ie.filter)(()=>this.videoTracksMap.size>0)).subscribe(()=>R(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,uy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[f,p]=d,h=[...this.videoTracksMap.keys()].find(S=>{var g;return((g=this.videoTracksMap.get(S))==null?void 0:g.representation.id)===f.id});(0,ie.isNonNullable)(h)&&(this.stallsManager.lastVideoTrackSelected=h);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",f.id),p){let S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,S)}}),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.currentVideoRepresentation$.pipe((0,ie.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(sc(f));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,ie.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(rc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.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 o=t.playbackState.stateChangeStarted$.pipe((0,ie.map)(({to:l})=>l==="ready"),(0,ie.filterChanged)());this.subscription.add((0,ie.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,ie.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,ie.merge)(o,this.player.state$.stateChangeEnded$,(0,ie.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,ie.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ie.observableFrom)(["init"])).pipe((0,ie.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var M,Q,H,Z,le,he,F,$,P,B,q,we,tt;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Es:Is,t=this.params.tuning.useNewAutoSelectVideoTrack?Dn:Mn,i=this.params.tuning.useNewAutoSelectVideoTrack?Bt:$n,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(M=r.videoTrack.getState())==null?void 0:M.id,l=[...this.videoTracksMap.keys()].find(({id:Se})=>Se===o),c=a.currentVideoTrack$.getValue(),d=((Z=(H=r.videoStream.getState())!=null?H:l&&((Q=this.videoTracksMap.get(l))==null?void 0:Q.stream))!=null?Z:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let f=[...this.videoStreamsMap.keys()].find(({id:Se})=>Se===d.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=Be(this.video.buffered,this.video.currentTime*1e3),b;this.player.isActiveLive$.getValue()?b=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?b=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:b=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let S=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(h/Math.min(b,S||1/0),1),y=(le=r.audioStream.getState())!=null?le:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,A=(he=[...this.audioStreamsMap.keys()].find(({id:Se})=>Se===(y==null?void 0:y.id)))!=null?he:this.audioStreamsMap.keys().next().value,E=0;if(A){if(l&&!n){let Se=e(l,p,(F=this.audioStreamsMap.get(A))!=null?F:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,($=Se==null?void 0:Se.bitrate)!=null?$:-1/0)}if(c){let Se=e(c,p,(P=this.audioStreamsMap.get(A))!=null?P:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,(B=Se==null?void 0:Se.bitrate)!=null?B:-1/0)}}let w=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:E,forwardBufferHealth:g,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}),_=n?w!=null?w:l:l!=null?l:w,W=A&&t(_,p,(q=this.audioStreamsMap.get(A))!=null?q:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),O=(we=this.videoTracksMap.get(_))==null?void 0:we.representation,U=W&&((tt=this.audioTracksMap.get(W))==null?void 0:tt.representation);if(O&&U)return[O,U];if(O&&!U&&this.audioTracksMap.size===0)return[O,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),N(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ie.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),Ye(this.video),this.tracer.end()}};var la=class extends Qi{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 be=require("@vkontakte/videoplayer-shared/es2015");var ca=class extends Qi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,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 be.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,be.filterChanged)()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe((0,be.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,be.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,be.map)(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,be.filter)(u=>(0,be.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add((0,be.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,be.merge)(r.playbackRateState$,new be.ValueSubject(1))}).pipe((0,be.filter)(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||(0,be.isNullable)(c)||(t=u-c)})).add((0,be.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,be.merge)(r.playbackRateState$,new be.ValueSubject(1))}).pipe((0,be.filterChanged)((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||(0,be.isNullable)(u)||(0,be.isNullable)(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=XS(u);this.params.output.availableTextTracks$.next([l])}}))}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 re=require("@vkontakte/videoplayer-shared/es2015");var Sy=Y(je(),1),yc=Y(Ls(),1);var T=require("@vkontakte/videoplayer-shared/es2015");var ho=Y(je(),1),Gi=Y(xt(),1),fo=Y(Ls(),1);var gy=Y(gn(),1);var Si=require("@vkontakte/videoplayer-shared/es2015");var L$=18,ly=!1;try{ly=K.browser.isSafari&&!!K.browser.safariVersion&&K.browser.safariVersion<=L$}catch(s){console.error(s)}var fc=class{constructor(e){this.bufferFull$=new Si.Subject;this.error$=new Si.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Si.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(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 R(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};ly&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!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.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(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Si.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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,Si.assertNever)(t)}}},cy=fc;var L=require("@vkontakte/videoplayer-shared/es2015");var mc=Y(xt(),1);var uo=require("@vkontakte/videoplayer-shared/es2015"),dy=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?hi(a):void 0)!=null?u:(0,uo.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},py=({id:s,bitrate:e})=>({id:s,bitrate:e}),hy=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),fy=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),bc=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,mc.default)(i.split("."),0),isDefault:r}),gc=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,mc.default)(r.split("."),0)}),vc=s=>"url"in s,lt=s=>s.type==="template";var my=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},Wi=(s,e)=>{for(let t of s)if(e(t))return t;return null},by=s=>{let e=!1,t=(0,uo.throttleFn)(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var po=require("@vkontakte/videoplayer-shared/es2015");var lo=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var co=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new po.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,po.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!te(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=lo(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var da=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new L.ValueSubject(0);this.currentLowLatencySegmentLength$=new L.ValueSubject(0);this.currentSegmentLength$=new L.ValueSubject(0);this.onLastSegment$=new L.ValueSubject(!1);this.fullyBuffered$=new L.ValueSubject(!1);this.playingRepresentation$=new L.ValueSubject(void 0);this.playingRepresentationInit$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.gaps=[];this.subscription=new L.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new fe;this.switchAbortController=new fe;this.destroyAbortController=new fe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=(0,L.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){let t=this.representations.get(e);(0,L.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 cy(this.sourceBuffer),this.sourceBufferBufferedDiff=new co(this.mediaSource,this.sourceBuffer),this.subscription.add((0,L.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,L.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.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,kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Be(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,L.assertNonNullable)(i,"No init buffer for starting representation"),(0,L.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(a))})}.bind(this));this.switchTo=(0,L.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(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,L.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,L.isNullable)(a)||(0,L.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,L.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,L.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,L.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(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,L.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,L.isNullable)(a)||(0,L.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,L.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,L.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,L.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){var u,l;let t=(u=(0,fo.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!lt(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,L.assertNonNullable)(r);let a=this.segments.get(i);(0,L.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,L.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),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 fe,(0,L.abortable)(this.switchAbortController.signal,function(i,r=!1){return oe(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,L.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,L.isNullable)(o)||(0,L.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,L.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,L.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,L.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return R(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new fe,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,L.isNullable)(e)||(0,L.isNullable)(this.downloadingRepresentationId)||(0,L.isNullable)(this.playingRepresentationId)||(0,L.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||(0,L.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,L.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);(0,L.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Be(this.sourceBuffer.buffered,e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(a=d)}if(isFinite(this.bufferLimit)&&kr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=Be(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,ho.default)(u,r))c="high";else{let d=(0,Gi.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&Be(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Gi.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Be(this.sourceBuffer.buffered,e)<n),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 a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;(0,L.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=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,fo.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,fo.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!lt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>j(C({},p),{status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(a=(0,Gi.default)(c,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,L.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!lt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=At(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a: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,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&_t&&_t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_t&&_t(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:f,time:{from:p,to:h}},b)=>{let S=p<=i&&h>=i,g=p>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&g&&A&&this.sourceBuffer&&te(this.mediaSource,this.sourceBuffer)&&!(qe(this.sourceBuffer.buffered,p)&&qe(this.sourceBuffer.buffered,h)))&&g&&A});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=a;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}loadSegments(e,t,i="auto"){return R(this,null,function*(){lt(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return R(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:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,L.abortable)(o,function(){return oe(this,null,function*(){let c=(0,L.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,L.now)(),!c)return;let d=new DataView(c),f=Ot(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ft(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())lt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return R(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:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,L.abortable)(n,function(){return oe(this,null,function*(){let u=(0,L.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,L.fromEvent)(window,"online").pipe((0,L.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,L.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ft(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(lt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Gi.default)(e,0).byte.from,to:(0,Gi.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>R(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,L.now)(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:L.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!lt(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:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,L.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:L.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,ho.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){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:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ot(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!te(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let{segment:c}=l,d=c.byte.from-i,f=c.byte.to-i,p=f-d+1,h=d<r,b=f<=r;if(h){if(c.status==="downloading"&&b){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),g=l.loadedBytes===p?S:Ot(u.mime).parseFeedableSegmentChunk(S);g!=null&&g.byteLength&&(c.status="partially_fed",l.feedingBytes+=g.byteLength,(yield this.sourceBufferTaskQueue.append(g,a))&&!a.aborted?(l.fedBytes+=g.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}}})}onSegmentFullyAppended(e,t){if(!((0,L.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer))){!this.isLive&&K.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qe(this.sourceBuffer.buffered,e.segment.time.from,100)&&qe(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:L.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",vc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&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,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Rr(()=>(0,gy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return R(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,L.abortable)(this.destroyAbortController.signal,function(){return oe(this,null,function*(){let o=(0,L.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ot(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&<(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(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 R(this,null,function*(){if(!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,L.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push(C({},o.time));let u=vc(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let f of d)(0,ho.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let d={time:{from:u,to:l},url:"",status:"none"};n(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=my(r),(yield Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1})}abortBuffer(){return R(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)}}getBufferedTo(){return!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null: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,L.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.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}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,L.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||(0,L.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=lo(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let c=0;c<e.length;c+=2){let d=e[c],f=e[c+1];u||(u=d-t<=n&&f+t>=o),(n>=d&&n<f-t||o>d+t&&o<=f)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:L.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,Gi.default)(e,-1))==null?void 0:t.time.to:0)||0}};var J=require("@vkontakte/videoplayer-shared/es2015");var bo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!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.recoverableError$=new J.Subject;this.error$=new J.Subject;this.abortAllController=new fe;this.subscription=new J.SubscriptionRemovable;this.fetchManifest=(0,J.abortable)(this.abortAllController.signal,function(e){return oe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=gi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=jn(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(mo);return r?(t.log("success",(0,J.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(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(c){return oe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var le,he,F;let d=e,f=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{f.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(d,location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),d=$.toString();break}default:(0,J.assertNever)(t)}this.requestQuic&&(d=gi(d));let h=this.abortAllController.signal,b;if(n){let $=new fe;if(b=(0,J.merge)((0,J.fromEvent)(this.abortAllController.signal,"abort"),(0,J.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(P){mo(P)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(P){mo(P)}h=$.signal}let S=0,g=(0,J.now)();p.log("startRequest",(0,J.flattenObject)({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let y=yield this.doFetch(d,{priority:a,headers:f,signal:h}),A=(0,J.now)();if(!y)return p.error("error",{message:"No response in request"}),p.end(),this.unsubscribeAbortSubscription(b),null;if((le=this.throughputEstimator)==null||le.addRawRtt(A-g),!y.ok||!y.body){this.unsubscribeAbortSubscription(b);let $=`Fetch error ${y.status}: ${y.statusText}`;return p.error("error",{message:$}),p.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){this.unsubscribeAbortSubscription(b);let $=(0,J.now)(),P={requestStartedAt:g,requestEndedAt:$,duration:$-g};return p.log("endRequest",(0,J.flattenObject)(P)),p.end(),y.arrayBuffer()}let E=y.body;if(o){let $;[E,$]=y.body.tee(),(he=this.throughputEstimator)==null||he.trackStream($,u)}let w=E.getReader(),_,W=parseInt((F=y.headers.get("content-length"))!=null?F:"",10);Number.isFinite(W)&&(_=W),!_&&i&&(_=i.to-i.from+1);let O=_?new Uint8Array(_):new Uint8Array(0),U=!1,M=$=>{this.unsubscribeAbortSubscription(b),U=!0,mo($)},Q=(0,J.abortable)(h,function(B){return oe(this,arguments,function*({done:$,value:P}){if(S===0&&(this.lastRequestFirstBytes$.next((0,J.now)()-g),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(b);return}if(!$&&P){if(l&&_)O.set(P,S),S+=P.byteLength;else{let q=new Uint8Array(O.length+P.length);q.set(O),q.set(P,O.length),O=q,S+=P.byteLength}r==null||r(new DataView(O.buffer),S),yield w==null?void 0:w.read().then(Q,M)}})}.bind(this));yield w==null?void 0:w.read().then(Q,M),this.unsubscribeAbortSubscription(b);let H=(0,J.now)(),Z={failed:U,requestStartedAt:g,requestEndedAt:H,duration:H-g};return U?(p.error("endRequest",(0,J.flattenObject)(Z)),p.end(),null):(p.log("endRequest",(0,J.flattenObject)(Z)),p.end(),O.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t,i){return oe(this,null,function*(){var g;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(c,a))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(g=e.indexRange)!=null?g:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,p,h);return{init:p,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t){return oe(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});return r?{init:null,segments:e.segments.map(n=>j(C({},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=a}onHeadersReceived(e){let{type:t,reused:i}=Hn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return R(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,J.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}doFetch(e,t){return R(this,null,function*(){let i=yield mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:J.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:J.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:J.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:J.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:J.ErrorCategory.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},mo=s=>{if(!Ft(s))throw s};var go=require("@vkontakte/videoplayer-shared/es2015");var pa=class s{constructor(e,t){this.currentRepresentation$=new go.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,go.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(j(C({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.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=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&<(t.segmentReference))}};var D$=["progress","play","seeked","stalled","waiting"],C$=["timeupdate","progress","loadeddata","playing","seeked"];var vo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;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.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.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.destroyController=new fe;this.initManifest=(0,T.abortable)(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Re(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 oe(this,null,function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=Nn(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=On(e))!=null?u:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,b,S;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((S=(b=nt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let b="active";p||(b=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(b)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:b})=>i(c,h,b));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:b})=>b);c==="audio"&&(n=to(h),p=n[0]),c==="video"&&(a=eo(h),this.forceVideoCodec&&(0,Sy.default)(a,this.forceVideoCodec)?p=this.forceVideoCodec:p=a[0]),p&&(r[c]=f.filter(({codecs:b})=>Br(b)===p))}else{let h=new Set(f.map(({codecs:b})=>b));p=Zn(h),p&&(r[c]=f.filter(({codecs:b})=>b.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,b=r.video.some(g=>g.hdr),S=r.video.some(g=>!g.hdr);K.display.isHDR&&h&&b?r.video=r.video.filter(g=>g.hdr):S&&(r.video=r.video.filter(g=>!g.hdr))}}let o=j(C({},t),{streams:r});return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,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 oe(this,null,function*(){var f;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.representationSubscription=new T.Subscription,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,T.fromEvent)(p,"error").pipe((0,T.filter)(h=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Tn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),Tr())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 da("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,b)=>[...h,...b.representations],[]);this.audioBufferManager=new da("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}pa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new pa(this.manifest.streams.text,n)),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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,T.merge)(...C$.map(p=>(0,T.fromEvent)(this.element,p))).pipe((0,T.map)(p=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),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(()=>{this.livePauseWatchdogSubscription=(0,T.interval)(1e3).subscribe(h=>{let b=di(this.manifestUrlString,2);this.manifestUrlString=Re(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(h=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:h,isLowLatency:b})=>h&&b),(0,T.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Cr(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:b,isLowLatency:S})=>b&&S&&!!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 b=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(b,-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,b)=>b.bufferLength<h.bufferLength),(0,T.map)(({rtt:h,bufferLength:b,segmentServerLatency:S})=>{let g=di(this.manifestUrlString,2);return(h/2+b+S+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:b,isLowLatency:S})=>{if(!S||!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=h-g;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(E)>y&&(w=1+Math.sign(E)*A),Cr(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var S,g;let b=0;if(h){let y=((g=(S=this.element)==null?void 0:S.currentTime)!=null?g:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var w,_;return(_=(w=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?_:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(1e3)).subscribe(S=>R(this,[S],function*({liveLoadBufferLength:h,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,y=di(this.manifestUrlString,2),A=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(A,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,_=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,W=isFinite(h)?h:b,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),U=A<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(U);let M="none";if(O?M="active_low_latency":this.isLowLatency$.getValue()&&U?(this.bufferManagers.forEach(Q=>Q.proceedLowLatencyLive()),M="active_low_latency"):y!==0&&W<E?M="live_forward_buffering":W<E+_&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let Q=p-(E+w),H=this.normolizeLiveOffset(Math.trunc(y+Q/g)),Z=Math.abs(H-y),le=0;!h||Z<=this.tuning.dashCmafLive.offsetCalculationError?le=y:H>0&&Z>this.tuning.dashCmafLive.offsetCalculationError&&(le=H),this.manifestUrlString=Re(this.manifestUrlString,le,2)}(M==="live_with_target_offset"||M==="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 l=(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:l,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 b;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.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)),(b=this.source)==null||b.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,yc.default)((0,yc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let b=[];return h.duration&&b.push(h.duration),lt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&b.push(h.segmentReference.totalSegmentsDurationMs),b})];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,a;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||(a=this.audioBufferManager)!=null&&a.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.liveBuffer=Xt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,C({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,a,n;(0,T.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Re(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,T.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,T.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,T.merge)(...D$.map(t=>(0,T.fromEvent)(this.element,t)),(0,T.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&qe(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,b,S,g,y,A,E,w,_,W,O;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=(0,T.now)(),o=100,u=(S=(b=this.videoBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?S:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(y=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?y:0,c=(E=(A=this.videoBufferManager)==null?void 0:A.getForwardBufferDuration())!=null?E:0,d=(_=(w=this.audioBufferManager)==null?void 0:w.getForwardBufferDuration())!=null?_:0,f=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let U=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(U).catch(M=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:M})}),a.liveLastOffset=U}else{let U=this.element.currentTime*1e3;(W=this.videoBufferManager)==null||W.maintain(U),(O=this.audioBufferManager)==null||O.maintain(U),a.position=U}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=(0,T.interval)(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return R(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 R(this,null,function*(){var r,a,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=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),qe(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.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(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(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.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",(0,T.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}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 et=require("@vkontakte/videoplayer-shared/es2015"),So=class{constructor(){this.subscription=new et.Subscription;this.pipSize$=new et.ValueSubject(void 0);this.videoSize$=new et.ValueSubject(void 0);this.elementSize$=new et.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=et.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,et.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,et.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,et.map)(({videoSize:r,inPip:a,pipSize:n})=>a?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 zi=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new ne("stopped");this.observableVideo=null;this.droppedFramesManager=new wr;this.stallsManager=new no;this.elementSizeManager=new So;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new fi;this.audioTrackSwitchHistory=new fi;this.selectedRepresentations={audio:null,video:null};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.hostname$.next(void 0),this.videoState.setState("stopped"),N(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"),N(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&N(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"&&N(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&N(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Vr(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:((a=e.projectionData)==null?void 0:a.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 ht(e.source.url),this.params=e,this.video=ze(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(Ne(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 vo({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,re.isNullable)(this.observableVideo)&&(this.observableVideo=Xe(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:re.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,re.filter)(d=>!!d.length),(0,re.once)()).subscribe(d=>{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:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,re.map)(d=>d.to.state!=="none"),(0,re.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$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,re.filter)(re.isNonNullable),(0,re.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,re.map)(d=>d.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(Ct(this.video,t.isLooped,r)),this.subscription.add(Ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ft(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),N(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),N(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"),N(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:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams(),p=this.player.getCodecs();if((0,re.assertNonNullable)(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of f.audio){b.push(bc(S));let g=[];for(let y of S.representations){let A=py(y);g.push(A),this.audioTracksMap.set(A,{stream:S,representation:y})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(b)}let h=[];for(let b of f.video){h.push(gc(b));let S=[];for(let g of b.representations){let y=dy(j(C({},g),{streamId:b.id}));y&&(S.push(y),this.videoTracksMap.set(y,{stream:b,representation:g}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(h);for(let b of f.text)for(let S of b.representations){let g=hy(b,S);this.textTracksMap.set(g,{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),p!=null&&p.video&&this.params.output.availableVideoCodecs$.next(p.video),p!=null&&p.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&by(o)||null;this.subscription.add((0,re.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,re.fromEvent)(this.video,"progress")).pipe((0,re.filter)(()=>this.videoTracksMap.size>0)).subscribe(()=>R(this,null,function*(){let d=this.player.state$.getState(),f=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||f||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let b=Wi(this.videoTracksMap.keys(),g=>{var y;return((y=this.videoTracksMap.get(g))==null?void 0:y.representation.id)===p.id});(0,re.isNonNullable)(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),d==="manifest_ready")yield this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,g)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,re.filterChanged)()).subscribe(d=>{let f=Wi(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===h.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(gc(h));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,re.filterChanged)()).subscribe(d=>{let f=Wi(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===d);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===h.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(bc(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var f,p;if(d!=null&&d.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},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 l=t.playbackState.stateChangeStarted$.pipe((0,re.map)(({to:d})=>d==="ready"),(0,re.filterChanged)());this.subscription.add((0,re.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,re.observableFrom)(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,re.merge)(l,this.player.state$.stateChangeEnded$,(0,re.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=(0,re.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var O,U,M,Q,H,Z,le,he,F,$,P,B;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Es:Is,t=this.params.tuning.useNewAutoSelectVideoTrack?Dn:Mn,i=this.params.tuning.useNewAutoSelectVideoTrack?Bt:$n,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(O=r.videoTrack.getState())==null?void 0:O.id,u=Wi(this.videoTracksMap.keys(),q=>q.id===o),l=a.currentVideoTrack$.getValue(),c=((Q=(M=r.videoStream.getState())!=null?M:u&&((U=this.videoTracksMap.get(u))==null?void 0:U.stream))!=null?Q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Wi(this.videoStreamsMap.keys(),q=>q.id===c.id),f=d&&this.videoStreamsMap.get(d);if(!f)return;let p=Be(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=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(p/Math.min(h,b||1/0),1),g=(H=r.audioStream.getState())!=null?H:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(g==null?void 0:g.id)&&Wi(this.audioStreamsMap.keys(),q=>q.id===g.id)||this.audioStreamsMap.keys().next().value,A=0;if(y){if(u&&!n){let q=e(u,f,(Z=this.audioStreamsMap.get(y))!=null?Z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,(le=q==null?void 0:q.bitrate)!=null?le:-1/0)}if(l){let q=e(l,f,(he=this.audioStreamsMap.get(y))!=null?he:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,(F=q==null?void 0:q.bitrate)!=null?F:-1/0)}}let E=u;(n||!E)&&(E=i(f,{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:A,forwardBufferHealth:S,current:l,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 w=y&&t(E,f,($=this.audioStreamsMap.get(y))!=null?$:[],{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}),_=(P=this.videoTracksMap.get(E))==null?void 0:P.representation,W=w&&((B=this.audioTracksMap.get(w))==null?void 0:B.representation);_&&W?(this.selectedRepresentations.video=_,this.selectedRepresentations.audio=W):_&&!W&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=_,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),N(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.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),Ye(this.video),this.tracer.end()}};var ha=class extends zi{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 ge=require("@vkontakte/videoplayer-shared/es2015");var fa=class extends zi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,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 ge.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,ge.filterChanged)()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe((0,ge.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,ge.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ge.map)(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,ge.filter)(u=>(0,ge.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add((0,ge.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ge.merge)(r.playbackRateState$,new ge.ValueSubject(1))}).pipe((0,ge.filter)(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||(0,ge.isNullable)(c)||(t=u-c)})).add((0,ge.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ge.merge)(r.playbackRateState$,new ge.ValueSubject(1))}).pipe((0,ge.filterChanged)((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||(0,ge.isNullable)(u)||(0,ge.isNullable)(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=fy(u);this.params.output.availableTextTracks$.next([l])}}))}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",Tc=s=>R(null,null,function*(){var r;let e=yield mt(s),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 Ec=Y(Bu(),1);var yo=require("@vkontakte/videoplayer-shared/es2015");var V$=s=>{let e=null;if(s.QUALITY&&(e=hi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,yo.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},_$=(s,e)=>{var a,n;let t=s.split(`
|
|
179
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,
|
|
180
|
-
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+c},url:l}),a=a+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-d}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 l=new Date(u);l.setMilliseconds(0),a=l.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,ct.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([j(C({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return R(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new fe;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return R(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:ct.ErrorCategory.WTF,thrown:t,message:e})}};var ma=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 Fi;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(),a=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.hostname$.next(void 0),this.videoState.setState("stopped"),N(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?N(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),N(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"&&N(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 c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(N(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=ze(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,a)=>To(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Io(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ht(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{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(a,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(Ne(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,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.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=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),a(ft(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(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"),N(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),N(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(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ue.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},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:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).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),Ye(this.video)}prepare(){var o,u,l;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:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[c,"mq"],[d,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Re(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Tc(n).then(c=>{var d;if(!(0,ue.isNullable)(c))this.maxSeekBackTime$.next(c);else{let f=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,ue.isNullable)(f)||!isFinite(f))&&mt(n).then(p=>p.text()).then(p=>{var b;let h=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(h){let S=new URL(h,n).toString();Tc(S).then(g=>{(0,ue.isNullable)(g)||this.maxSeekBackTime$.next(g)})}}).catch(()=>{})}})}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),N(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=Re(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 pe=require("@vkontakte/videoplayer-shared/es2015");var ba=class{constructor(e){this.subscription=new pe.Subscription;this.videoState=new ne("stopped");this.manifests$=new pe.ValueSubject([]);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(),a=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.hostname$.next(void 0),this.videoState.setState("stopped"),N(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?N(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),N(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"&&N(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&N(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,pe.assertNever)(t)}};this.textTracksManager=new ht(e.source.url),this.params=e,this.video=ze(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:pe.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(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),To(Re(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.manifestReceived$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:pe.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:pe.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,pe.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(Ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),N(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),N(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 p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,pe.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(S=>S.id===h);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(Ne(b.url)))}let d=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==f){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),N(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe((0,pe.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!K.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,pe.merge)((0,pe.fromEvent)(o,"addtrack"),(0,pe.fromEvent)(o,"removetrack"),(0,pe.fromEvent)(o,"change"),(0,pe.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,pe.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,pe.observableFrom)(["init"])).pipe((0,pe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ye(this.video)}prepare(){var a,n;let e=this.selectManifest();if((0,pe.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=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),N(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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Iy=Y(cr(),1),xc=Y(Di(),1),Ey=Y(xt(),1);var Ie=require("@vkontakte/videoplayer-shared/es2015");var ga=class{constructor(e){this.subscription=new Ie.Subscription;this.videoState=new ne("stopped");this.trackUrls={};this.textTracksManager=new ht;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.hostname$.next(void 0),this.videoState.setState("stopped"),N(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.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"?N(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),N(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"&&N(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&N(this.params.desiredState.playbackState,"paused");return;default:return(0,Ie.assertNever)(e)}};this.params=e,this.video=ze(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Iy.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,xc.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:Ie.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,Ie.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(Ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),a(ft(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),N(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),N(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,Ie.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),N(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=(0,Ie.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Ie.observableFrom)(["init"])).pipe((0,Ie.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),Ye(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,Ie.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,Ie.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=gi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ne(t))}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),N(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ie.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let f=Bt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,xc.default)(this.trackUrls).map(d=>d.track);if(!r||!a||Ir(e,n[0].quality,(c=(0,Ey.default)(n,-1))==null?void 0:c.quality)){i();return}let o=e.max?(0,Ie.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,Ie.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var Ee=require("@vkontakte/videoplayer-shared/es2015");var wy=require("@vkontakte/videoplayer-shared/es2015");var xy=["stun:videostun.mycdn.me:80"],F$=1e3,N$=3,wc=()=>null,Eo=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=wc;this.externalStopCallback=wc;this.externalErrorCallback=wc;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 R(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 R(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 R(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return R(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:wy.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return R(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 R(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),F$)}normalizeOptions(e={}){let t={stunServerList:xy,maxRetryNumber:N$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var va=class{constructor(e){this.videoState=new ne("stopped");this.maxSeekBackTime$=new Ee.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.hostname$.next(void 0),this.videoState.setState("stopped"),N(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),N(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"&&N(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&N(this.params.desiredState.playbackState,"paused");return;default:return(0,Ee.assertNever)(e)}};this.subscription=new Ee.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ze(e.container,e.tuning),this.liveStreamClient=new Eo(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ye(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ee.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,Ee.merge)(this.videoState.stateChangeStarted$.pipe((0,Ee.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Ee.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(ft(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(Ke(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,Ee.assertNever)(n.to)}},i)).add((0,Ee.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Ee.observableFrom)(["init"])).pipe((0,Ee.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(Ne(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:Ee.VideoQuality.INVARIANT}),this.video.srcObject=e,N(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ee.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),N(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ee.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var _r=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 x=require("@vkontakte/videoplayer-shared/es2015");var Jt=require("@vkontakte/videoplayer-shared/es2015"),Ay=s=>new Jt.Observable(e=>{let t=new Jt.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe((0,Jt.map)(({from:l,to:c})=>`${l}-${c}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe((0,Jt.map)(({type:l})=>l!==void 0)),n=new Jt.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var bt=require("@vkontakte/videoplayer-shared/es2015");function Py(){return new(window.AudioContext||window.webkitAudioContext)}var Sa=class Sa{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new fe;this.subscriptions=new bt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,bt.filter)(a=>!!a.type),(0,bt.once)()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){K.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,bt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,bt.filter)(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),(0,bt.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 R(this,null,function*(){let{volumeMultiplier:t}=this,i=Py();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 a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.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:Sa.errorId,category:bt.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Sa.errorId} exception`,thrown:e})}};Sa.errorId="VolumeMultiplierManager";var Or=Sa;var q$={chunkDuration:5e3,maxParallelRequests:5},ya=class{constructor(e){this.current$=new x.ValueSubject({type:void 0});this.providerError$=new x.Subject;this.noAvailableProvidersError$=new x.Subject;this.volumeMultiplierError$=new x.Subject;this.providerOutput={position$:new x.ValueSubject(0),duration$:new x.ValueSubject(1/0),volume$:new x.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new x.ValueSubject([]),currentVideoStream$:new x.ValueSubject(void 0),availableVideoTracks$:new x.ValueSubject([]),currentVideoTrack$:new x.ValueSubject(void 0),availableVideoCodecs$:new x.ValueSubject([]),availableAudioStreams$:new x.ValueSubject([]),currentAudioStream$:new x.ValueSubject(void 0),availableAudioTracks$:new x.ValueSubject([]),availableAudioCodecs$:new x.ValueSubject([]),currentVideoSegmentLength$:new x.ValueSubject(0),currentAudioSegmentLength$:new x.ValueSubject(0),isAudioAvailable$:new x.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new x.ValueSubject(!1),autoVideoTrackLimits$:new x.ValueSubject(void 0),currentBuffer$:new x.ValueSubject(void 0),isBuffering$:new x.ValueSubject(!0),error$:new x.Subject,fetcherError$:new x.Subject,fetcherRecoverableError$:new x.Subject,warning$:new x.Subject,willSeekEvent$:new x.Subject,soundProhibitedEvent$:new x.Subject,seekedEvent$:new x.Subject,loopedEvent$:new x.Subject,endedEvent$:new x.Subject,manifestRequested$:new x.Subject,manifestReceived$:new x.Subject,firstBytesRequested$:new x.Subject,firstBytesReceived$:new x.Subject,firstBytesEvent$:new x.Subject,loadedMetadataEvent$:new x.Subject,firstFrameEvent$:new x.Subject,canplay$:new x.Subject,isLive$:new x.ValueSubject(void 0),isLiveEnded$:new x.ValueSubject(null),canPlayLiveTailBuffer$:new x.ValueSubject(!1),isLowLatency$:new x.ValueSubject(!1),canChangePlaybackSpeed$:new x.ValueSubject(!0),liveTime$:new x.ValueSubject(void 0),liveBufferTime$:new x.ValueSubject(void 0),liveLatency$:new x.ValueSubject(void 0),severeStallOccurred$:new x.Subject,availableTextTracks$:new x.ValueSubject([]),currentTextTrack$:new x.ValueSubject(void 0),hostname$:new x.ValueSubject(void 0),httpConnectionType$:new x.ValueSubject(void 0),httpConnectionReused$:new x.ValueSubject(void 0),inPiP$:new x.ValueSubject(!1),inFullscreen$:new x.ValueSubject(!1),element$:new x.ValueSubject(void 0),elementVisible$:new x.ValueSubject(!0),availableSources$:new x.ValueSubject(void 0),is3DVideo$:new x.ValueSubject(!1),playbackState$:new x.ValueSubject(""),getCurrentTime$:new x.ValueSubject(null)};this.subscription=new x.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=xl([...ty(this.params.tuning),...ey(this.params.tuning)]).filter(l=>(0,x.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Ac.default)(r,l)),...t.filter(l=>(0,Ac.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",(0,x.flattenObject)(a)),this.screenFormatsIterator=new _r(a);let n=[...lc(!0),...lc(!1)];this.chromecastFormatsIterator=new _r(n.filter(l=>(0,x.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Or.isSupported()&&(this.volumeMultiplierManager=new Or(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){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 _r(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,x.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:x.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 a=this.providerOutput.isBuffering$;a.getValue()||a.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,x.assertNever)(e)}}createScreenProvider(e){var u,l;let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let c=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,x.assertNonNullable)(c),this.params.tuning.useNewDashProvider?new ha(j(C({},o),{source:c,sourceHls:d,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()})):new la(j(C({},o),{source:c,sourceHls:d,forceVideoCodec:(l=this.videoCodecsIterator)==null?void 0:l.getValue()}))}case"DASH_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),this.params.tuning.useNewDashProvider?new fa(j(C({},o),{source:c})):new ca(j(C({},o),{source:c}))}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),new ba(j(C({},o),{source:c}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),new ma(j(C({},o),{source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),new ga(j(C({},o),{source:c}))}case"DASH_LIVE":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),new Jg(j(C({},o),{source:c,config:j(C({},q$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),new va({container:i,source:c,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,x.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,x.assertNonNullable)(o),new Ss({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,x.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,x.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,x.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 a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return j(C({},e),{url:i(e.url)})}return(0,ky.default)((0,Ry.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new x.Subscription,t=!1,i=0;return e.add((0,x.merge)(this.providerOutput.error$.pipe((0,x.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Ay({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,x.map)(r=>({id:`ProviderHangup:${r}`,category:x.ErrorCategory.WTF,message:`A ${r} 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 r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,x.filter)(({to:a})=>a==="playing"),(0,x.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===x.ErrorCategory.NETWORK,u=r.category===x.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,f=l&&!u&&(o&&t||!c);n=j(C({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:f,canReinitProvider:c}),c?(i++,this.reinitProvider()):f?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",(0,x.flattenObject)(n)):this.tracer.error("providerError",(0,x.flattenObject)(n))})),e}};var se=require("@vkontakte/videoplayer-shared/es2015");var U$=5e3,Ly="one_video_throughput",$y="one_video_rtt",Zt=window.navigator.connection,My=()=>{let s=Zt==null?void 0:Zt.downlink;if((0,se.isNonNullable)(s)&&s!==10)return s*1e3},Dy=()=>{let s=Zt==null?void 0:Zt.rtt;if((0,se.isNonNullable)(s)&&s!==3e3)return s},Cy=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Pc=class s{constructor(e){this.subscription=new se.Subscription;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(Ly)||(e.useBrowserEstimation?My():void 0)||U$,i=(a=(r=s.load($y))!=null?r:e.useBrowserEstimation?Dy():void 0)!=null?a:0;if(this.throughput$=new se.ValueSubject(t),this.rtt$=new se.ValueSubject(i),this.rttAdjustedThroughput$=new se.ValueSubject(Cy(t,i,e.rttPenaltyRequestSize)),this.throughput=Xt.getSmoothedValue(t,-1,e),this.rtt=Xt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=My();u&&this.throughput.next(u);let l=Dy();(0,se.isNonNullable)(l)&&this.rtt.next(l)};Zt&&"onchange"in Zt&&this.subscription.add((0,se.fromEvent)(Zt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{se.safeStorage.set(Ly,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{se.safeStorage.set($y,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,se.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,se.map)(({throughput:n,rtt:o})=>Cy(n,o,e.rttPenaltyRequestSize)),(0,se.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,se.now)(),r=new se.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,se.fromEvent)(e,"progress").pipe((0,se.once)()).subscribe(a=>{t=a.loaded,i=(0,se.now)()}));break;case 1:case 0:r.add((0,se.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,se.now)()}));break}r.add((0,se.fromEvent)(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=(0,se.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,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,a=(0,se.now)(),n=0,o=(0,se.now)(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=f=>R(this,[f],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(r,(0,se.now)()-a,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,se.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-a;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,a=(0,se.now)()}else n+=d.byteLength;o=(0,se.now)()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,se.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,se.now)()-o,this.concurrentDownloads.size),n=0,o=(0,se.now)());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*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=se.safeStorage.get(e);if((0,se.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},By=Pc;var Yi=require("@vkontakte/videoplayer-shared/es2015");var Vy={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{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:Yi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Yi.VideoQuality.Q_720P,trafficSavingLimit:Yi.VideoQuality.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,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:Yi.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,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1},dashCmafLive:{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",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,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},_y=s=>{var e;return j(C({},(0,Yi.fillWithDefault)(s,Vy)),{configName:[...(e=s.configName)!=null?e:[],...Vy.configName]})};var m=require("@vkontakte/videoplayer-shared/es2015");var ei=require("@vkontakte/videoplayer-shared/es2015"),Rc=({seekState:s,position$:e})=>(0,ei.merge)(s.stateChangeEnded$.pipe((0,ei.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,ei.filter)(ei.isNonNullable)),e.pipe((0,ei.filter)(()=>s.getState().state==="none")));var Oy=require("@vkontakte/videoplayer-shared/es2015"),Fy=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return(0,Oy.assertNonNullable)(e,`Wrong container or containerId {${s.container}}`),e};var xo=require("@vkontakte/videoplayer-shared/es2015"),Ny=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,xo.filter)(r=>r.length>0),(0,xo.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Ta=class{constructor(e={configName:[]},t=m.TracerFactory.createRootTracer(!1)){this.subscription=new m.Subscription;this.logger=new m.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new m.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new m.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 m.ValueSubject(void 0),position$:new m.ValueSubject(0),duration$:new m.ValueSubject(1/0),muted$:new m.ValueSubject(!1),volume$:new m.ValueSubject(1),availableVideoStreams$:new m.ValueSubject([]),currentVideoStream$:new m.ValueSubject(void 0),availableQualities$:new m.ValueSubject([]),availableQualitiesFps$:new m.ValueSubject({}),currentQuality$:new m.ValueSubject(void 0),isAutoQualityEnabled$:new m.ValueSubject(!0),autoQualityLimitingAvailable$:new m.ValueSubject(!1),autoQualityLimits$:new m.ValueSubject({}),predefinedQualityLimitType$:new m.ValueSubject("unknown"),availableAudioStreams$:new m.ValueSubject([]),currentAudioStream$:new m.ValueSubject(void 0),availableAudioTracks$:new m.ValueSubject([]),isAudioAvailable$:new m.ValueSubject(!0),currentPlaybackRate$:new m.ValueSubject(1),currentBuffer$:new m.ValueSubject({start:0,end:0}),isBuffering$:new m.ValueSubject(!0),isStalled$:new m.ValueSubject(!1),isEnded$:new m.ValueSubject(!1),isLooped$:new m.ValueSubject(!1),isLive$:new m.ValueSubject(void 0),isLiveEnded$:new m.ValueSubject(null),canPlayLiveTailBuffer$:new m.ValueSubject(!1),canChangePlaybackSpeed$:new m.ValueSubject(void 0),atLiveEdge$:new m.ValueSubject(void 0),atLiveDurationEdge$:new m.ValueSubject(void 0),liveTime$:new m.ValueSubject(void 0),liveBufferTime$:new m.ValueSubject(void 0),liveLatency$:new m.ValueSubject(void 0),currentFormat$:new m.ValueSubject(void 0),availableTextTracks$:new m.ValueSubject([]),currentTextTrack$:new m.ValueSubject(void 0),throughputEstimation$:new m.ValueSubject(void 0),rttEstimation$:new m.ValueSubject(void 0),videoBitrate$:new m.ValueSubject(void 0),hostname$:new m.ValueSubject(void 0),httpConnectionType$:new m.ValueSubject(void 0),httpConnectionReused$:new m.ValueSubject(void 0),surface$:new m.ValueSubject("none"),chromecastState$:new m.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new m.ValueSubject(void 0),intrinsicVideoSize$:new m.ValueSubject(void 0),availableSources$:new m.ValueSubject(void 0),is3DVideo$:new m.ValueSubject(!1),currentVideoSegmentLength$:new m.ValueSubject(0),currentAudioSegmentLength$:new m.ValueSubject(0)};this.events={inited$:new m.Subject,ready$:new m.Subject,started$:new m.Subject,playing$:new m.Subject,paused$:new m.Subject,stopped$:new m.Subject,willReady$:new m.Subject,willStart$:new m.Subject,willResume$:new m.Subject,willPause$:new m.Subject,willStop$:new m.Subject,willDestruct$:new m.Subject,watchCoverageRecord$:new m.Subject,watchCoverageLive$:new m.Subject,managedError$:new m.Subject,fatalError$:new m.Subject,fetcherRecoverableError$:new m.Subject,ended$:new m.Subject,looped$:new m.Subject,seeked$:new m.Subject,willSeek$:new m.Subject,autoplaySoundProhibited$:new m.Subject,manifestRequested$:new m.Subject,manifestReceived$:new m.Subject,firstBytesRequested$:new m.Subject,firstBytesReceived$:new m.Subject,firstBytes$:new m.Subject,loadedMetadata$:new m.Subject,firstFrame$:new m.Subject,canplay$:new m.Subject,log$:new m.Subject,fetcherError$:new m.Subject,severeStallOccured$:new m.Subject};this.experimental={element$:new m.ValueSubject(void 0),tuningConfigName$:new m.ValueSubject([]),enableDebugTelemetry$:new m.ValueSubject(!1),dumpTelemetry:Bg,getCurrentTime$:new m.ValueSubject(null)};if(this.initLogs(),this.tuning=_y(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,kc.default)(this.info).forEach(i=>i.setSuppressErrors(!0)),(0,kc.default)(this.events).forEach(i=>i.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Qa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new By(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new m.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(f=>JSON.stringify(f,(p,h)=>{let b=typeof h;return(0,qy.default)(["number","string","boolean"],b)?h:h===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:m.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var l,c,d;let u=e,{container:n}=u,o=bd(u,["container"]);this.tracer.log("initVideo",(0,m.flattenObject)(o)),this.domContainer=Fy(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new ya({sources:e.sources,meta:(c=e.meta)!=null?c:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],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)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?K.isInited$.pipe((0,m.filter)(n=>!!n),(0,m.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,m.fromEvent)(document,"visibilitychange").pipe((0,m.once)()).subscribe(r)):r(),this}destroy(){var e,t;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()}prepare(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.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.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{(0,m.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,m.filter)(i=>i.length>0),(0,m.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",(0,m.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{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.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{var i;(0,m.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,m.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>C({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{var t;Ny(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.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",C({},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.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{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.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>e),(0,m.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,m.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,m.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,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Cl(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.filter)(({from:e})=>e==="stopped"),(0,m.once)()).subscribe(()=>{this.initedAt=(0,m.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,m.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(j(C({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:m.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,m.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,m.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,m.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,m.map)(n=>n.destination),(0,m.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,m.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,m.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,m.isInvariantQuality)(u)?1:(0,m.isInvariantQuality)(l)?-1:(0,m.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,m.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,m.filter)(n=>(0,m.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,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,m.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,m.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,m.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,m.combine)({hasLiveOffsetByPaused:(0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(n=>n.to),(0,m.filterChanged)(),(0,m.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,m.combine)({atLiveEdge:(0,m.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Rc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,m.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,m.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,m.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,m.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.muted),(0,m.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.volume),(0,m.filterChanged)()).subscribe(this.info.volume$)).add(Rc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,m.merge)(e.providerOutput.endedEvent$.pipe((0,m.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,m.mapTo)(!1))).pipe((0,m.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,m.map)(n=>({id:n?`No${n}`:"NoProviders",category:m.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,m.once)()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe((0,m.once)()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe((0,m.once)()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe((0,m.once)()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe((0,m.once)(),(0,m.map)(n=>n!=null?n:(0,m.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.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 m.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new m.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.filter)(({to:n})=>n==="playing"),(0,m.once)()).subscribe(()=>i.next(!1)));let r=0,a=(0,m.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,m.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,m.filterChanged)());this.subscription.add(a.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,m.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,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,m.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(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,m.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 m.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,m.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,m.filter)(i=>i.length>0),(0,m.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:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Bt(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,m.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,m.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,m.assertNonNullable)(this.providerContainer),(0,m.assertNonNullable)(e),Cg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Dg(i)),this.providerContainer.current$.subscribe(({type:i})=>Ts("provider",i)),e.duration$.subscribe(i=>Ts("duration",i)),e.availableVideoTracks$.pipe((0,m.filter)(i=>!!i.length),(0,m.once)()).subscribe(i=>Ts("tracks",i)),this.events.fatalError$.subscribe(new Qe("fatalError")),this.events.managedError$.subscribe(new Qe("managedError")),e.position$.subscribe(new Qe("position")),e.currentVideoTrack$.pipe((0,m.map)(i=>i==null?void 0:i.quality)).subscribe(new Qe("quality")),this.info.currentBuffer$.subscribe(new Qe("buffer")),e.isBuffering$.subscribe(new Qe("isBuffering"))].forEach(i=>this.subscription.add(i)),Ts("codecs",K.video.supportedCodecs)}initTracerSubscription(){let e=(0,m.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,m.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,m.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,m.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,m.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,m.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,m.filter)(i=>i>0),(0,m.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,m.filter)(i=>i>0),(0,m.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,m.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,m.filter)(i=>i.end>0),(0,m.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,m.filterChanged)())}).pipe((0,m.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,m.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,m.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,m.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,m.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,m.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,m.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,m.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,m.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,m.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,m.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,m.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,m.filterChanged)(),(0,m.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=()=>R(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:m.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,m.merge)((0,m.fromEvent)(document,"visibilitychange"),(0,m.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?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,m.flattenObject)({quality:t,availableTracks:(0,m.flattenObject)(e),track:(0,m.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&&!Ps()}};var Nt=require("@vkontakte/videoplayer-shared/es2015"),H$=`@vkontakte/videoplayer-core@${$o}`;
|
|
178
|
+
`;var Vr=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 io(this.params.fov,this.params.orientation),this.cameraRotationManager=new ro(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"),a=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(a,-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(sy,this.gl.VERTEX_SHADER),i=this.createShader(ay,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,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,f=t+r;return[a,n,o,u,l,c,d,f]}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 Te=require("@vkontakte/videoplayer-shared/es2015");var so="stalls_manager_metrics",cc="stalls_manager_abr_params",ny="stalls_manager_default_tuning_abr_params",dc=class{constructor(){this.isSeeked$=new Te.ValueSubject(!1);this.isBuffering$=new Te.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 Te.Subscription;this.severeStallOccurred$=new Te.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.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(cc):{};return C(C({},this.abrParams),e)}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Te.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,Te.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}=C({},this.getStoredData(ny)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}=C({},this.abrParams);this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(cc),this.setStoredData(ny,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(so,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+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 a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(so,[]),this.setStoredData(cc,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(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=Te.safeStorage.get(e))!=null?i:t)}setStoredData(e,t){Te.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){Te.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(so,"[]"),r=t/e,a=i.length?Kt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(so,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,Te.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,Te.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,Te.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if((0,Te.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=(0,Te.now)(),d=r&&this.currentStallsCount>=r,f=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Te.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,Te.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},a)),this.lastStallDuration=t}))}},ao=dc;var Ze=require("@vkontakte/videoplayer-shared/es2015"),no=class{constructor(){this.subscription=new Ze.Subscription;this.pipSize$=new Ze.ValueSubject(void 0);this.videoSize$=new Ze.ValueSubject(void 0);this.elementSize$=new Ze.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Ze.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,Ze.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,Ze.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Ze.map)(({videoSize:r,inPip:a,pipSize:n})=>a?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 Qi=class{constructor(e){this.subscription=new ie.Subscription;this.videoState=new ne("stopped");this.observableVideo=null;this.droppedFramesManager=new wr;this.stallsManager=new ao;this.elementSizeManager=new no;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new fi;this.audioTrackSwitchHistory=new fi;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.hostname$.next(void 0),this.videoState.setState("stopped"),N(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"),N(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&N(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"&&N(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&N(this.params.desiredState.playbackState,"paused");return;default:return(0,ie.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Vr(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:((a=e.projectionData)==null?void 0:a.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 ht(e.source.url),this.params=e,this.video=ze(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(Ne(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 to({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,ie.isNullable)(this.observableVideo)&&(this.observableVideo=Xe(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:ie.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,ie.filter)(l=>!!l.length),(0,ie.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,ie.map)(l=>l.to.state!=="none"),(0,ie.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$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,ie.filter)(ie.isNonNullable),(0,ie.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,ie.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(Ct(this.video,t.isLooped,r)),this.subscription.add(Ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ft(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),N(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),N(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"),N(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 c=this.player.getStreams(),d=this.player.getCodecs();if((0,ie.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(tc(h));let b=[];for(let S of h.representations){let g=zS(S);b.push(g),this.audioTracksMap.set(g,{stream:h,representation:S})}this.audioStreamsMap.set(h,b)}this.params.output.availableAudioStreams$.next(p)}let f=[];for(let p of c.video){f.push(ic(p));let h=[];for(let b of p.representations){let S=GS(j(C({},b),{streamId:p.id}));S&&(h.push(S),this.videoTracksMap.set(S,{stream:p,representation:b}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(f);for(let p of c.text)for(let h of p.representations){let b=YS(p,h);this.textTracksMap.set(b,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),d!=null&&d.video&&this.params.output.availableVideoCodecs$.next(d.video),d!=null&&d.audio&&this.params.output.availableAudioCodecs$.next(d.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)),this.subscription.add((0,ie.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,ie.fromEvent)(this.video,"progress")).pipe((0,ie.filter)(()=>this.videoTracksMap.size>0)).subscribe(()=>R(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,oy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[f,p]=d,h=[...this.videoTracksMap.keys()].find(S=>{var g;return((g=this.videoTracksMap.get(S))==null?void 0:g.representation.id)===f.id});(0,ie.isNonNullable)(h)&&(this.stallsManager.lastVideoTrackSelected=h);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",f.id),p){let S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,S)}}),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.currentVideoRepresentation$.pipe((0,ie.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(ic(f));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,ie.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(tc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.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 o=t.playbackState.stateChangeStarted$.pipe((0,ie.map)(({to:l})=>l==="ready"),(0,ie.filterChanged)());this.subscription.add((0,ie.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,ie.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,ie.merge)(o,this.player.state$.stateChangeEnded$,(0,ie.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,ie.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ie.observableFrom)(["init"])).pipe((0,ie.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var M,Q,H,Z,le,he,F,$,P,V,q,we,tt;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Es:Is,t=this.params.tuning.useNewAutoSelectVideoTrack?Mn:$n,i=this.params.tuning.useNewAutoSelectVideoTrack?Bt:Ln,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(M=r.videoTrack.getState())==null?void 0:M.id,l=[...this.videoTracksMap.keys()].find(({id:Se})=>Se===o),c=a.currentVideoTrack$.getValue(),d=((Z=(H=r.videoStream.getState())!=null?H:l&&((Q=this.videoTracksMap.get(l))==null?void 0:Q.stream))!=null?Z:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let f=[...this.videoStreamsMap.keys()].find(({id:Se})=>Se===d.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=Be(this.video.buffered,this.video.currentTime*1e3),b;this.player.isActiveLive$.getValue()?b=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?b=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:b=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let S=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(h/Math.min(b,S||1/0),1),y=(le=r.audioStream.getState())!=null?le:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,A=(he=[...this.audioStreamsMap.keys()].find(({id:Se})=>Se===(y==null?void 0:y.id)))!=null?he:this.audioStreamsMap.keys().next().value,E=0;if(A){if(l&&!n){let Se=e(l,p,(F=this.audioStreamsMap.get(A))!=null?F:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,($=Se==null?void 0:Se.bitrate)!=null?$:-1/0)}if(c){let Se=e(c,p,(P=this.audioStreamsMap.get(A))!=null?P:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);E=Math.max(E,(V=Se==null?void 0:Se.bitrate)!=null?V:-1/0)}}let w=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:E,forwardBufferHealth:g,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}),_=n?w!=null?w:l:l!=null?l:w,W=A&&t(_,p,(q=this.audioStreamsMap.get(A))!=null?q:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),O=(we=this.videoTracksMap.get(_))==null?void 0:we.representation,U=W&&((tt=this.audioTracksMap.get(W))==null?void 0:tt.representation);if(O&&U)return[O,U];if(O&&!U&&this.audioTracksMap.size===0)return[O,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),N(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ie.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),Ye(this.video),this.tracer.end()}};var la=class extends Qi{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 be=require("@vkontakte/videoplayer-shared/es2015");var ca=class extends Qi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,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 be.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,be.filterChanged)()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe((0,be.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,be.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,be.map)(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,be.filter)(u=>(0,be.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add((0,be.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,be.merge)(r.playbackRateState$,new be.ValueSubject(1))}).pipe((0,be.filter)(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||(0,be.isNullable)(c)||(t=u-c)})).add((0,be.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,be.merge)(r.playbackRateState$,new be.ValueSubject(1))}).pipe((0,be.filterChanged)((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||(0,be.isNullable)(u)||(0,be.isNullable)(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=KS(u);this.params.output.availableTextTracks$.next([l])}}))}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 re=require("@vkontakte/videoplayer-shared/es2015");var vy=Y(je(),1),vc=Y(Ls(),1);var T=require("@vkontakte/videoplayer-shared/es2015");var po=Y(je(),1),Gi=Y(xt(),1),ho=Y(Ls(),1);var by=Y(gn(),1);var Si=require("@vkontakte/videoplayer-shared/es2015");var k$=18,uy=!1;try{uy=K.browser.isSafari&&!!K.browser.safariVersion&&K.browser.safariVersion<=k$}catch(s){console.error(s)}var pc=class{constructor(e){this.bufferFull$=new Si.Subject;this.error$=new Si.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Si.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(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 R(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};uy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!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.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(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Si.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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,Si.assertNever)(t)}}},ly=pc;var L=require("@vkontakte/videoplayer-shared/es2015");var hc=Y(xt(),1);var oo=require("@vkontakte/videoplayer-shared/es2015"),cy=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?hi(a):void 0)!=null?u:(0,oo.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},dy=({id:s,bitrate:e})=>({id:s,bitrate:e}),py=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),hy=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),fc=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,hc.default)(i.split("."),0),isDefault:r}),mc=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,hc.default)(r.split("."),0)}),bc=s=>"url"in s,lt=s=>s.type==="template";var fy=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},Wi=(s,e)=>{for(let t of s)if(e(t))return t;return null},my=s=>{let e=!1,t=(0,oo.throttleFn)(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var co=require("@vkontakte/videoplayer-shared/es2015");var uo=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var lo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new co.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,co.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!te(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=uo(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var da=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new L.ValueSubject(0);this.currentLowLatencySegmentLength$=new L.ValueSubject(0);this.currentSegmentLength$=new L.ValueSubject(0);this.onLastSegment$=new L.ValueSubject(!1);this.fullyBuffered$=new L.ValueSubject(!1);this.playingRepresentation$=new L.ValueSubject(void 0);this.playingRepresentationInit$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.gaps=[];this.subscription=new L.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new fe;this.switchAbortController=new fe;this.destroyAbortController=new fe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=(0,L.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){let t=this.representations.get(e);(0,L.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 ly(this.sourceBuffer),this.sourceBufferBufferedDiff=new lo(this.mediaSource,this.sourceBuffer),this.subscription.add((0,L.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,L.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.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,kr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Be(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,L.assertNonNullable)(i,"No init buffer for starting representation"),(0,L.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(a))})}.bind(this));this.switchTo=(0,L.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(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,L.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,L.isNullable)(a)||(0,L.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,L.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,L.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,L.abortable)(this.destroyAbortController.signal,function(e,t=!1){return oe(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,L.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,L.isNullable)(a)||(0,L.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,L.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,L.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Pi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,L.abortable)(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){var u,l;let t=(u=(0,ho.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!lt(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,L.assertNonNullable)(r);let a=this.segments.get(i);(0,L.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,L.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),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 fe,(0,L.abortable)(this.switchAbortController.signal,function(i,r=!1){return oe(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,L.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,L.isNullable)(o)||(0,L.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,L.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,L.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,L.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return R(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new fe,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,L.isNullable)(e)||(0,L.isNullable)(this.downloadingRepresentationId)||(0,L.isNullable)(this.playingRepresentationId)||(0,L.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||(0,L.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,L.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);(0,L.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Be(this.sourceBuffer.buffered,e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(a=d)}if(isFinite(this.bufferLimit)&&kr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=Be(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,po.default)(u,r))c="high";else{let d=(0,Gi.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&Be(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Gi.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Be(this.sourceBuffer.buffered,e)<n),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 a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;(0,L.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=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,ho.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,ho.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!lt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>j(C({},p),{status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(a=(0,Gi.default)(c,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,L.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!lt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=At(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a: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,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&_t&&_t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_t&&_t(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:f,time:{from:p,to:h}},b)=>{let S=p<=i&&h>=i,g=p>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&g&&A&&this.sourceBuffer&&te(this.mediaSource,this.sourceBuffer)&&!(qe(this.sourceBuffer.buffered,p)&&qe(this.sourceBuffer.buffered,h)))&&g&&A});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=a;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}loadSegments(e,t,i="auto"){return R(this,null,function*(){lt(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return R(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:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,L.abortable)(o,function(){return oe(this,null,function*(){let c=(0,L.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,L.now)(),!c)return;let d=new DataView(c),f=Ot(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ft(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())lt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return R(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:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,L.abortable)(n,function(){return oe(this,null,function*(){let u=(0,L.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,L.fromEvent)(window,"online").pipe((0,L.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,L.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ft(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(lt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Gi.default)(e,0).byte.from,to:(0,Gi.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>R(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,L.now)(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:L.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!lt(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:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,L.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:L.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,po.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){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:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ot(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!te(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let{segment:c}=l,d=c.byte.from-i,f=c.byte.to-i,p=f-d+1,h=d<r,b=f<=r;if(h){if(c.status==="downloading"&&b){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),g=l.loadedBytes===p?S:Ot(u.mime).parseFeedableSegmentChunk(S);g!=null&&g.byteLength&&(c.status="partially_fed",l.feedingBytes+=g.byteLength,(yield this.sourceBufferTaskQueue.append(g,a))&&!a.aborted?(l.fedBytes+=g.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}}})}onSegmentFullyAppended(e,t){if(!((0,L.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer))){!this.isLive&&K.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qe(this.sourceBuffer.buffered,e.segment.time.from,100)&&qe(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:L.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",bc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&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,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Rr(()=>(0,by.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return R(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,L.abortable)(this.destroyAbortController.signal,function(){return oe(this,null,function*(){let o=(0,L.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ot(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&<(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(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 R(this,null,function*(){if(!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,L.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push(C({},o.time));let u=bc(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let f of d)(0,po.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let d={time:{from:u,to:l},url:"",status:"none"};n(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=fy(r),(yield Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1})}abortBuffer(){return R(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)}}getBufferedTo(){return!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null: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,L.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.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}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,L.isNullable)(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||(0,L.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=uo(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let c=0;c<e.length;c+=2){let d=e[c],f=e[c+1];u||(u=d-t<=n&&f+t>=o),(n>=d&&n<f-t||o>d+t&&o<=f)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:L.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,Gi.default)(e,-1))==null?void 0:t.time.to:0)||0}};var J=require("@vkontakte/videoplayer-shared/es2015");var mo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!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.recoverableError$=new J.Subject;this.error$=new J.Subject;this.abortAllController=new fe;this.subscription=new J.SubscriptionRemovable;this.fetchManifest=(0,J.abortable)(this.abortAllController.signal,function(e){return oe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=gi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Hn(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(fo);return r?(t.log("success",(0,J.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(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(c){return oe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var le,he,F;let d=e,f=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{f.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(d,location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),d=$.toString();break}default:(0,J.assertNever)(t)}this.requestQuic&&(d=gi(d));let h=this.abortAllController.signal,b;if(n){let $=new fe;if(b=(0,J.merge)((0,J.fromEvent)(this.abortAllController.signal,"abort"),(0,J.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(P){fo(P)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(P){fo(P)}h=$.signal}let S=0,g=(0,J.now)();p.log("startRequest",(0,J.flattenObject)({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let y=yield this.doFetch(d,{priority:a,headers:f,signal:h}),A=(0,J.now)();if(!y)return p.error("error",{message:"No response in request"}),p.end(),this.unsubscribeAbortSubscription(b),null;if((le=this.throughputEstimator)==null||le.addRawRtt(A-g),!y.ok||!y.body){this.unsubscribeAbortSubscription(b);let $=`Fetch error ${y.status}: ${y.statusText}`;return p.error("error",{message:$}),p.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){this.unsubscribeAbortSubscription(b);let $=(0,J.now)(),P={requestStartedAt:g,requestEndedAt:$,duration:$-g};return p.log("endRequest",(0,J.flattenObject)(P)),p.end(),y.arrayBuffer()}let E=y.body;if(o){let $;[E,$]=y.body.tee(),(he=this.throughputEstimator)==null||he.trackStream($,u)}let w=E.getReader(),_,W=parseInt((F=y.headers.get("content-length"))!=null?F:"",10);Number.isFinite(W)&&(_=W),!_&&i&&(_=i.to-i.from+1);let O=_?new Uint8Array(_):new Uint8Array(0),U=!1,M=$=>{this.unsubscribeAbortSubscription(b),U=!0,fo($)},Q=(0,J.abortable)(h,function(V){return oe(this,arguments,function*({done:$,value:P}){if(S===0&&(this.lastRequestFirstBytes$.next((0,J.now)()-g),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(b);return}if(!$&&P){if(l&&_)O.set(P,S),S+=P.byteLength;else{let q=new Uint8Array(O.length+P.length);q.set(O),q.set(P,O.length),O=q,S+=P.byteLength}r==null||r(new DataView(O.buffer),S),yield w==null?void 0:w.read().then(Q,M)}})}.bind(this));yield w==null?void 0:w.read().then(Q,M),this.unsubscribeAbortSubscription(b);let H=(0,J.now)(),Z={failed:U,requestStartedAt:g,requestEndedAt:H,duration:H-g};return U?(p.error("endRequest",(0,J.flattenObject)(Z)),p.end(),null):(p.log("endRequest",(0,J.flattenObject)(Z)),p.end(),O.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t,i){return oe(this,null,function*(){var g;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(c,a))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(g=e.indexRange)!=null?g:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,p,h);return{init:p,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t){return oe(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});return r?{init:null,segments:e.segments.map(n=>j(C({},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=a}onHeadersReceived(e){let{type:t,reused:i}=Un(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return R(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,J.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}doFetch(e,t){return R(this,null,function*(){let i=yield mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:J.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:J.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:J.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:J.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:J.ErrorCategory.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},fo=s=>{if(!Ft(s))throw s};var bo=require("@vkontakte/videoplayer-shared/es2015");var pa=class s{constructor(e,t){this.currentRepresentation$=new bo.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,bo.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(j(C({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.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=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&<(t.segmentReference))}};var M$=["progress","play","seeked","stalled","waiting"],D$=["timeupdate","progress","loadeddata","playing","seeked"];var go=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;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.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.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.destroyController=new fe;this.initManifest=(0,T.abortable)(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Re(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 oe(this,null,function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=Fn(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=_n(e))!=null?u:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,b,S;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((S=(b=nt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let b="active";p||(b=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(b)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:b})=>i(c,h,b));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:b})=>b);c==="audio"&&(n=eo(h),p=n[0]),c==="video"&&(a=Zn(h),this.forceVideoCodec&&(0,vy.default)(a,this.forceVideoCodec)?p=this.forceVideoCodec:p=a[0]),p&&(r[c]=f.filter(({codecs:b})=>Br(b)===p))}else{let h=new Set(f.map(({codecs:b})=>b));p=Jn(h),p&&(r[c]=f.filter(({codecs:b})=>b.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,b=r.video.some(g=>g.hdr),S=r.video.some(g=>!g.hdr);K.display.isHDR&&h&&b?r.video=r.video.filter(g=>g.hdr):S&&(r.video=r.video.filter(g=>!g.hdr))}}let o=j(C({},t),{streams:r});return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,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 oe(this,null,function*(){var f;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.representationSubscription=new T.Subscription,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,T.fromEvent)(p,"error").pipe((0,T.filter)(h=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Tn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),Tr())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 da("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,b)=>[...h,...b.representations],[]);this.audioBufferManager=new da("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}pa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new pa(this.manifest.streams.text,n)),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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,T.merge)(...D$.map(p=>(0,T.fromEvent)(this.element,p))).pipe((0,T.map)(p=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),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(()=>{this.livePauseWatchdogSubscription=(0,T.interval)(1e3).subscribe(h=>{let b=di(this.manifestUrlString,2);this.manifestUrlString=Re(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(h=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:h,isLowLatency:b})=>h&&b),(0,T.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Cr(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:b,isLowLatency:S})=>b&&S&&!!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 b=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(b,-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,b)=>b.bufferLength<h.bufferLength),(0,T.map)(({rtt:h,bufferLength:b,segmentServerLatency:S})=>{let g=di(this.manifestUrlString,2);return(h/2+b+S+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:b,isLowLatency:S})=>{if(!S||!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=h-g;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(E)>y&&(w=1+Math.sign(E)*A),Cr(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var S,g;let b=0;if(h){let y=((g=(S=this.element)==null?void 0:S.currentTime)!=null?g:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var w,_;return(_=(w=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?_:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(1e3)).subscribe(S=>R(this,[S],function*({liveLoadBufferLength:h,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,y=di(this.manifestUrlString,2),A=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(A,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,_=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,W=isFinite(h)?h:b,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),U=A<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(U);let M="none";if(O?M="active_low_latency":this.isLowLatency$.getValue()&&U?(this.bufferManagers.forEach(Q=>Q.proceedLowLatencyLive()),M="active_low_latency"):y!==0&&W<E?M="live_forward_buffering":W<E+_&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let Q=p-(E+w),H=this.normolizeLiveOffset(Math.trunc(y+Q/g)),Z=Math.abs(H-y),le=0;!h||Z<=this.tuning.dashCmafLive.offsetCalculationError?le=y:H>0&&Z>this.tuning.dashCmafLive.offsetCalculationError&&(le=H),this.manifestUrlString=Re(this.manifestUrlString,le,2)}(M==="live_with_target_offset"||M==="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 l=(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:l,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 b;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.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)),(b=this.source)==null||b.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,vc.default)((0,vc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let b=[];return h.duration&&b.push(h.duration),lt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&b.push(h.segmentReference.totalSegmentsDurationMs),b})];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,a;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||(a=this.audioBufferManager)!=null&&a.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 mo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Xt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,C({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,a,n;(0,T.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Re(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,T.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,T.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,T.merge)(...M$.map(t=>(0,T.fromEvent)(this.element,t)),(0,T.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&qe(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,b,S,g,y,A,E,w,_,W,O;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=(0,T.now)(),o=100,u=(S=(b=this.videoBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?S:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(y=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?y:0,c=(E=(A=this.videoBufferManager)==null?void 0:A.getForwardBufferDuration())!=null?E:0,d=(_=(w=this.audioBufferManager)==null?void 0:w.getForwardBufferDuration())!=null?_:0,f=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let U=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(U).catch(M=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:M})}),a.liveLastOffset=U}else{let U=this.element.currentTime*1e3;(W=this.videoBufferManager)==null||W.maintain(U),(O=this.audioBufferManager)==null||O.maintain(U),a.position=U}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=(0,T.interval)(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return R(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 R(this,null,function*(){var r,a,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=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),qe(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.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(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(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.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",(0,T.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}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 et=require("@vkontakte/videoplayer-shared/es2015"),vo=class{constructor(){this.subscription=new et.Subscription;this.pipSize$=new et.ValueSubject(void 0);this.videoSize$=new et.ValueSubject(void 0);this.elementSize$=new et.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=et.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,et.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,et.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,et.map)(({videoSize:r,inPip:a,pipSize:n})=>a?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 zi=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new ne("stopped");this.observableVideo=null;this.droppedFramesManager=new wr;this.stallsManager=new ao;this.elementSizeManager=new vo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new fi;this.audioTrackSwitchHistory=new fi;this.selectedRepresentations={audio:null,video:null};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.hostname$.next(void 0),this.videoState.setState("stopped"),N(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"),N(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&N(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"&&N(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&N(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Vr(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:((a=e.projectionData)==null?void 0:a.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 ht(e.source.url),this.params=e,this.video=ze(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(Ne(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 go({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,re.isNullable)(this.observableVideo)&&(this.observableVideo=Xe(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:re.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,re.filter)(d=>!!d.length),(0,re.once)()).subscribe(d=>{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:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,re.map)(d=>d.to.state!=="none"),(0,re.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$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,re.filter)(re.isNonNullable),(0,re.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,re.map)(d=>d.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(Ct(this.video,t.isLooped,r)),this.subscription.add(Ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ft(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),N(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),N(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"),N(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:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams(),p=this.player.getCodecs();if((0,re.assertNonNullable)(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of f.audio){b.push(fc(S));let g=[];for(let y of S.representations){let A=dy(y);g.push(A),this.audioTracksMap.set(A,{stream:S,representation:y})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(b)}let h=[];for(let b of f.video){h.push(mc(b));let S=[];for(let g of b.representations){let y=cy(j(C({},g),{streamId:b.id}));y&&(S.push(y),this.videoTracksMap.set(y,{stream:b,representation:g}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(h);for(let b of f.text)for(let S of b.representations){let g=py(b,S);this.textTracksMap.set(g,{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),p!=null&&p.video&&this.params.output.availableVideoCodecs$.next(p.video),p!=null&&p.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&my(o)||null;this.subscription.add((0,re.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,re.fromEvent)(this.video,"progress")).pipe((0,re.filter)(()=>this.videoTracksMap.size>0)).subscribe(()=>R(this,null,function*(){let d=this.player.state$.getState(),f=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||f||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let b=Wi(this.videoTracksMap.keys(),g=>{var y;return((y=this.videoTracksMap.get(g))==null?void 0:y.representation.id)===p.id});(0,re.isNonNullable)(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),d==="manifest_ready")yield this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,g)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,re.filterChanged)()).subscribe(d=>{let f=Wi(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===h.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(mc(h));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,re.filterChanged)()).subscribe(d=>{let f=Wi(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===d);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===h.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(fc(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var f,p;if(d!=null&&d.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},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 l=t.playbackState.stateChangeStarted$.pipe((0,re.map)(({to:d})=>d==="ready"),(0,re.filterChanged)());this.subscription.add((0,re.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,re.observableFrom)(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,re.merge)(l,this.player.state$.stateChangeEnded$,(0,re.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=(0,re.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var O,U,M,Q,H,Z,le,he,F,$,P,V;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Es:Is,t=this.params.tuning.useNewAutoSelectVideoTrack?Mn:$n,i=this.params.tuning.useNewAutoSelectVideoTrack?Bt:Ln,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(O=r.videoTrack.getState())==null?void 0:O.id,u=Wi(this.videoTracksMap.keys(),q=>q.id===o),l=a.currentVideoTrack$.getValue(),c=((Q=(M=r.videoStream.getState())!=null?M:u&&((U=this.videoTracksMap.get(u))==null?void 0:U.stream))!=null?Q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Wi(this.videoStreamsMap.keys(),q=>q.id===c.id),f=d&&this.videoStreamsMap.get(d);if(!f)return;let p=Be(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=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(p/Math.min(h,b||1/0),1),g=(H=r.audioStream.getState())!=null?H:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(g==null?void 0:g.id)&&Wi(this.audioStreamsMap.keys(),q=>q.id===g.id)||this.audioStreamsMap.keys().next().value,A=0;if(y){if(u&&!n){let q=e(u,f,(Z=this.audioStreamsMap.get(y))!=null?Z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,(le=q==null?void 0:q.bitrate)!=null?le:-1/0)}if(l){let q=e(l,f,(he=this.audioStreamsMap.get(y))!=null?he:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);A=Math.max(A,(F=q==null?void 0:q.bitrate)!=null?F:-1/0)}}let E=u;(n||!E)&&(E=i(f,{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:A,forwardBufferHealth:S,current:l,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 w=y&&t(E,f,($=this.audioStreamsMap.get(y))!=null?$:[],{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}),_=(P=this.videoTracksMap.get(E))==null?void 0:P.representation,W=w&&((V=this.audioTracksMap.get(w))==null?void 0:V.representation);_&&W?(this.selectedRepresentations.video=_,this.selectedRepresentations.audio=W):_&&!W&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=_,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),N(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.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),Ye(this.video),this.tracer.end()}};var ha=class extends zi{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 ge=require("@vkontakte/videoplayer-shared/es2015");var fa=class extends zi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,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 ge.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,ge.filterChanged)()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe((0,ge.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,ge.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ge.map)(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,ge.filter)(u=>(0,ge.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add((0,ge.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ge.merge)(r.playbackRateState$,new ge.ValueSubject(1))}).pipe((0,ge.filter)(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||(0,ge.isNullable)(c)||(t=u-c)})).add((0,ge.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ge.merge)(r.playbackRateState$,new ge.ValueSubject(1))}).pipe((0,ge.filterChanged)((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||(0,ge.isNullable)(u)||(0,ge.isNullable)(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=hy(u);this.params.output.availableTextTracks$.next([l])}}))}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 Sy="X-Playback-Duration",Sc=s=>R(null,null,function*(){var r;let e=yield mt(s),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(Sy)?parseInt(e.headers.get(Sy),10):void 0});var ue=require("@vkontakte/videoplayer-shared/es2015");var Tc=Y(Cu(),1);var So=require("@vkontakte/videoplayer-shared/es2015");var B$=s=>{let e=null;if(s.QUALITY&&(e=hi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,So.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},V$=(s,e)=>{var a,n;let t=s.split(`
|
|
179
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Tc.default)(l[1].split(",").map(y=>y.split("="))),f=(a=d.QUALITY)!=null?a:`stream-${d.BANDWIDTH}`,p=B$(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[y,A]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));y&&A&&(S={width:y,height:A})}let g=new URL(t[++o],e).toString();p&&i.push({id:f,quality:p,url:g,bandwidth:h,size:S,fps:b})}if(c){let d=(0,Tc.default)(c[1].split(",").map(b=>{let S=b.indexOf("=");return[b.substring(0,S),b.substring(S+1)]}).map(([b,S])=>[b,S.replace(/^"|"$/g,"")])),f=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,h=d.NAME;f&&p&&r.push({type:"internal",id:p,label:h,language:p,url:f,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},_$=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),yc=0,yy=(r,...a)=>R(null,[r,...a],function*(s,e=s,t,i){let o=yield(yield mt(s,i)).text();yc+=1;try{let{qualityManifests:u,textTracks:l}=V$(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(yc<=t.manifestRetryMaxCount)return yield _$((0,So.getExponentialDelay)(yc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),yy(s,e,t)}return{qualityManifests:[],textTracks:[]}}),yo=yy;var ct=require("@vkontakte/videoplayer-shared/es2015");var To=class{constructor(e,t,i,r,a){this.subscription=new ct.Subscription;this.abortControllers={destroy:new fe,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new ct.ValueSubject(null);this.getCurrentTime$=new ct.ValueSubject(null);this.error$=new ct.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe((0,ct.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 R(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 R(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 R(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield mt(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
|
+
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+c},url:l}),a=a+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-d}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 l=new Date(u);l.setMilliseconds(0),a=l.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,ct.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([j(C({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return R(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new fe;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return R(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:ct.ErrorCategory.WTF,thrown:t,message:e})}};var ma=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 Fi;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(),a=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.hostname$.next(void 0),this.videoState.setState("stopped"),N(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?N(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),N(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"&&N(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 c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(N(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=ze(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,a)=>yo(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new To(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ht(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{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(a,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(Ne(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,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.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=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),a(ft(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(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"),N(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),N(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(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ue.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},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:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).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),Ye(this.video)}prepare(){var o,u,l;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:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[c,"mq"],[d,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Re(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Sc(n).then(c=>{var d;if(!(0,ue.isNullable)(c))this.maxSeekBackTime$.next(c);else{let f=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,ue.isNullable)(f)||!isFinite(f))&&mt(n).then(p=>p.text()).then(p=>{var b;let h=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(h){let S=new URL(h,n).toString();Sc(S).then(g=>{(0,ue.isNullable)(g)||this.maxSeekBackTime$.next(g)})}}).catch(()=>{})}})}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),N(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=Re(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 pe=require("@vkontakte/videoplayer-shared/es2015");var ba=class{constructor(e){this.subscription=new pe.Subscription;this.videoState=new ne("stopped");this.manifests$=new pe.ValueSubject([]);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(),a=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.hostname$.next(void 0),this.videoState.setState("stopped"),N(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?N(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),N(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"&&N(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&N(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,pe.assertNever)(t)}};this.textTracksManager=new ht(e.source.url),this.params=e,this.video=ze(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:pe.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(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),yo(Re(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.manifestReceived$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:pe.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:pe.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,pe.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(Ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),N(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),N(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 p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,pe.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(S=>S.id===h);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(Ne(b.url)))}let d=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==f){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),N(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe((0,pe.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!K.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,pe.merge)((0,pe.fromEvent)(o,"addtrack"),(0,pe.fromEvent)(o,"removetrack"),(0,pe.fromEvent)(o,"change"),(0,pe.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,pe.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,pe.observableFrom)(["init"])).pipe((0,pe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ye(this.video)}prepare(){var a,n;let e=this.selectManifest();if((0,pe.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=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),N(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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Ty=Y(cr(),1),Ic=Y(Di(),1),Iy=Y(xt(),1);var Ie=require("@vkontakte/videoplayer-shared/es2015");var ga=class{constructor(e){this.subscription=new Ie.Subscription;this.videoState=new ne("stopped");this.trackUrls={};this.textTracksManager=new ht;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.hostname$.next(void 0),this.videoState.setState("stopped"),N(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.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"?N(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),N(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"&&N(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&N(this.params.desiredState.playbackState,"paused");return;default:return(0,Ie.assertNever)(e)}};this.params=e,this.video=ze(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Ty.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Ic.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:Ie.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,Ie.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(Ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),a(ft(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),N(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),N(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,Ie.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),N(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=(0,Ie.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Ie.observableFrom)(["init"])).pipe((0,Ie.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),Ye(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,Ie.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,Ie.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=gi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ne(t))}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),N(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ie.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let f=Bt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,Ic.default)(this.trackUrls).map(d=>d.track);if(!r||!a||Ir(e,n[0].quality,(c=(0,Iy.default)(n,-1))==null?void 0:c.quality)){i();return}let o=e.max?(0,Ie.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,Ie.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var Ee=require("@vkontakte/videoplayer-shared/es2015");var xy=require("@vkontakte/videoplayer-shared/es2015");var Ey=["stun:videostun.mycdn.me:80"],O$=1e3,F$=3,Ec=()=>null,Io=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=Ec;this.externalStopCallback=Ec;this.externalErrorCallback=Ec;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 R(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 R(this,null,function*(){try{let e={iceServers:[{urls:Ey}]};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 R(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return R(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:xy.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return R(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 R(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),O$)}normalizeOptions(e={}){let t={stunServerList:Ey,maxRetryNumber:F$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var va=class{constructor(e){this.videoState=new ne("stopped");this.maxSeekBackTime$=new Ee.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.hostname$.next(void 0),this.videoState.setState("stopped"),N(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),N(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"&&N(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&N(this.params.desiredState.playbackState,"paused");return;default:return(0,Ee.assertNever)(e)}};this.subscription=new Ee.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ze(e.container,e.tuning),this.liveStreamClient=new Io(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ye(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ee.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,Ee.merge)(this.videoState.stateChangeStarted$.pipe((0,Ee.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Ee.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(ft(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(Ke(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,Ee.assertNever)(n.to)}},i)).add((0,Ee.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Ee.observableFrom)(["init"])).pipe((0,Ee.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(Ne(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:Ee.VideoQuality.INVARIANT}),this.video.srcObject=e,N(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ee.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),N(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ee.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var _r=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 x=require("@vkontakte/videoplayer-shared/es2015");var Jt=require("@vkontakte/videoplayer-shared/es2015"),wy=s=>new Jt.Observable(e=>{let t=new Jt.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe((0,Jt.map)(({from:l,to:c})=>`${l}-${c}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe((0,Jt.map)(({type:l})=>l!==void 0)),n=new Jt.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var bt=require("@vkontakte/videoplayer-shared/es2015");function Ay(){return new(window.AudioContext||window.webkitAudioContext)}var Sa=class Sa{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new fe;this.subscriptions=new bt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,bt.filter)(a=>!!a.type),(0,bt.once)()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){K.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,bt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,bt.filter)(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),(0,bt.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 R(this,null,function*(){let{volumeMultiplier:t}=this,i=Ay();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 a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.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:Sa.errorId,category:bt.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Sa.errorId} exception`,thrown:e})}};Sa.errorId="VolumeMultiplierManager";var Or=Sa;var N$={chunkDuration:5e3,maxParallelRequests:5},ya=class{constructor(e){this.current$=new x.ValueSubject({type:void 0});this.providerError$=new x.Subject;this.noAvailableProvidersError$=new x.Subject;this.volumeMultiplierError$=new x.Subject;this.providerOutput={position$:new x.ValueSubject(0),duration$:new x.ValueSubject(1/0),volume$:new x.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new x.ValueSubject([]),currentVideoStream$:new x.ValueSubject(void 0),availableVideoTracks$:new x.ValueSubject([]),currentVideoTrack$:new x.ValueSubject(void 0),availableVideoCodecs$:new x.ValueSubject([]),availableAudioStreams$:new x.ValueSubject([]),currentAudioStream$:new x.ValueSubject(void 0),availableAudioTracks$:new x.ValueSubject([]),availableAudioCodecs$:new x.ValueSubject([]),currentVideoSegmentLength$:new x.ValueSubject(0),currentAudioSegmentLength$:new x.ValueSubject(0),isAudioAvailable$:new x.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new x.ValueSubject(!1),autoVideoTrackLimits$:new x.ValueSubject(void 0),currentBuffer$:new x.ValueSubject(void 0),isBuffering$:new x.ValueSubject(!0),error$:new x.Subject,fetcherError$:new x.Subject,fetcherRecoverableError$:new x.Subject,warning$:new x.Subject,willSeekEvent$:new x.Subject,soundProhibitedEvent$:new x.Subject,seekedEvent$:new x.Subject,loopedEvent$:new x.Subject,endedEvent$:new x.Subject,manifestRequested$:new x.Subject,manifestReceived$:new x.Subject,firstBytesRequested$:new x.Subject,firstBytesReceived$:new x.Subject,firstBytesEvent$:new x.Subject,loadedMetadataEvent$:new x.Subject,firstFrameEvent$:new x.Subject,canplay$:new x.Subject,isLive$:new x.ValueSubject(void 0),isLiveEnded$:new x.ValueSubject(null),canPlayLiveTailBuffer$:new x.ValueSubject(!1),isLowLatency$:new x.ValueSubject(!1),canChangePlaybackSpeed$:new x.ValueSubject(!0),liveTime$:new x.ValueSubject(void 0),liveBufferTime$:new x.ValueSubject(void 0),liveLatency$:new x.ValueSubject(void 0),severeStallOccurred$:new x.Subject,availableTextTracks$:new x.ValueSubject([]),currentTextTrack$:new x.ValueSubject(void 0),hostname$:new x.ValueSubject(void 0),httpConnectionType$:new x.ValueSubject(void 0),httpConnectionReused$:new x.ValueSubject(void 0),inPiP$:new x.ValueSubject(!1),inFullscreen$:new x.ValueSubject(!1),element$:new x.ValueSubject(void 0),elementVisible$:new x.ValueSubject(!0),availableSources$:new x.ValueSubject(void 0),is3DVideo$:new x.ValueSubject(!1),playbackState$:new x.ValueSubject(""),getCurrentTime$:new x.ValueSubject(null)};this.subscription=new x.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=El([...ey(this.params.tuning),...ZS(this.params.tuning)]).filter(l=>(0,x.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,xc.default)(r,l)),...t.filter(l=>(0,xc.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",(0,x.flattenObject)(a)),this.screenFormatsIterator=new _r(a);let n=[...oc(!0),...oc(!1)];this.chromecastFormatsIterator=new _r(n.filter(l=>(0,x.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Or.isSupported()&&(this.volumeMultiplierManager=new Or(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){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 _r(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,x.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:x.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 a=this.providerOutput.isBuffering$;a.getValue()||a.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,x.assertNever)(e)}}createScreenProvider(e){var u,l;let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let c=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,x.assertNonNullable)(c),this.params.tuning.useNewDashProvider?new ha(j(C({},o),{source:c,sourceHls:d,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()})):new la(j(C({},o),{source:c,sourceHls:d,forceVideoCodec:(l=this.videoCodecsIterator)==null?void 0:l.getValue()}))}case"DASH_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),this.params.tuning.useNewDashProvider?new fa(j(C({},o),{source:c})):new ca(j(C({},o),{source:c}))}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),new ba(j(C({},o),{source:c}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),new ma(j(C({},o),{source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),new ga(j(C({},o),{source:c}))}case"DASH_LIVE":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),new Xg(j(C({},o),{source:c,config:j(C({},N$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let c=this.applyFailoverHost(t[e]);return(0,x.assertNonNullable)(c),new va({container:i,source:c,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,x.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,x.assertNonNullable)(o),new Ss({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,x.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,x.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,x.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 a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return j(C({},e),{url:i(e.url)})}return(0,Ry.default)((0,Py.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new x.Subscription,t=!1,i=0;return e.add((0,x.merge)(this.providerOutput.error$.pipe((0,x.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),wy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,x.map)(r=>({id:`ProviderHangup:${r}`,category:x.ErrorCategory.WTF,message:`A ${r} 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 r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,x.filter)(({to:a})=>a==="playing"),(0,x.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===x.ErrorCategory.NETWORK,u=r.category===x.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,f=l&&!u&&(o&&t||!c);n=j(C({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:f,canReinitProvider:c}),c?(i++,this.reinitProvider()):f?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",(0,x.flattenObject)(n)):this.tracer.error("providerError",(0,x.flattenObject)(n))})),e}};var se=require("@vkontakte/videoplayer-shared/es2015");var q$=5e3,ky="one_video_throughput",Ly="one_video_rtt",Zt=window.navigator.connection,$y=()=>{let s=Zt==null?void 0:Zt.downlink;if((0,se.isNonNullable)(s)&&s!==10)return s*1e3},My=()=>{let s=Zt==null?void 0:Zt.rtt;if((0,se.isNonNullable)(s)&&s!==3e3)return s},Dy=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},wc=class s{constructor(e){this.subscription=new se.Subscription;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(ky)||(e.useBrowserEstimation?$y():void 0)||q$,i=(a=(r=s.load(Ly))!=null?r:e.useBrowserEstimation?My():void 0)!=null?a:0;if(this.throughput$=new se.ValueSubject(t),this.rtt$=new se.ValueSubject(i),this.rttAdjustedThroughput$=new se.ValueSubject(Dy(t,i,e.rttPenaltyRequestSize)),this.throughput=Xt.getSmoothedValue(t,-1,e),this.rtt=Xt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=$y();u&&this.throughput.next(u);let l=My();(0,se.isNonNullable)(l)&&this.rtt.next(l)};Zt&&"onchange"in Zt&&this.subscription.add((0,se.fromEvent)(Zt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{se.safeStorage.set(ky,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{se.safeStorage.set(Ly,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,se.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,se.map)(({throughput:n,rtt:o})=>Dy(n,o,e.rttPenaltyRequestSize)),(0,se.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,se.now)(),r=new se.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,se.fromEvent)(e,"progress").pipe((0,se.once)()).subscribe(a=>{t=a.loaded,i=(0,se.now)()}));break;case 1:case 0:r.add((0,se.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,se.now)()}));break}r.add((0,se.fromEvent)(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=(0,se.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,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,a=(0,se.now)(),n=0,o=(0,se.now)(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=f=>R(this,[f],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(r,(0,se.now)()-a,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,se.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-a;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,a=(0,se.now)()}else n+=d.byteLength;o=(0,se.now)()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,se.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,se.now)()-o,this.concurrentDownloads.size),n=0,o=(0,se.now)());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*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=se.safeStorage.get(e);if((0,se.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},Cy=wc;var Yi=require("@vkontakte/videoplayer-shared/es2015");var By={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{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:Yi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Yi.VideoQuality.Q_720P,trafficSavingLimit:Yi.VideoQuality.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,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:Yi.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,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1},dashCmafLive:{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",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,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},Vy=s=>{var e;return j(C({},(0,Yi.fillWithDefault)(s,By)),{configName:[...(e=s.configName)!=null?e:[],...By.configName]})};var m=require("@vkontakte/videoplayer-shared/es2015");var ei=require("@vkontakte/videoplayer-shared/es2015"),Ac=({seekState:s,position$:e})=>(0,ei.merge)(s.stateChangeEnded$.pipe((0,ei.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,ei.filter)(ei.isNonNullable)),e.pipe((0,ei.filter)(()=>s.getState().state==="none")));var _y=require("@vkontakte/videoplayer-shared/es2015"),Oy=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return(0,_y.assertNonNullable)(e,`Wrong container or containerId {${s.container}}`),e};var Eo=require("@vkontakte/videoplayer-shared/es2015"),Fy=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,Eo.filter)(r=>r.length>0),(0,Eo.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Ta=class{constructor(e={configName:[]},t=m.TracerFactory.createRootTracer(!1)){this.subscription=new m.Subscription;this.logger=new m.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new m.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new m.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 m.ValueSubject(void 0),position$:new m.ValueSubject(0),duration$:new m.ValueSubject(1/0),muted$:new m.ValueSubject(!1),volume$:new m.ValueSubject(1),availableVideoStreams$:new m.ValueSubject([]),currentVideoStream$:new m.ValueSubject(void 0),availableQualities$:new m.ValueSubject([]),availableQualitiesFps$:new m.ValueSubject({}),currentQuality$:new m.ValueSubject(void 0),isAutoQualityEnabled$:new m.ValueSubject(!0),autoQualityLimitingAvailable$:new m.ValueSubject(!1),autoQualityLimits$:new m.ValueSubject({}),predefinedQualityLimitType$:new m.ValueSubject("unknown"),availableAudioStreams$:new m.ValueSubject([]),currentAudioStream$:new m.ValueSubject(void 0),availableAudioTracks$:new m.ValueSubject([]),isAudioAvailable$:new m.ValueSubject(!0),currentPlaybackRate$:new m.ValueSubject(1),currentBuffer$:new m.ValueSubject({start:0,end:0}),isBuffering$:new m.ValueSubject(!0),isStalled$:new m.ValueSubject(!1),isEnded$:new m.ValueSubject(!1),isLooped$:new m.ValueSubject(!1),isLive$:new m.ValueSubject(void 0),isLiveEnded$:new m.ValueSubject(null),canPlayLiveTailBuffer$:new m.ValueSubject(!1),canChangePlaybackSpeed$:new m.ValueSubject(void 0),atLiveEdge$:new m.ValueSubject(void 0),atLiveDurationEdge$:new m.ValueSubject(void 0),liveTime$:new m.ValueSubject(void 0),liveBufferTime$:new m.ValueSubject(void 0),liveLatency$:new m.ValueSubject(void 0),currentFormat$:new m.ValueSubject(void 0),availableTextTracks$:new m.ValueSubject([]),currentTextTrack$:new m.ValueSubject(void 0),throughputEstimation$:new m.ValueSubject(void 0),rttEstimation$:new m.ValueSubject(void 0),videoBitrate$:new m.ValueSubject(void 0),hostname$:new m.ValueSubject(void 0),httpConnectionType$:new m.ValueSubject(void 0),httpConnectionReused$:new m.ValueSubject(void 0),surface$:new m.ValueSubject("none"),chromecastState$:new m.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new m.ValueSubject(void 0),intrinsicVideoSize$:new m.ValueSubject(void 0),availableSources$:new m.ValueSubject(void 0),is3DVideo$:new m.ValueSubject(!1),currentVideoSegmentLength$:new m.ValueSubject(0),currentAudioSegmentLength$:new m.ValueSubject(0)};this.events={inited$:new m.Subject,ready$:new m.Subject,started$:new m.Subject,playing$:new m.Subject,paused$:new m.Subject,stopped$:new m.Subject,willReady$:new m.Subject,willStart$:new m.Subject,willResume$:new m.Subject,willPause$:new m.Subject,willStop$:new m.Subject,willDestruct$:new m.Subject,watchCoverageRecord$:new m.Subject,watchCoverageLive$:new m.Subject,managedError$:new m.Subject,fatalError$:new m.Subject,fetcherRecoverableError$:new m.Subject,ended$:new m.Subject,looped$:new m.Subject,seeked$:new m.Subject,willSeek$:new m.Subject,autoplaySoundProhibited$:new m.Subject,manifestRequested$:new m.Subject,manifestReceived$:new m.Subject,firstBytesRequested$:new m.Subject,firstBytesReceived$:new m.Subject,firstBytes$:new m.Subject,loadedMetadata$:new m.Subject,firstFrame$:new m.Subject,canplay$:new m.Subject,log$:new m.Subject,fetcherError$:new m.Subject,severeStallOccured$:new m.Subject};this.experimental={element$:new m.ValueSubject(void 0),tuningConfigName$:new m.ValueSubject([]),enableDebugTelemetry$:new m.ValueSubject(!1),dumpTelemetry:Dg,getCurrentTime$:new m.ValueSubject(null)};if(this.initLogs(),this.tuning=Vy(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,Pc.default)(this.info).forEach(i=>i.setSuppressErrors(!0)),(0,Pc.default)(this.events).forEach(i=>i.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Qa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Cy(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new m.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(f=>JSON.stringify(f,(p,h)=>{let b=typeof h;return(0,Ny.default)(["number","string","boolean"],b)?h:h===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:m.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var l,c,d;let u=e,{container:n}=u,o=fd(u,["container"]);this.tracer.log("initVideo",(0,m.flattenObject)(o)),this.domContainer=Oy(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new ya({sources:e.sources,meta:(c=e.meta)!=null?c:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],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)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?K.isInited$.pipe((0,m.filter)(n=>!!n),(0,m.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,m.fromEvent)(document,"visibilitychange").pipe((0,m.once)()).subscribe(r)):r(),this}destroy(){var e,t;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()}prepare(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.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.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{(0,m.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,m.filter)(i=>i.length>0),(0,m.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",(0,m.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{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.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{var i;(0,m.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,m.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>C({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{var t;Fy(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.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",C({},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.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{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.subscription.add(this.playerInited.pipe((0,m.filter)(t=>!!t),(0,m.once)()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe((0,m.filter)(i=>!!i),(0,m.once)()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>e),(0,m.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe((0,m.filter)(e=>!!e),(0,m.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,m.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,m.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,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Cg(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.filter)(({from:e})=>e==="stopped"),(0,m.once)()).subscribe(()=>{this.initedAt=(0,m.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,m.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(j(C({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:m.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,m.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,m.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,m.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,m.map)(n=>n.destination),(0,m.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,m.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,m.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,m.isInvariantQuality)(u)?1:(0,m.isInvariantQuality)(l)?-1:(0,m.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,m.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,m.filter)(n=>(0,m.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,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,m.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,m.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,m.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,m.combine)({hasLiveOffsetByPaused:(0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(n=>n.to),(0,m.filterChanged)(),(0,m.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,m.combine)({atLiveEdge:(0,m.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ac({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,m.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,m.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,m.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,m.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.muted),(0,m.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.volume),(0,m.filterChanged)()).subscribe(this.info.volume$)).add(Ac({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,m.merge)(e.providerOutput.endedEvent$.pipe((0,m.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,m.mapTo)(!1))).pipe((0,m.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,m.map)(n=>({id:n?`No${n}`:"NoProviders",category:m.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,m.once)()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe((0,m.once)()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe((0,m.once)()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe((0,m.once)()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe((0,m.once)(),(0,m.map)(n=>n!=null?n:(0,m.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.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 m.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new m.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.filter)(({to:n})=>n==="playing"),(0,m.once)()).subscribe(()=>i.next(!1)));let r=0,a=(0,m.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,m.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,m.filterChanged)());this.subscription.add(a.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,m.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,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,m.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(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,m.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 m.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,m.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,m.filter)(i=>i.length>0),(0,m.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:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Bt(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,m.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,m.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,m.assertNonNullable)(this.providerContainer),(0,m.assertNonNullable)(e),Mg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>$g(i)),this.providerContainer.current$.subscribe(({type:i})=>Ts("provider",i)),e.duration$.subscribe(i=>Ts("duration",i)),e.availableVideoTracks$.pipe((0,m.filter)(i=>!!i.length),(0,m.once)()).subscribe(i=>Ts("tracks",i)),this.events.fatalError$.subscribe(new Qe("fatalError")),this.events.managedError$.subscribe(new Qe("managedError")),e.position$.subscribe(new Qe("position")),e.currentVideoTrack$.pipe((0,m.map)(i=>i==null?void 0:i.quality)).subscribe(new Qe("quality")),this.info.currentBuffer$.subscribe(new Qe("buffer")),e.isBuffering$.subscribe(new Qe("isBuffering"))].forEach(i=>this.subscription.add(i)),Ts("codecs",K.video.supportedCodecs)}initTracerSubscription(){let e=(0,m.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,m.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,m.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,m.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,m.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,m.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,m.filter)(i=>i>0),(0,m.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,m.filter)(i=>i>0),(0,m.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,m.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,m.filter)(i=>i.end>0),(0,m.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,m.filterChanged)())}).pipe((0,m.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,m.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,m.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,m.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,m.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,m.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,m.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,m.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,m.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,m.filterChanged)(),(0,m.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,m.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,m.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,m.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,m.filterChanged)(),(0,m.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=()=>R(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:m.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,m.merge)((0,m.fromEvent)(document,"visibilitychange"),(0,m.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?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,m.flattenObject)({quality:t,availableTracks:(0,m.flattenObject)(e),track:(0,m.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&&!Ps()}};var Nt=require("@vkontakte/videoplayer-shared/es2015"),U$=`@vkontakte/videoplayer-core@${Lo}`;
|