@vkontakte/videoplayer-core 2.0.151-beta.0 → 2.0.151-beta.1
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 +4 -4
- package/es2015.esm.js +4 -4
- package/es2018.cjs +4 -4
- package/es2018.esm.js +4 -4
- package/es2024.cjs +4 -4
- package/es2024.esm.js +4 -4
- package/esnext.cjs +4 -4
- package/esnext.esm.js +4 -4
- package/evergreen.esm.js +3 -3
- package/package.json +2 -2
package/es2018.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.151-beta.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.151-beta.1
|
|
3
|
+
* Mon, 09 Feb 2026 16:47:21 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-151/doc/
|
|
5
5
|
*/
|
|
6
6
|
"use strict";var ST=Object.create;var en=Object.defineProperty;var yT=Object.getOwnPropertyDescriptor;var TT=Object.getOwnPropertyNames;var IT=Object.getPrototypeOf,ET=Object.prototype.hasOwnProperty;var g=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),wT=(s,e)=>{for(var t in e)en(s,t,{get:e[t],enumerable:!0})},_d=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of TT(e))!ET.call(s,r)&&r!==t&&en(s,r,{get:()=>e[r],enumerable:!(i=yT(e,r))||i.enumerable});return s};var G=(s,e,t)=>(t=s!=null?ST(IT(s)):{},_d(e||!s||!s.__esModule?en(t,"default",{value:s,enumerable:!0}):t,s)),xT=s=>_d(en({},"__esModule",{value:!0}),s);var Pe=g((eu,Od)=>{"use strict";var na=function(s){return s&&s.Math===Math&&s};Od.exports=na(typeof globalThis=="object"&&globalThis)||na(typeof window=="object"&&window)||na(typeof self=="object"&&self)||na(typeof global=="object"&&global)||na(typeof eu=="object"&&eu)||function(){return this}()||Function("return this")()});var Ce=g((SL,Nd)=>{"use strict";Nd.exports=function(s){try{return!!s()}catch(e){return!0}}});var oa=g((yL,Fd)=>{"use strict";var PT=Ce();Fd.exports=!PT(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var tu=g((TL,Hd)=>{"use strict";var kT=oa(),jd=Function.prototype,Ud=jd.apply,qd=jd.call;Hd.exports=typeof Reflect=="object"&&Reflect.apply||(kT?qd.bind(Ud):function(){return qd.apply(Ud,arguments)})});var De=g((IL,zd)=>{"use strict";var Wd=oa(),Qd=Function.prototype,iu=Qd.call,AT=Wd&&Qd.bind.bind(iu,iu);zd.exports=Wd?AT:function(s){return function(){return iu.apply(s,arguments)}}});var Ni=g((EL,Yd)=>{"use strict";var Gd=De(),RT=Gd({}.toString),MT=Gd("".slice);Yd.exports=function(s){return MT(RT(s),8,-1)}});var ru=g((wL,Kd)=>{"use strict";var $T=Ni(),LT=De();Kd.exports=function(s){if($T(s)==="Function")return LT(s)}});var ke=g((xL,Xd)=>{"use strict";var au=typeof document=="object"&&document.all;Xd.exports=typeof au=="undefined"&&au!==void 0?function(s){return typeof s=="function"||s===au}:function(s){return typeof s=="function"}});var nt=g((PL,Jd)=>{"use strict";var CT=Ce();Jd.exports=!CT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ot=g((kL,Zd)=>{"use strict";var DT=oa(),an=Function.prototype.call;Zd.exports=DT?an.bind(an):function(){return an.apply(an,arguments)}});var su=g(ip=>{"use strict";var ep={}.propertyIsEnumerable,tp=Object.getOwnPropertyDescriptor,BT=tp&&!ep.call({1:2},1);ip.f=BT?function(e){var t=tp(this,e);return!!t&&t.enumerable}:ep});var ua=g((RL,rp)=>{"use strict";rp.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var sp=g((ML,ap)=>{"use strict";var VT=De(),_T=Ce(),OT=Ni(),nu=Object,NT=VT("".split);ap.exports=_T(function(){return!nu("z").propertyIsEnumerable(0)})?function(s){return OT(s)==="String"?NT(s,""):nu(s)}:nu});var ca=g(($L,np)=>{"use strict";np.exports=function(s){return s==null}});var di=g((LL,op)=>{"use strict";var FT=ca(),UT=TypeError;op.exports=function(s){if(FT(s))throw new UT("Can't call method on "+s);return s}});var Fi=g((CL,up)=>{"use strict";var qT=sp(),jT=di();up.exports=function(s){return qT(jT(s))}});var Ke=g((DL,cp)=>{"use strict";var HT=ke();cp.exports=function(s){return typeof s=="object"?s!==null:HT(s)}});var Ui=g((BL,lp)=>{"use strict";lp.exports={}});var zt=g((VL,pp)=>{"use strict";var ou=Ui(),uu=Pe(),WT=ke(),dp=function(s){return WT(s)?s:void 0};pp.exports=function(s,e){return arguments.length<2?dp(ou[s])||dp(uu[s]):ou[s]&&ou[s][e]||uu[s]&&uu[s][e]}});var la=g((_L,hp)=>{"use strict";var QT=De();hp.exports=QT({}.isPrototypeOf)});var qi=g((OL,bp)=>{"use strict";var zT=Pe(),fp=zT.navigator,mp=fp&&fp.userAgent;bp.exports=mp?String(mp):""});var lu=g((NL,Ip)=>{"use strict";var Tp=Pe(),cu=qi(),gp=Tp.process,vp=Tp.Deno,Sp=gp&&gp.versions||vp&&vp.version,yp=Sp&&Sp.v8,Et,sn;yp&&(Et=yp.split("."),sn=Et[0]>0&&Et[0]<4?1:+(Et[0]+Et[1]));!sn&&cu&&(Et=cu.match(/Edge\/(\d+)/),(!Et||Et[1]>=74)&&(Et=cu.match(/Chrome\/(\d+)/),Et&&(sn=+Et[1])));Ip.exports=sn});var du=g((FL,wp)=>{"use strict";var Ep=lu(),GT=Ce(),YT=Pe(),KT=YT.String;wp.exports=!!Object.getOwnPropertySymbols&&!GT(function(){var s=Symbol("symbol detection");return!KT(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ep&&Ep<41})});var pu=g((UL,xp)=>{"use strict";var XT=du();xp.exports=XT&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var hu=g((qL,Pp)=>{"use strict";var JT=zt(),ZT=ke(),eI=la(),tI=pu(),iI=Object;Pp.exports=tI?function(s){return typeof s=="symbol"}:function(s){var e=JT("Symbol");return ZT(e)&&eI(e.prototype,iI(s))}});var da=g((jL,kp)=>{"use strict";var rI=String;kp.exports=function(s){try{return rI(s)}catch(e){return"Object"}}});var Bt=g((HL,Ap)=>{"use strict";var aI=ke(),sI=da(),nI=TypeError;Ap.exports=function(s){if(aI(s))return s;throw new nI(sI(s)+" is not a function")}});var pa=g((WL,Rp)=>{"use strict";var oI=Bt(),uI=ca();Rp.exports=function(s,e){var t=s[e];return uI(t)?void 0:oI(t)}});var $p=g((QL,Mp)=>{"use strict";var fu=ot(),mu=ke(),bu=Ke(),cI=TypeError;Mp.exports=function(s,e){var t,i;if(e==="string"&&mu(t=s.toString)&&!bu(i=fu(t,s))||mu(t=s.valueOf)&&!bu(i=fu(t,s))||e!=="string"&&mu(t=s.toString)&&!bu(i=fu(t,s)))return i;throw new cI("Can't convert object to primitive value")}});var wt=g((zL,Lp)=>{"use strict";Lp.exports=!0});var Bp=g((GL,Dp)=>{"use strict";var Cp=Pe(),lI=Object.defineProperty;Dp.exports=function(s,e){try{lI(Cp,s,{value:e,configurable:!0,writable:!0})}catch(t){Cp[s]=e}return e}});var ha=g((YL,Op)=>{"use strict";var dI=wt(),pI=Pe(),hI=Bp(),Vp="__core-js_shared__",_p=Op.exports=pI[Vp]||hI(Vp,{});(_p.versions||(_p.versions=[])).push({version:"3.43.0",mode:dI?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var gu=g((KL,Fp)=>{"use strict";var Np=ha();Fp.exports=function(s,e){return Np[s]||(Np[s]=e||{})}});var vr=g((XL,Up)=>{"use strict";var fI=di(),mI=Object;Up.exports=function(s){return mI(fI(s))}});var xt=g((JL,qp)=>{"use strict";var bI=De(),gI=vr(),vI=bI({}.hasOwnProperty);qp.exports=Object.hasOwn||function(e,t){return vI(gI(e),t)}});var vu=g((ZL,jp)=>{"use strict";var SI=De(),yI=0,TI=Math.random(),II=SI(1.1.toString);jp.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+II(++yI+TI,36)}});var je=g((eC,Wp)=>{"use strict";var EI=Pe(),wI=gu(),Hp=xt(),xI=vu(),PI=du(),kI=pu(),Sr=EI.Symbol,Su=wI("wks"),AI=kI?Sr.for||Sr:Sr&&Sr.withoutSetter||xI;Wp.exports=function(s){return Hp(Su,s)||(Su[s]=PI&&Hp(Sr,s)?Sr[s]:AI("Symbol."+s)),Su[s]}});var Yp=g((tC,Gp)=>{"use strict";var RI=ot(),Qp=Ke(),zp=hu(),MI=pa(),$I=$p(),LI=je(),CI=TypeError,DI=LI("toPrimitive");Gp.exports=function(s,e){if(!Qp(s)||zp(s))return s;var t=MI(s,DI),i;if(t){if(e===void 0&&(e="default"),i=RI(t,s,e),!Qp(i)||zp(i))return i;throw new CI("Can't convert object to primitive value")}return e===void 0&&(e="number"),$I(s,e)}});var yu=g((iC,Kp)=>{"use strict";var BI=Yp(),VI=hu();Kp.exports=function(s){var e=BI(s,"string");return VI(e)?e:e+""}});var nn=g((rC,Jp)=>{"use strict";var _I=Pe(),Xp=Ke(),Tu=_I.document,OI=Xp(Tu)&&Xp(Tu.createElement);Jp.exports=function(s){return OI?Tu.createElement(s):{}}});var Iu=g((aC,Zp)=>{"use strict";var NI=nt(),FI=Ce(),UI=nn();Zp.exports=!NI&&!FI(function(){return Object.defineProperty(UI("div"),"a",{get:function(){return 7}}).a!==7})});var ih=g(th=>{"use strict";var qI=nt(),jI=ot(),HI=su(),WI=ua(),QI=Fi(),zI=yu(),GI=xt(),YI=Iu(),eh=Object.getOwnPropertyDescriptor;th.f=qI?eh:function(e,t){if(e=QI(e),t=zI(t),YI)try{return eh(e,t)}catch(i){}if(GI(e,t))return WI(!jI(HI.f,e,t),e[t])}});var Eu=g((nC,rh)=>{"use strict";var KI=Ce(),XI=ke(),JI=/#|\.prototype\./,fa=function(s,e){var t=eE[ZI(s)];return t===iE?!0:t===tE?!1:XI(e)?KI(e):!!e},ZI=fa.normalize=function(s){return String(s).replace(JI,".").toLowerCase()},eE=fa.data={},tE=fa.NATIVE="N",iE=fa.POLYFILL="P";rh.exports=fa});var yr=g((oC,sh)=>{"use strict";var ah=ru(),rE=Bt(),aE=oa(),sE=ah(ah.bind);sh.exports=function(s,e){return rE(s),e===void 0?s:aE?sE(s,e):function(){return s.apply(e,arguments)}}});var wu=g((uC,nh)=>{"use strict";var nE=nt(),oE=Ce();nh.exports=nE&&oE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Vt=g((cC,oh)=>{"use strict";var uE=Ke(),cE=String,lE=TypeError;oh.exports=function(s){if(uE(s))return s;throw new lE(cE(s)+" is not an object")}});var ji=g(ch=>{"use strict";var dE=nt(),pE=Iu(),hE=wu(),on=Vt(),uh=yu(),fE=TypeError,xu=Object.defineProperty,mE=Object.getOwnPropertyDescriptor,Pu="enumerable",ku="configurable",Au="writable";ch.f=dE?hE?function(e,t,i){if(on(e),t=uh(t),on(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Au in i&&!i[Au]){var r=mE(e,t);r&&r[Au]&&(e[t]=i.value,i={configurable:ku in i?i[ku]:r[ku],enumerable:Pu in i?i[Pu]:r[Pu],writable:!1})}return xu(e,t,i)}:xu:function(e,t,i){if(on(e),t=uh(t),on(i),pE)try{return xu(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new fE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Tr=g((dC,lh)=>{"use strict";var bE=nt(),gE=ji(),vE=ua();lh.exports=bE?function(s,e,t){return gE.f(s,e,vE(1,t))}:function(s,e,t){return s[e]=t,s}});var Me=g((pC,ph)=>{"use strict";var ma=Pe(),SE=tu(),yE=ru(),TE=ke(),IE=ih().f,EE=Eu(),Ir=Ui(),wE=yr(),Er=Tr(),dh=xt();ha();var xE=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 SE(s,this,arguments)};return e.prototype=s.prototype,e};ph.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ma:r?ma[t]:ma[t]&&ma[t].prototype,o=i?Ir:Ir[t]||Er(Ir,t,{})[t],u=o.prototype,c,d,l,p,h,m,b,S,v;for(p in e)c=EE(i?p:t+(r?".":"#")+p,s.forced),d=!c&&n&&dh(n,p),m=o[p],d&&(s.dontCallGetSet?(v=IE(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!c&&!a&&typeof m==typeof h)&&(s.bind&&d?S=wE(h,ma):s.wrap&&d?S=xE(h):a&&TE(h)?S=yE(h):S=h,(s.sham||h&&h.sham||m&&m.sham)&&Er(S,"sham",!0),Er(o,p,S),a&&(l=t+"Prototype",dh(Ir,l)||Er(Ir,l,{}),Er(Ir[l],p,h),s.real&&u&&(c||!u[p])&&Er(u,p,h)))}});var un=g((hC,fh)=>{"use strict";var PE=gu(),kE=vu(),hh=PE("keys");fh.exports=function(s){return hh[s]||(hh[s]=kE(s))}});var bh=g((fC,mh)=>{"use strict";var AE=Ce();mh.exports=!AE(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var cn=g((mC,vh)=>{"use strict";var RE=xt(),ME=ke(),$E=vr(),LE=un(),CE=bh(),gh=LE("IE_PROTO"),Ru=Object,DE=Ru.prototype;vh.exports=CE?Ru.getPrototypeOf:function(s){var e=$E(s);if(RE(e,gh))return e[gh];var t=e.constructor;return ME(t)&&e instanceof t?t.prototype:e instanceof Ru?DE:null}});var yh=g((bC,Sh)=>{"use strict";var BE=Math.ceil,VE=Math.floor;Sh.exports=Math.trunc||function(e){var t=+e;return(t>0?VE:BE)(t)}});var ba=g((gC,Th)=>{"use strict";var _E=yh();Th.exports=function(s){var e=+s;return e!==e||e===0?0:_E(e)}});var Eh=g((vC,Ih)=>{"use strict";var OE=ba(),NE=Math.max,FE=Math.min;Ih.exports=function(s,e){var t=OE(s);return t<0?NE(t+e,0):FE(t,e)}});var Mu=g((SC,wh)=>{"use strict";var UE=ba(),qE=Math.min;wh.exports=function(s){var e=UE(s);return e>0?qE(e,9007199254740991):0}});var wr=g((yC,xh)=>{"use strict";var jE=Mu();xh.exports=function(s){return jE(s.length)}});var $u=g((TC,kh)=>{"use strict";var HE=Fi(),WE=Eh(),QE=wr(),Ph=function(s){return function(e,t,i){var r=HE(e),a=QE(r);if(a===0)return!s&&-1;var n=WE(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}};kh.exports={includes:Ph(!0),indexOf:Ph(!1)}});var ln=g((IC,Ah)=>{"use strict";Ah.exports={}});var $h=g((EC,Mh)=>{"use strict";var zE=De(),Lu=xt(),GE=Fi(),YE=$u().indexOf,KE=ln(),Rh=zE([].push);Mh.exports=function(s,e){var t=GE(s),i=0,r=[],a;for(a in t)!Lu(KE,a)&&Lu(t,a)&&Rh(r,a);for(;e.length>i;)Lu(t,a=e[i++])&&(~YE(r,a)||Rh(r,a));return r}});var Cu=g((wC,Lh)=>{"use strict";Lh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Du=g((xC,Ch)=>{"use strict";var XE=$h(),JE=Cu();Ch.exports=Object.keys||function(e){return XE(e,JE)}});var Bu=g((PC,Oh)=>{"use strict";var Bh=nt(),ZE=Ce(),Vh=De(),ew=cn(),tw=Du(),iw=Fi(),rw=su().f,_h=Vh(rw),aw=Vh([].push),sw=Bh&&ZE(function(){var s=Object.create(null);return s[2]=2,!_h(s,2)}),Dh=function(s){return function(e){for(var t=iw(e),i=tw(t),r=sw&&ew(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Bh||(r?u in t:_h(t,u)))&&aw(o,s?[u,t[u]]:t[u]);return o}};Oh.exports={entries:Dh(!0),values:Dh(!1)}});var Nh=g(()=>{"use strict";var nw=Me(),ow=Bu().values;nw({target:"Object",stat:!0},{values:function(e){return ow(e)}})});var Uh=g((RC,Fh)=>{"use strict";Nh();var uw=Ui();Fh.exports=uw.Object.values});var jh=g((MC,qh)=>{"use strict";var cw=Uh();qh.exports=cw});var Hi=g(($C,Hh)=>{"use strict";var lw=jh();Hh.exports=lw});var ga=g((LC,Wh)=>{"use strict";Wh.exports=function(){}});var Qh=g(()=>{"use strict";var dw=Me(),pw=$u().includes,hw=Ce(),fw=ga(),mw=hw(function(){return!Array(1).includes()});dw({target:"Array",proto:!0,forced:mw},{includes:function(e){return pw(this,e,arguments.length>1?arguments[1]:void 0)}});fw("includes")});var pi=g((BC,zh)=>{"use strict";var bw=zt();zh.exports=bw});var Yh=g((VC,Gh)=>{"use strict";Qh();var gw=pi();Gh.exports=gw("Array","includes")});var Xh=g((_C,Kh)=>{"use strict";var vw=Yh();Kh.exports=vw});var Xe=g((OC,Jh)=>{"use strict";var Sw=Xh();Jh.exports=Sw});var ff=g(()=>{"use strict";var Rw=Me(),Mw=Bu().entries;Rw({target:"Object",stat:!0},{entries:function(e){return Mw(e)}})});var bf=g((x0,mf)=>{"use strict";ff();var $w=Ui();mf.exports=$w.Object.entries});var vf=g((P0,gf)=>{"use strict";var Lw=bf();gf.exports=Lw});var bi=g((k0,Sf)=>{"use strict";var Cw=vf();Sf.exports=Cw});var Qi=g((A0,yf)=>{"use strict";yf.exports={}});var Ef=g((R0,If)=>{"use strict";var Dw=Pe(),Bw=ke(),Tf=Dw.WeakMap;If.exports=Bw(Tf)&&/native code/.test(String(Tf))});var ju=g((M0,Pf)=>{"use strict";var Vw=Ef(),xf=Pe(),_w=Ke(),Ow=Tr(),Fu=xt(),Uu=ha(),Nw=un(),Fw=ln(),wf="Object already initialized",qu=xf.TypeError,Uw=xf.WeakMap,En,Ia,wn,qw=function(s){return wn(s)?Ia(s):En(s,{})},jw=function(s){return function(e){var t;if(!_w(e)||(t=Ia(e)).type!==s)throw new qu("Incompatible receiver, "+s+" required");return t}};Vw||Uu.state?(Pt=Uu.state||(Uu.state=new Uw),Pt.get=Pt.get,Pt.has=Pt.has,Pt.set=Pt.set,En=function(s,e){if(Pt.has(s))throw new qu(wf);return e.facade=s,Pt.set(s,e),e},Ia=function(s){return Pt.get(s)||{}},wn=function(s){return Pt.has(s)}):(zi=Nw("state"),Fw[zi]=!0,En=function(s,e){if(Fu(s,zi))throw new qu(wf);return e.facade=s,Ow(s,zi,e),e},Ia=function(s){return Fu(s,zi)?s[zi]:{}},wn=function(s){return Fu(s,zi)});var Pt,zi;Pf.exports={set:En,get:Ia,has:wn,enforce:qw,getterFor:jw}});var Qu=g(($0,Af)=>{"use strict";var Hu=nt(),Hw=xt(),kf=Function.prototype,Ww=Hu&&Object.getOwnPropertyDescriptor,Wu=Hw(kf,"name"),Qw=Wu&&function(){}.name==="something",zw=Wu&&(!Hu||Hu&&Ww(kf,"name").configurable);Af.exports={EXISTS:Wu,PROPER:Qw,CONFIGURABLE:zw}});var Mf=g(Rf=>{"use strict";var Gw=nt(),Yw=wu(),Kw=ji(),Xw=Vt(),Jw=Fi(),Zw=Du();Rf.f=Gw&&!Yw?Object.defineProperties:function(e,t){Xw(e);for(var i=Jw(t),r=Zw(t),a=r.length,n=0,o;a>n;)Kw.f(e,o=r[n++],i[o]);return e}});var zu=g((C0,$f)=>{"use strict";var ex=zt();$f.exports=ex("document","documentElement")});var Xu=g((D0,Of)=>{"use strict";var tx=Vt(),ix=Mf(),Lf=Cu(),rx=ln(),ax=zu(),sx=nn(),nx=un(),Cf=">",Df="<",Yu="prototype",Ku="script",Vf=nx("IE_PROTO"),Gu=function(){},_f=function(s){return Df+Ku+Cf+s+Df+"/"+Ku+Cf},Bf=function(s){s.write(_f("")),s.close();var e=s.parentWindow.Object;return s=null,e},ox=function(){var s=sx("iframe"),e="java"+Ku+":",t;return s.style.display="none",ax.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(_f("document.F=Object")),t.close(),t.F},xn,Pn=function(){try{xn=new ActiveXObject("htmlfile")}catch(e){}Pn=typeof document!="undefined"?document.domain&&xn?Bf(xn):ox():Bf(xn);for(var s=Lf.length;s--;)delete Pn[Yu][Lf[s]];return Pn()};rx[Vf]=!0;Of.exports=Object.create||function(e,t){var i;return e!==null?(Gu[Yu]=tx(e),i=new Gu,Gu[Yu]=null,i[Vf]=e):i=Pn(),t===void 0?i:ix.f(i,t)}});var Pr=g((B0,Nf)=>{"use strict";var ux=Tr();Nf.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:ux(s,e,t),s}});var tc=g((V0,qf)=>{"use strict";var cx=Ce(),lx=ke(),dx=Ke(),px=Xu(),Ff=cn(),hx=Pr(),fx=je(),mx=wt(),ec=fx("iterator"),Uf=!1,Yt,Ju,Zu;[].keys&&(Zu=[].keys(),"next"in Zu?(Ju=Ff(Ff(Zu)),Ju!==Object.prototype&&(Yt=Ju)):Uf=!0);var bx=!dx(Yt)||cx(function(){var s={};return Yt[ec].call(s)!==s});bx?Yt={}:mx&&(Yt=px(Yt));lx(Yt[ec])||hx(Yt,ec,function(){return this});qf.exports={IteratorPrototype:Yt,BUGGY_SAFARI_ITERATORS:Uf}});var kn=g((_0,Hf)=>{"use strict";var gx=je(),vx=gx("toStringTag"),jf={};jf[vx]="z";Hf.exports=String(jf)==="[object z]"});var Ea=g((O0,Wf)=>{"use strict";var Sx=kn(),yx=ke(),An=Ni(),Tx=je(),Ix=Tx("toStringTag"),Ex=Object,wx=An(function(){return arguments}())==="Arguments",xx=function(s,e){try{return s[e]}catch(t){}};Wf.exports=Sx?An:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=xx(e=Ex(s),Ix))=="string"?t:wx?An(e):(i=An(e))==="Object"&&yx(e.callee)?"Arguments":i}});var zf=g((N0,Qf)=>{"use strict";var Px=kn(),kx=Ea();Qf.exports=Px?{}.toString:function(){return"[object "+kx(this)+"]"}});var wa=g((F0,Yf)=>{"use strict";var Ax=kn(),Rx=ji().f,Mx=Tr(),$x=xt(),Lx=zf(),Cx=je(),Gf=Cx("toStringTag");Yf.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&($x(r,Gf)||Rx(r,Gf,{configurable:!0,value:e}),i&&!Ax&&Mx(r,"toString",Lx))}});var Xf=g((U0,Kf)=>{"use strict";var Dx=tc().IteratorPrototype,Bx=Xu(),Vx=ua(),_x=wa(),Ox=Qi(),Nx=function(){return this};Kf.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Bx(Dx,{next:Vx(+!i,t)}),_x(s,r,!1,!0),Ox[r]=Nx,s}});var Zf=g((q0,Jf)=>{"use strict";var Fx=De(),Ux=Bt();Jf.exports=function(s,e,t){try{return Fx(Ux(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var tm=g((j0,em)=>{"use strict";var qx=Ke();em.exports=function(s){return qx(s)||s===null}});var rm=g((H0,im)=>{"use strict";var jx=tm(),Hx=String,Wx=TypeError;im.exports=function(s){if(jx(s))return s;throw new Wx("Can't set "+Hx(s)+" as a prototype")}});var ic=g((W0,am)=>{"use strict";var Qx=Zf(),zx=Ke(),Gx=di(),Yx=rm();am.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=Qx(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return Gx(r),Yx(a),zx(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var mm=g((Q0,fm)=>{"use strict";var Kx=Me(),Xx=ot(),Rn=wt(),pm=Qu(),Jx=ke(),Zx=Xf(),sm=cn(),nm=ic(),eP=wa(),tP=Tr(),rc=Pr(),iP=je(),om=Qi(),hm=tc(),rP=pm.PROPER,aP=pm.CONFIGURABLE,um=hm.IteratorPrototype,Mn=hm.BUGGY_SAFARI_ITERATORS,xa=iP("iterator"),cm="keys",Pa="values",lm="entries",dm=function(){return this};fm.exports=function(s,e,t,i,r,a,n){Zx(t,e,i);var o=function(v){if(v===r&&p)return p;if(!Mn&&v&&v in d)return d[v];switch(v){case cm:return function(){return new t(this,v)};case Pa:return function(){return new t(this,v)};case lm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,d=s.prototype,l=d[xa]||d["@@iterator"]||r&&d[r],p=!Mn&&l||o(r),h=e==="Array"&&d.entries||l,m,b,S;if(h&&(m=sm(h.call(new s)),m!==Object.prototype&&m.next&&(!Rn&&sm(m)!==um&&(nm?nm(m,um):Jx(m[xa])||rc(m,xa,dm)),eP(m,u,!0,!0),Rn&&(om[u]=dm))),rP&&r===Pa&&l&&l.name!==Pa&&(!Rn&&aP?tP(d,"name",Pa):(c=!0,p=function(){return Xx(l,this)})),r)if(b={values:o(Pa),keys:a?p:o(cm),entries:o(lm)},n)for(S in b)(Mn||c||!(S in d))&&rc(d,S,b[S]);else Kx({target:e,proto:!0,forced:Mn||c},b);return(!Rn||n)&&d[xa]!==p&&rc(d,xa,p,{name:r}),om[e]=p,b}});var gm=g((z0,bm)=>{"use strict";bm.exports=function(s,e){return{value:s,done:e}}});var sc=g((G0,Im)=>{"use strict";var sP=Fi(),ac=ga(),vm=Qi(),ym=ju(),nP=ji().f,oP=mm(),$n=gm(),uP=wt(),cP=nt(),Tm="Array Iterator",lP=ym.set,dP=ym.getterFor(Tm);Im.exports=oP(Array,"Array",function(s,e){lP(this,{type:Tm,target:sP(s),index:0,kind:e})},function(){var s=dP(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,$n(void 0,!0);switch(s.kind){case"keys":return $n(t,!1);case"values":return $n(e[t],!1)}return $n([t,e[t]],!1)},"values");var Sm=vm.Arguments=vm.Array;ac("keys");ac("values");ac("entries");if(!uP&&cP&&Sm.name!=="values")try{nP(Sm,"name",{value:"values"})}catch(s){}});var wm=g((Y0,Em)=>{"use strict";var pP=je(),hP=Qi(),fP=pP("iterator"),mP=Array.prototype;Em.exports=function(s){return s!==void 0&&(hP.Array===s||mP[fP]===s)}});var nc=g((K0,Pm)=>{"use strict";var bP=Ea(),xm=pa(),gP=ca(),vP=Qi(),SP=je(),yP=SP("iterator");Pm.exports=function(s){if(!gP(s))return xm(s,yP)||xm(s,"@@iterator")||vP[bP(s)]}});var Am=g((X0,km)=>{"use strict";var TP=ot(),IP=Bt(),EP=Vt(),wP=da(),xP=nc(),PP=TypeError;km.exports=function(s,e){var t=arguments.length<2?xP(s):e;if(IP(t))return EP(TP(t,s));throw new PP(wP(s)+" is not iterable")}});var $m=g((J0,Mm)=>{"use strict";var kP=ot(),Rm=Vt(),AP=pa();Mm.exports=function(s,e,t){var i,r;Rm(s);try{if(i=AP(s,"return"),!i){if(e==="throw")throw t;return t}i=kP(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Rm(i),t}});var Cn=g((Z0,Bm)=>{"use strict";var RP=yr(),MP=ot(),$P=Vt(),LP=da(),CP=wm(),DP=wr(),Lm=la(),BP=Am(),VP=nc(),Cm=$m(),_P=TypeError,Ln=function(s,e){this.stopped=s,this.result=e},Dm=Ln.prototype;Bm.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=RP(e,i),c,d,l,p,h,m,b,S=function(y){return c&&Cm(c,"normal"),new Ln(!0,y)},v=function(y){return r?($P(y),o?u(y[0],y[1],S):u(y[0],y[1])):o?u(y,S):u(y)};if(a)c=s.iterator;else if(n)c=s;else{if(d=VP(s),!d)throw new _P(LP(s)+" is not iterable");if(CP(d)){for(l=0,p=DP(s);p>l;l++)if(h=v(s[l]),h&&Lm(Dm,h))return h;return new Ln(!1)}c=BP(s,d)}for(m=a?s.next:c.next;!(b=MP(m,c)).done;){try{h=v(b.value)}catch(y){Cm(c,"throw",y)}if(typeof h=="object"&&h&&Lm(Dm,h))return h}return new Ln(!1)}});var _m=g((eB,Vm)=>{"use strict";var OP=nt(),NP=ji(),FP=ua();Vm.exports=function(s,e,t){OP?NP.f(s,e,FP(0,t)):s[e]=t}});var Om=g(()=>{"use strict";var UP=Me(),qP=Cn(),jP=_m();UP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return qP(e,function(i,r){jP(t,i,r)},{AS_ENTRIES:!0}),t}})});var Fm=g((rB,Nm)=>{"use strict";sc();Om();var HP=Ui();Nm.exports=HP.Object.fromEntries});var qm=g((aB,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 Hm=g(()=>{"use strict";sc();var WP=qm(),QP=Pe(),zP=wa(),jm=Qi();for(Dn in WP)zP(QP[Dn],Dn),jm[Dn]=jm.Array;var Dn});var Qm=g((oB,Wm)=>{"use strict";var GP=Fm();Hm();Wm.exports=GP});var oc=g((uB,zm)=>{"use strict";var YP=Qm();zm.exports=YP});var Gm=g(()=>{"use strict"});var uc=g((dB,Ym)=>{"use strict";var ka=Pe(),KP=qi(),XP=Ni(),Bn=function(s){return KP.slice(0,s.length)===s};Ym.exports=function(){return Bn("Bun/")?"BUN":Bn("Cloudflare-Workers")?"CLOUDFLARE":Bn("Deno/")?"DENO":Bn("Node.js/")?"NODE":ka.Bun&&typeof Bun.version=="string"?"BUN":ka.Deno&&typeof Deno.version=="object"?"DENO":XP(ka.process)==="process"?"NODE":ka.window&&ka.document?"BROWSER":"REST"}()});var Vn=g((pB,Km)=>{"use strict";var JP=uc();Km.exports=JP==="NODE"});var Jm=g((hB,Xm)=>{"use strict";var ZP=ji();Xm.exports=function(s,e,t){return ZP.f(s,e,t)}});var tb=g((fB,eb)=>{"use strict";var ek=zt(),tk=Jm(),ik=je(),rk=nt(),Zm=ik("species");eb.exports=function(s){var e=ek(s);rk&&e&&!e[Zm]&&tk(e,Zm,{configurable:!0,get:function(){return this}})}});var rb=g((mB,ib)=>{"use strict";var ak=la(),sk=TypeError;ib.exports=function(s,e){if(ak(e,s))return s;throw new sk("Incorrect invocation")}});var lc=g((bB,ab)=>{"use strict";var nk=De(),ok=ke(),cc=ha(),uk=nk(Function.toString);ok(cc.inspectSource)||(cc.inspectSource=function(s){return uk(s)});ab.exports=cc.inspectSource});var pc=g((gB,cb)=>{"use strict";var ck=De(),lk=Ce(),sb=ke(),dk=Ea(),pk=zt(),hk=lc(),nb=function(){},ob=pk("Reflect","construct"),dc=/^\s*(?:class|function)\b/,fk=ck(dc.exec),mk=!dc.test(nb),Aa=function(e){if(!sb(e))return!1;try{return ob(nb,[],e),!0}catch(t){return!1}},ub=function(e){if(!sb(e))return!1;switch(dk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return mk||!!fk(dc,hk(e))}catch(t){return!0}};ub.sham=!0;cb.exports=!ob||lk(function(){var s;return Aa(Aa.call)||!Aa(Object)||!Aa(function(){s=!0})||s})?ub:Aa});var db=g((vB,lb)=>{"use strict";var bk=pc(),gk=da(),vk=TypeError;lb.exports=function(s){if(bk(s))return s;throw new vk(gk(s)+" is not a constructor")}});var hc=g((SB,hb)=>{"use strict";var pb=Vt(),Sk=db(),yk=ca(),Tk=je(),Ik=Tk("species");hb.exports=function(s,e){var t=pb(s).constructor,i;return t===void 0||yk(i=pb(t)[Ik])?e:Sk(i)}});var mb=g((yB,fb)=>{"use strict";var Ek=De();fb.exports=Ek([].slice)});var gb=g((TB,bb)=>{"use strict";var wk=TypeError;bb.exports=function(s,e){if(s<e)throw new wk("Not enough arguments");return s}});var fc=g((IB,vb)=>{"use strict";var xk=qi();vb.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(xk)});var Ec=g((EB,kb)=>{"use strict";var ct=Pe(),Pk=tu(),kk=yr(),Sb=ke(),Ak=xt(),Pb=Ce(),yb=zu(),Rk=mb(),Tb=nn(),Mk=gb(),$k=fc(),Lk=Vn(),yc=ct.setImmediate,Tc=ct.clearImmediate,Ck=ct.process,mc=ct.Dispatch,Dk=ct.Function,Ib=ct.MessageChannel,Bk=ct.String,bc=0,Ra={},Eb="onreadystatechange",Ma,Gi,gc,vc;Pb(function(){Ma=ct.location});var Ic=function(s){if(Ak(Ra,s)){var e=Ra[s];delete Ra[s],e()}},Sc=function(s){return function(){Ic(s)}},wb=function(s){Ic(s.data)},xb=function(s){ct.postMessage(Bk(s),Ma.protocol+"//"+Ma.host)};(!yc||!Tc)&&(yc=function(e){Mk(arguments.length,1);var t=Sb(e)?e:Dk(e),i=Rk(arguments,1);return Ra[++bc]=function(){Pk(t,void 0,i)},Gi(bc),bc},Tc=function(e){delete Ra[e]},Lk?Gi=function(s){Ck.nextTick(Sc(s))}:mc&&mc.now?Gi=function(s){mc.now(Sc(s))}:Ib&&!$k?(gc=new Ib,vc=gc.port2,gc.port1.onmessage=wb,Gi=kk(vc.postMessage,vc)):ct.addEventListener&&Sb(ct.postMessage)&&!ct.importScripts&&Ma&&Ma.protocol!=="file:"&&!Pb(xb)?(Gi=xb,ct.addEventListener("message",wb,!1)):Eb in Tb("script")?Gi=function(s){yb.appendChild(Tb("script"))[Eb]=function(){yb.removeChild(this),Ic(s)}}:Gi=function(s){setTimeout(Sc(s),0)});kb.exports={set:yc,clear:Tc}});var Mb=g((wB,Rb)=>{"use strict";var Ab=Pe(),Vk=nt(),_k=Object.getOwnPropertyDescriptor;Rb.exports=function(s){if(!Vk)return Ab[s];var e=_k(Ab,s);return e&&e.value}});var wc=g((xB,Lb)=>{"use strict";var $b=function(){this.head=null,this.tail=null};$b.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}}};Lb.exports=$b});var Db=g((PB,Cb)=>{"use strict";var Ok=qi();Cb.exports=/ipad|iphone|ipod/i.test(Ok)&&typeof Pebble!="undefined"});var Vb=g((kB,Bb)=>{"use strict";var Nk=qi();Bb.exports=/web0s(?!.*chrome)/i.test(Nk)});var jb=g((AB,qb)=>{"use strict";var Ar=Pe(),Fk=Mb(),_b=yr(),xc=Ec().set,Uk=wc(),qk=fc(),jk=Db(),Hk=Vb(),Pc=Vn(),Ob=Ar.MutationObserver||Ar.WebKitMutationObserver,Nb=Ar.document,Fb=Ar.process,_n=Ar.Promise,Rc=Fk("queueMicrotask"),kr,kc,Ac,On,Ub;Rc||($a=new Uk,La=function(){var s,e;for(Pc&&(s=Fb.domain)&&s.exit();e=$a.get();)try{e()}catch(t){throw $a.head&&kr(),t}s&&s.enter()},!qk&&!Pc&&!Hk&&Ob&&Nb?(kc=!0,Ac=Nb.createTextNode(""),new Ob(La).observe(Ac,{characterData:!0}),kr=function(){Ac.data=kc=!kc}):!jk&&_n&&_n.resolve?(On=_n.resolve(void 0),On.constructor=_n,Ub=_b(On.then,On),kr=function(){Ub(La)}):Pc?kr=function(){Fb.nextTick(La)}:(xc=_b(xc,Ar),kr=function(){xc(La)}),Rc=function(s){$a.head||kr(),$a.add(s)});var $a,La;qb.exports=Rc});var Wb=g((RB,Hb)=>{"use strict";Hb.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Nn=g((MB,Qb)=>{"use strict";Qb.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var Yi=g(($B,zb)=>{"use strict";var Wk=Pe();zb.exports=Wk.Promise});var Rr=g((LB,Xb)=>{"use strict";var Qk=Pe(),Ca=Yi(),zk=ke(),Gk=Eu(),Yk=lc(),Kk=je(),Gb=uc(),Xk=wt(),Mc=lu(),Yb=Ca&&Ca.prototype,Jk=Kk("species"),$c=!1,Kb=zk(Qk.PromiseRejectionEvent),Zk=Gk("Promise",function(){var s=Yk(Ca),e=s!==String(Ca);if(!e&&Mc===66||Xk&&!(Yb.catch&&Yb.finally))return!0;if(!Mc||Mc<51||!/native code/.test(s)){var t=new Ca(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Jk]=i,$c=t.then(function(){})instanceof i,!$c)return!0}return!e&&(Gb==="BROWSER"||Gb==="DENO")&&!Kb});Xb.exports={CONSTRUCTOR:Zk,REJECTION_EVENT:Kb,SUBCLASSING:$c}});var Mr=g((CB,Zb)=>{"use strict";var Jb=Bt(),eA=TypeError,tA=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new eA("Bad Promise constructor");e=i,t=r}),this.resolve=Jb(e),this.reject=Jb(t)};Zb.exports.f=function(s){return new tA(s)}});var Sg=g(()=>{"use strict";var iA=Me(),rA=wt(),jn=Vn(),gi=Pe(),aA=Ui(),Dr=ot(),eg=Pr(),tg=ic(),sA=wa(),nA=tb(),oA=Bt(),qn=ke(),uA=Ke(),cA=rb(),lA=hc(),ng=Ec().set,Vc=jb(),dA=Wb(),pA=Nn(),hA=wc(),og=ju(),Hn=Yi(),_c=Rr(),ug=Mr(),Wn="Promise",cg=_c.CONSTRUCTOR,fA=_c.REJECTION_EVENT,mA=_c.SUBCLASSING,Lc=og.getterFor(Wn),bA=og.set,$r=Hn&&Hn.prototype,Ki=Hn,Fn=$r,lg=gi.TypeError,Cc=gi.document,Oc=gi.process,Dc=ug.f,gA=Dc,vA=!!(Cc&&Cc.createEvent&&gi.dispatchEvent),dg="unhandledrejection",SA="rejectionhandled",ig=0,pg=1,yA=2,Nc=1,hg=2,Un,rg,fg,ag,mg=function(s){var e;return uA(s)&&qn(e=s.then)?e:!1},bg=function(s,e){var t=e.value,i=e.state===pg,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,c,d;try{r?(i||(e.rejection===hg&&IA(e),e.rejection=Nc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new lg("Promise-chain cycle")):(c=mg(u))?Dr(c,u,a,n):a(u)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},gg=function(s,e){s.notified||(s.notified=!0,Vc(function(){for(var t=s.reactions,i;i=t.get();)bg(i,s);s.notified=!1,e&&!s.rejection&&TA(s)}))},vg=function(s,e,t){var i,r;vA?(i=Cc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),gi.dispatchEvent(i)):i={promise:e,reason:t},!fA&&(r=gi["on"+s])?r(i):s===dg&&dA("Unhandled promise rejection",t)},TA=function(s){Dr(ng,gi,function(){var e=s.facade,t=s.value,i=sg(s),r;if(i&&(r=pA(function(){jn?Oc.emit("unhandledRejection",t,e):vg(dg,e,t)}),s.rejection=jn||sg(s)?hg:Nc,r.error))throw r.value})},sg=function(s){return s.rejection!==Nc&&!s.parent},IA=function(s){Dr(ng,gi,function(){var e=s.facade;jn?Oc.emit("rejectionHandled",e):vg(SA,e,s.value)})},Lr=function(s,e,t){return function(i){s(e,i,t)}},Cr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=yA,gg(s,!0))},Bc=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new lg("Promise can't be resolved itself");var i=mg(e);i?Vc(function(){var r={done:!1};try{Dr(i,e,Lr(Bc,r,s),Lr(Cr,r,s))}catch(a){Cr(r,a,s)}}):(s.value=e,s.state=pg,gg(s,!1))}catch(r){Cr({done:!1},r,s)}}};if(cg&&(Ki=function(e){cA(this,Fn),oA(e),Dr(Un,this);var t=Lc(this);try{e(Lr(Bc,t),Lr(Cr,t))}catch(i){Cr(t,i)}},Fn=Ki.prototype,Un=function(e){bA(this,{type:Wn,done:!1,notified:!1,parent:!1,reactions:new hA,rejection:!1,state:ig,value:null})},Un.prototype=eg(Fn,"then",function(e,t){var i=Lc(this),r=Dc(lA(this,Ki));return i.parent=!0,r.ok=qn(e)?e:!0,r.fail=qn(t)&&t,r.domain=jn?Oc.domain:void 0,i.state===ig?i.reactions.add(r):Vc(function(){bg(r,i)}),r.promise}),rg=function(){var s=new Un,e=Lc(s);this.promise=s,this.resolve=Lr(Bc,e),this.reject=Lr(Cr,e)},ug.f=Dc=function(s){return s===Ki||s===fg?new rg(s):gA(s)},!rA&&qn(Hn)&&$r!==Object.prototype)){ag=$r.then,mA||eg($r,"then",function(e,t){var i=this;return new Ki(function(r,a){Dr(ag,i,r,a)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch(s){}tg&&tg($r,Fn)}iA({global:!0,constructor:!0,wrap:!0,forced:cg},{Promise:Ki});fg=aA.Promise;sA(Ki,Wn,!1,!0);nA(Wn)});var wg=g((VB,Eg)=>{"use strict";var EA=je(),Tg=EA("iterator"),Ig=!1;try{yg=0,Fc={next:function(){return{done:!!yg++}},return:function(){Ig=!0}},Fc[Tg]=function(){return this},Array.from(Fc,function(){throw 2})}catch(s){}var yg,Fc;Eg.exports=function(s,e){try{if(!e&&!Ig)return!1}catch(r){return!1}var t=!1;try{var i={};i[Tg]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Uc=g((_B,xg)=>{"use strict";var wA=Yi(),xA=wg(),PA=Rr().CONSTRUCTOR;xg.exports=PA||!xA(function(s){wA.all(s).then(void 0,function(){})})});var Pg=g(()=>{"use strict";var kA=Me(),AA=ot(),RA=Bt(),MA=Mr(),$A=Nn(),LA=Cn(),CA=Uc();kA({target:"Promise",stat:!0,forced:CA},{all:function(e){var t=this,i=MA.f(t),r=i.resolve,a=i.reject,n=$A(function(){var o=RA(t.resolve),u=[],c=0,d=1;LA(e,function(l){var p=c++,h=!1;d++,AA(o,t,l).then(function(m){h||(h=!0,u[p]=m,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var Ag=g(()=>{"use strict";var DA=Me(),BA=wt(),VA=Rr().CONSTRUCTOR,jc=Yi(),_A=zt(),OA=ke(),NA=Pr(),kg=jc&&jc.prototype;DA({target:"Promise",proto:!0,forced:VA,real:!0},{catch:function(s){return this.then(void 0,s)}});!BA&&OA(jc)&&(qc=_A("Promise").prototype.catch,kg.catch!==qc&&NA(kg,"catch",qc,{unsafe:!0}));var qc});var Rg=g(()=>{"use strict";var FA=Me(),UA=ot(),qA=Bt(),jA=Mr(),HA=Nn(),WA=Cn(),QA=Uc();FA({target:"Promise",stat:!0,forced:QA},{race:function(e){var t=this,i=jA.f(t),r=i.reject,a=HA(function(){var n=qA(t.resolve);WA(e,function(o){UA(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Mg=g(()=>{"use strict";var zA=Me(),GA=Mr(),YA=Rr().CONSTRUCTOR;zA({target:"Promise",stat:!0,forced:YA},{reject:function(e){var t=GA.f(this),i=t.reject;return i(e),t.promise}})});var Hc=g((QB,$g)=>{"use strict";var KA=Vt(),XA=Ke(),JA=Mr();$g.exports=function(s,e){if(KA(s),XA(e)&&e.constructor===s)return e;var t=JA.f(s),i=t.resolve;return i(e),t.promise}});var Dg=g(()=>{"use strict";var ZA=Me(),eR=zt(),Lg=wt(),tR=Yi(),Cg=Rr().CONSTRUCTOR,iR=Hc(),rR=eR("Promise"),aR=Lg&&!Cg;ZA({target:"Promise",stat:!0,forced:Lg||Cg},{resolve:function(e){return iR(aR&&this===rR?tR:this,e)}})});var Bg=g(()=>{"use strict";Sg();Pg();Ag();Rg();Mg();Dg()});var Ng=g(()=>{"use strict";var sR=Me(),nR=wt(),Qn=Yi(),oR=Ce(),_g=zt(),Og=ke(),uR=hc(),Vg=Hc(),cR=Pr(),Qc=Qn&&Qn.prototype,lR=!!Qn&&oR(function(){Qc.finally.call({then:function(){}},function(){})});sR({target:"Promise",proto:!0,real:!0,forced:lR},{finally:function(s){var e=uR(this,_g("Promise")),t=Og(s);return this.then(t?function(i){return Vg(e,s()).then(function(){return i})}:s,t?function(i){return Vg(e,s()).then(function(){throw i})}:s)}});!nR&&Og(Qn)&&(Wc=_g("Promise").prototype.finally,Qc.finally!==Wc&&cR(Qc,"finally",Wc,{unsafe:!0}));var Wc});var Ug=g((ZB,Fg)=>{"use strict";Gm();Bg();Ng();var dR=pi();Fg.exports=dR("Promise","finally")});var jg=g((eV,qg)=>{"use strict";var pR=Ug();qg.exports=pR});var zc=g((tV,Hg)=>{"use strict";var hR=jg();Hg.exports=hR});var Jg=g(()=>{"use strict";var TR=Me(),IR=vr(),ER=wr(),wR=ba(),xR=ga();TR({target:"Array",proto:!0},{at:function(e){var t=IR(this),i=ER(t),r=wR(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});xR("at")});var ev=g((zV,Zg)=>{"use strict";Jg();var PR=pi();Zg.exports=PR("Array","at")});var iv=g((GV,tv)=>{"use strict";var kR=ev();tv.exports=kR});var bt=g((YV,rv)=>{"use strict";var AR=iv();rv.exports=AR});var ml=g((QN,Vv)=>{"use strict";var jR=Ni();Vv.exports=Array.isArray||function(e){return jR(e)==="Array"}});var Ov=g((zN,_v)=>{"use strict";var HR=TypeError,WR=9007199254740991;_v.exports=function(s){if(s>WR)throw HR("Maximum allowed index exceeded");return s}});var Uv=g((GN,Fv)=>{"use strict";var QR=ml(),zR=wr(),GR=Ov(),YR=yr(),Nv=function(s,e,t,i,r,a,n,o){for(var u=r,c=0,d=n?YR(n,o):!1,l,p;c<i;)c in t&&(l=d?d(t[c],c,e):t[c],a>0&&QR(l)?(p=zR(l),u=Nv(s,e,l,p,u,a-1)-1):(GR(u+1),s[u]=l),u++),c++;return u};Fv.exports=Nv});var Wv=g((YN,Hv)=>{"use strict";var qv=ml(),KR=pc(),XR=Ke(),JR=je(),ZR=JR("species"),jv=Array;Hv.exports=function(s){var e;return qv(s)&&(e=s.constructor,KR(e)&&(e===jv||qv(e.prototype))?e=void 0:XR(e)&&(e=e[ZR],e===null&&(e=void 0))),e===void 0?jv:e}});var zv=g((KN,Qv)=>{"use strict";var eM=Wv();Qv.exports=function(s,e){return new(eM(s))(e===0?0:e)}});var Gv=g(()=>{"use strict";var tM=Me(),iM=Uv(),rM=Bt(),aM=vr(),sM=wr(),nM=zv();tM({target:"Array",proto:!0},{flatMap:function(e){var t=aM(this),i=sM(t),r;return rM(e),r=nM(t,0),r.length=iM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Yv=g(()=>{"use strict";var oM=ga();oM("flatMap")});var Xv=g((tF,Kv)=>{"use strict";Gv();Yv();var uM=pi();Kv.exports=uM("Array","flatMap")});var Zv=g((iF,Jv)=>{"use strict";var cM=Xv();Jv.exports=cM});var Qa=g((rF,eS)=>{"use strict";var lM=Zv();eS.exports=lM});var Ga=g((yF,aS)=>{"use strict";var pM=Ea(),hM=String;aS.exports=function(s){if(pM(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return hM(s)}});var gl=g((TF,sS)=>{"use strict";sS.exports=`
|
|
7
|
-
\v\f\r \u2028\u2029\uFEFF`});var uS=g((IF,oS)=>{"use strict";var fM=De(),mM=di(),bM=Ga(),Sl=gl(),nS=fM("".replace),gM=RegExp("^["+Sl+"]+"),vM=RegExp("(^|[^"+Sl+"])["+Sl+"]+$"),vl=function(s){return function(e){var t=bM(mM(e));return s&1&&(t=nS(t,gM,"")),s&2&&(t=nS(t,vM,"$1")),t}};oS.exports={start:vl(1),end:vl(2),trim:vl(3)}});var pS=g((EF,dS)=>{"use strict";var SM=Qu().PROPER,yM=Ce(),cS=gl(),lS="
";dS.exports=function(s){return yM(function(){return!!cS[s]()||lS[s]()!==lS||SM&&cS[s].name!==s})}});var yl=g((wF,hS)=>{"use strict";var TM=uS().start,IM=pS();hS.exports=IM("trimStart")?function(){return TM(this)}:"".trimStart});var mS=g(()=>{"use strict";var EM=Me(),fS=yl();EM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==fS},{trimLeft:fS})});var gS=g(()=>{"use strict";mS();var wM=Me(),bS=yl();wM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==bS},{trimStart:bS})});var SS=g((RF,vS)=>{"use strict";gS();var xM=pi();vS.exports=xM("String","trimLeft")});var TS=g((MF,yS)=>{"use strict";var PM=SS();yS.exports=PM});var ES=g(($F,IS)=>{"use strict";var kM=TS();IS.exports=kM});var xS=g(()=>{"use strict"});var PS=g(()=>{"use strict"});var AS=g((pU,kS)=>{"use strict";var AM=Ke(),RM=Ni(),MM=je(),$M=MM("match");kS.exports=function(s){var e;return AM(s)&&((e=s[$M])!==void 0?!!e:RM(s)==="RegExp")}});var $S=g((hU,MS)=>{"use strict";var LM=Pe(),CM=Ce(),RS=LM.RegExp,DM=!CM(function(){var s=!0;try{RS(".","d")}catch(u){s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!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(RS.prototype,"flags").get.call(e);return o!==i||t!==i});MS.exports={correct:DM}});var CS=g((fU,LS)=>{"use strict";var BM=Vt();LS.exports=function(){var s=BM(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 VS=g((mU,BS)=>{"use strict";var VM=ot(),_M=xt(),OM=la(),DS=$S(),NM=CS(),FM=RegExp.prototype;BS.exports=DS.correct?function(s){return s.flags}:function(s){return!DS.correct&&OM(FM,s)&&!_M(s,"flags")?VM(NM,s):s.flags}});var OS=g((bU,_S)=>{"use strict";var wl=De(),UM=vr(),qM=Math.floor,Il=wl("".charAt),jM=wl("".replace),El=wl("".slice),HM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,WM=/\$([$&'`]|\d{1,2})/g;_S.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=WM;return r!==void 0&&(r=UM(r),u=HM),jM(a,u,function(c,d){var l;switch(Il(d,0)){case"$":return"$";case"&":return s;case"`":return El(e,0,t);case"'":return El(e,n);case"<":l=r[El(d,1,-1)];break;default:var p=+d;if(p===0)return c;if(p>o){var h=qM(p/10);return h===0?c:h<=o?i[h-1]===void 0?Il(d,1):i[h-1]+Il(d,1):c}l=i[p-1]}return l===void 0?"":l})}});var US=g(()=>{"use strict";var QM=Me(),zM=ot(),Pl=De(),NS=di(),GM=ke(),YM=Ke(),KM=AS(),qr=Ga(),XM=pa(),JM=VS(),ZM=OS(),e$=je(),t$=wt(),i$=e$("replace"),r$=TypeError,xl=Pl("".indexOf),a$=Pl("".replace),FS=Pl("".slice),s$=Math.max;QM({target:"String",proto:!0},{replaceAll:function(e,t){var i=NS(this),r,a,n,o,u,c,d,l,p,h,m=0,b="";if(YM(e)){if(r=KM(e),r&&(a=qr(NS(JM(e))),!~xl(a,"g")))throw new r$("`.replaceAll` does not allow non-global regexes");if(n=XM(e,i$),n)return zM(n,e,i,t);if(t$&&r)return a$(qr(i),e,t)}for(o=qr(i),u=qr(e),c=GM(t),c||(t=qr(t)),d=u.length,l=s$(1,d),p=xl(o,u);p!==-1;)h=c?qr(t(u,p,o)):ZM(u,o,p,[],void 0,t),b+=FS(o,m,p)+h,m=p+d,p=p+l>o.length?-1:xl(o,u,p+l);return m<o.length&&(b+=FS(o,m)),b}})});var jS=g((SU,qS)=>{"use strict";xS();PS();US();var n$=pi();qS.exports=n$("String","replaceAll")});var WS=g((yU,HS)=>{"use strict";var o$=jS();HS.exports=o$});var zS=g((TU,QS)=>{"use strict";var u$=WS();QS.exports=u$});var YS=g((IU,GS)=>{"use strict";var c$=ba(),l$=Ga(),d$=di(),p$=RangeError;GS.exports=function(e){var t=l$(d$(this)),i="",r=c$(e);if(r<0||r===1/0)throw new p$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var ey=g((EU,ZS)=>{"use strict";var JS=De(),h$=Mu(),KS=Ga(),f$=YS(),m$=di(),b$=JS(f$),g$=JS("".slice),v$=Math.ceil,XS=function(s){return function(e,t,i){var r=KS(m$(e)),a=h$(t),n=r.length,o=i===void 0?" ":KS(i),u,c;return a<=n||o===""?r:(u=a-n,c=b$(o,v$(u/o.length)),c.length>u&&(c=g$(c,0,u)),s?r+c:c+r)}};ZS.exports={start:XS(!1),end:XS(!0)}});var iy=g((wU,ty)=>{"use strict";var S$=qi();ty.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(S$)});var ry=g(()=>{"use strict";var y$=Me(),T$=ey().start,I$=iy();y$({target:"String",proto:!0,forced:I$},{padStart:function(e){return T$(this,e,arguments.length>1?arguments[1]:void 0)}})});var sy=g((kU,ay)=>{"use strict";ry();var E$=pi();ay.exports=E$("String","padStart")});var oy=g((AU,ny)=>{"use strict";var w$=sy();ny.exports=w$});var cy=g((RU,uy)=>{"use strict";var x$=oy();uy.exports=x$});var mL={};wT(mL,{ChromecastState:()=>gr,HttpConnectionType:()=>tn,Observable:()=>jt.Observable,PlaybackState:()=>qe,Player:()=>Ns,PredefinedQualityLimits:()=>sa,SDK_VERSION:()=>fL,Subject:()=>jt.Subject,Subscription:()=>jt.Subscription,Surface:()=>rn,VERSION:()=>Zo,ValueSubject:()=>jt.ValueSubject,VideoFormat:()=>Dt,VideoQuality:()=>jt.VideoQuality,WebmCodecStrategy:()=>Ka,areValidLiveRecordSources:()=>df,clientChecker:()=>j,isMobile:()=>fi});module.exports=xT(mL);var Zo="2.0.151-beta.0";var qe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(qe||{}),Dt=(w=>(w.MPEG="MPEG",w.DASH="DASH",w.DASH_SEP="DASH_SEP",w.DASH_SEP_VK="DASH_SEP",w.DASH_WEBM="DASH_WEBM",w.DASH_WEBM_AV1="DASH_WEBM_AV1",w.DASH_STREAMS="DASH_STREAMS",w.DASH_WEBM_VK="DASH_WEBM",w.DASH_ONDEMAND="DASH_ONDEMAND",w.DASH_ONDEMAND_VK="DASH_ONDEMAND",w.DASH_LIVE="DASH_LIVE",w.DASH_LIVE_CMAF="DASH_LIVE_CMAF",w.DASH_LIVE_WEBM="DASH_LIVE_WEBM",w.HLS="HLS",w.HLS_ONDEMAND="HLS_ONDEMAND",w.HLS_JS="HLS",w.HLS_FMP4="HLS_FMP4",w.HLS_LIVE="HLS_LIVE",w.HLS_LIVE_CMAF="HLS_LIVE_CMAF",w.WEB_RTC_LIVE="WEB_RTC_LIVE",w))(Dt||{});var gr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(gr||{}),tn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(tn||{});var rn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(rn||{}),sa=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(sa||{});var Jl=G(Hi(),1),dT=G(Xe(),1);var re=require("@vkontakte/videoplayer-shared/es2018");var Zh=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 dn=class{constructor(e){this.connection$=new re.ValueSubject(void 0);this.castState$=new re.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new re.Subject;this.realCastState$=new re.ValueSubject("NOT_AVAILABLE");this.subscription=new re.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,re.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||Zh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:re.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,re.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,re.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,re.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,re.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,re.assertNever)(r.sessionState)}})).add((0,re.merge)((0,re.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,re.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,re.map)(r=>r.castState)),(0,re.observableFrom)([i.getCastState()])).pipe((0,re.filterChanged)(),(0,re.map)(yw),(0,re.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=(0,re.isNonNullable)(this.connection$.getValue());if(a&&!n){let c=i.getCurrentSession();(0,re.assertNonNullable)(c);let d=c.getCastDevice(),l=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,re.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,re.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:re.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},yw=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,re.assertNever)(s)}};var se=require("@vkontakte/videoplayer-shared/es2018");var Be=require("@vkontakte/videoplayer-shared/es2018");var Vu=require("@vkontakte/videoplayer-shared/es2018");var Ae=(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,Vu.assertNever)(t)}return s},hi=(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,Vu.assertNever)(e)}};var hn=s=>{var l;let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let p=e[t];(0,Be.assertNonNullable)(p);let h=(0,Be.getHighestQuality)(Object.keys(p));(0,Be.assertNonNullable)(h);let m=p[h];(0,Be.assertNonNullable)(m),a=m,n="video/mp4",o=pn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/x-mpegurl",o=pn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/dash+xml",o=pn();break}case"DASH_LIVE_CMAF":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/dash+xml",o=ef();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];(0,Be.assertNonNullable)(p),a=Ae(p.url),n="application/x-mpegurl",o=ef();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let p="Unsupported format for Chromecast",h=new Error(p);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Be.ErrorCategory.VIDEO_PIPELINE,message:p,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return(0,Be.assertNever)(t)}let u=Tw((l=i.videoId)!=null?l:a,n);u.contentUrl=a,u.streamType=o,u.metadata=Iw();let{title:c,subtitle:d}=i;return(0,Be.isNonNullable)(c)&&(u.metadata.title=c),(0,Be.isNonNullable)(d)&&(u.metadata.subtitle=d),u};function pn(){var s,e,t,i;return(i=(t=(e=(s=chrome.cast)==null?void 0:s.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function ef(){var s,e,t,i;return(i=(t=(e=(s=chrome.cast)==null?void 0:s.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function Tw(s,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:pn()}}function Iw(){var s,e;return(e=(s=chrome.cast)==null?void 0:s.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var B=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var fn=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};var Ou=require("@vkontakte/videoplayer-shared/es2018");var In=require("@vkontakte/videoplayer-shared/es2018");var tf=G(Xe(),1),rf=require("@vkontakte/videoplayer-shared/es2018");var mn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,tf.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,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,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||c||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}=(0,rf.getWindow)().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 af=G(Xe(),1),mi=require("@vkontakte/videoplayer-shared/es2018");var fi=()=>{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 bn=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,af.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=(0,mi.getWindow)();if(!(0,mi.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=fi()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=(0,mi.getWindow)();if(!(0,mi.isBrowserWindow)(e))return;let{userAgentData:t}=e.navigator;if(t!=null&&t.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,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("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r.length>0,o=r.length>1,u="Unknown",c="Unknown";if(n){let d=r[0];typeof d=="number"?d<a.length&&a[d]!==void 0&&(u=a[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<a.length&&a[d]!==void 0&&(c=a[d]):d!==void 0&&(c=d)}else a[2]!==void 0?c=a[2]:a[1]!==void 0&&n&&typeof r[0]=="string"&&(c=a[1]);u=this.normalizeOSName(u),c=this.normalizeOSVersion(c,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:c||"Unknown",full:c&&c!=="Unknown"?`${u} ${c}`:u};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r[0],o=r[1],u=typeof n=="number"?a[n]!==void 0?this.normalizeVendorName(a[n]):"Unknown":this.normalizeVendorName(n),c="Unknown";typeof o=="number"?c=a[o]!==void 0?a[o]:"Unknown":o!==void 0?c=o:a[1]!==void 0?c=a[1]:a[0]!==void 0&&(c=a[0]),c=this.normalizeModelName(c,u),this.details.vendor=u,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=(0,mi.getWindow)();if(!(0,mi.isBrowserWindow)(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t!=null&&t[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var va=require("@vkontakte/videoplayer-shared/es2018"),gn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,va.getWindow)()}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var a;let e=(0,va.getWindow)();if(!(0,va.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((a=e.matchMedia("(dynamic-range: high)"))!=null&&a.matches),this._colorDepth=i.colorDepth}catch(n){console.error(n)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(n){console.error(n)}}};var Wi=require("@vkontakte/videoplayer-shared/es2018");var ut=()=>window.ManagedMediaSource||window.MediaSource,xr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},sf=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},vn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var nf,Ew=(nf=(0,Wi.getWindow)().document)==null?void 0:nf.createElement("video"),ww='video/mp4; codecs="avc1.42000a,mp4a.40.2"',xw='video/mp4; codecs="hev1.1.6.L93.B0"',of='video/webm; codecs="vp09.00.10.08"',uf='video/webm; codecs="av01.0.00M.08"',Pw='audio/mp4; codecs="mp4a.40.2"',kw='audio/webm; codecs="opus"',cf,Aw=async()=>{let s=(0,Wi.getWindow)();if(!(0,Wi.isBrowserWindow)(s))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:uf}}),s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:of}})]);cf={DASH_WEBM_AV1:t,DASH_WEBM:i}};Aw().catch(s=>{console.log(Ew),console.error(s)});var Sn=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return cf}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,a,n,o,u,c,d,l,p,h,m,b,S,v,y,x,w,M,_;let e=(0,Wi.getWindow)();if(!(0,Wi.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:xr(),mse:sf(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(a=this._video).canPlayType)!=null&&n.call(a,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((d=(c=this._video).canPlayType)!=null&&d.call(c,"video/webm")),cmaf:!0};let F=!!((p=(l=ut())==null?void 0:l.isTypeSupported)!=null&&p.call(l,ww)),O=!!((m=(h=ut())==null?void 0:h.isTypeSupported)!=null&&m.call(h,xw)),H=!!((S=(b=ut())==null?void 0:b.isTypeSupported)!=null&&S.call(b,Pw));this._codecs={h264:F,h265:O,vp9:!!((y=(v=ut())==null?void 0:v.isTypeSupported)!=null&&y.call(v,of)),av1:!!((w=(x=ut())==null?void 0:x.isTypeSupported)!=null&&w.call(x,uf)),aac:H,opus:!!((_=(M=ut())==null?void 0:M.isTypeSupported)!=null&&_.call(M,kw)),mpeg:(F||O)&&H},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(F){console.error(F)}try{this.destroyVideoElement()}catch(F){console.error("Error destroying video element:",F)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Tn=require("@vkontakte/videoplayer-shared/es2018");var lf="audio/mpeg",yn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,a,n;let e=(0,Tn.getWindow)();if(!(0,Tn.isBrowserWindow)(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!((r=(i=this._audio).canPlayType)!=null&&r.call(i,lf))},this._codecs={mp3:!!((n=(a=ut())==null?void 0:a.isTypeSupported)!=null&&n.call(a,lf))}}catch(o){console.error(o)}try{this.destroyAudioElement()}catch(o){console.error("Error destroying audio element:",o)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var _u=class{constructor(){this.isInited$=new In.ValueSubject(!1);this._displayChecker=new gn,this._deviceChecker=new bn(this._displayChecker),this._browserChecker=new mn,this._videoChecker=new Sn(this._deviceChecker,this._browserChecker),this._audioChecker=new yn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){(0,In.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},j=new _u;var Nu=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=j.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,Ou.assertNever)(o)}})},Sa=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,Ou.assertNever)(s)}},df=s=>{let t=Object.keys(s).filter(i=>!Sa(i));return Nu(t).length>0};var ya=class{constructor(e){this.subscription=new se.Subscription;this.sessionId$=new se.ValueSubject(null);this.mediaSessionId$=new se.ValueSubject(null);this.contentId$=new se.ValueSubject(null);this.isMobile=fi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var a,n,o;if((0,se.isNullable)(e))return;this.media=e,this.mediaSessionId$.next((a=e.mediaSessionId)!=null?a:null);let t=(n=e.media)==null?void 0:n.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=(o=e.media)==null?void 0:o.duration;(0,se.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,se.isNonNullable)(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let c=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!c?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new fn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Sa(e.format)),this.subscribe()}subscribe(){let e=r=>{var a;this.params.output.error$.next({category:se.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:(a=r==null?void 0:r.message)!=null?a:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,se.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,se.filter)(se.isNonNullable),(0,se.filterChanged)(),(0,se.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,se.filterChanged)(),(0,se.map)(Boolean));this.subscription.add((0,se.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,se.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,se.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,se.filter)(({mediaLoaded:r})=>r),(0,se.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,se.filter)(({mediaLoaded:r,playbackState:{from:a,to:n}})=>!r&&a==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,se.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,se.debounce)(30)),mediaLoaded:t}).pipe((0,se.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:n}=r.to;this.setVolume(n,a)},e))}handleMessage(e){var t,i,r,a,n,o;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let u=(i=(t=e.message)==null?void 0:t.media)==null?void 0:i[0];this.syncMediaState(u);let c=(r=e.message)==null?void 0:r.receiver.volume;this.syncVolumeState(c)}break;case"v2_message":{switch((a=e.message)==null?void 0:a.type){case"MEDIA_STATUS":{let u=(o=(n=e.message)==null?void 0:n.status)==null?void 0:o[0];this.syncMediaState(u);break}}break}}}loadMedia(){var o;let e=hn(this.params),t=(o=this.media)==null?void 0:o.currentTime,i=this.params.desiredState.seekState.getState(),r=t!=null?t:i.state!=="none"?i.position/1e3:0,n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();(0,se.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,se.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,se.assertNonNullable)(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":B(this.params.desiredState.playbackState,"paused");break;case"PLAYING":B(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),B(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):B(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if((0,se.isNullable)(e))return;let{level:t,muted:i}=e,r={muted:i!=null?i:!1,volume:t!=null?t:0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let a=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,a+=`, volume passed to state machine: ${r.volume}`),this.log({message:a}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};var he=require("@vkontakte/videoplayer-shared/es2018");var pf=s=>({castDevice:{friendlyName:s},remotePlayer:{},remotePlayerController:{},session:{}}),hf=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Ta=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new he.ValueSubject(null);this.sessionId$=new he.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new he.Subscription;this.subscriptionEvents=new he.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new he.ValueSubject(!1);this.presentationConnection$=new he.ValueSubject(null);this.message$=new he.ValueSubject(null);this.friendlyName$=new he.ValueSubject(null);this.errorEvent$=new he.Subject;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let a=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add((0,he.fromEvent)(r,"change").subscribe(()=>{a()})),a()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){var e;this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let t=this.presentationRequest$.getValue();(0,he.assertNonNullable)(t,"connect with null presentationRequest");let i=await t.start();this.handleConnection(i)}catch(t){switch(t==null?void 0:t.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:he.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}}subscribe(){this.subscription.add((0,he.fromEvent)(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe((0,he.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,he.filter)(e=>!!e)).subscribe(e=>{let t=(0,he.fromEvent)(e,"message").subscribe(a=>{let n=JSON.parse(a.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${a.data}`}),this.handleMessage(n),this.message$.next(n))}),i=(0,he.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,he.fromEvent)(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:he.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:a});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();(t==null?void 0:t.state)==="connected"&&(t==null||t.send(e))}catch(t){this.errorEvent$.next({category:he.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){var t;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":((t=e.message)==null?void 0:t.action)==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||hf()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new he.Subscription}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};var He=require("@vkontakte/videoplayer-shared/es2018");var Gt=class s{constructor(e){this.subscription=new He.Subscription;this.connection$=new He.ValueSubject(void 0);this.castState$=new He.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new He.Subject;let t=s.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Ta({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,He.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,He.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,He.filterChanged)())});this.subscription.add(e.pipe((0,He.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,He.filterChanged)()).subscribe(t=>{var r,a;let i=(a=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?a:"";this.connection$.next(t?pf(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){var e;this.log({message:"connect"}),(e=this.chromecastConnector)==null||e.connect()}disconnect(){var e;this.log({message:"disconnect"}),(e=this.chromecastConnector)==null||e.disconnect()}async stopMedia(){var e;this.log({message:"stopMedia"}),(e=this.chromecastConnector)==null||e.stopMedia()}toggleConnection(){var t;let e=!!((t=this.chromecastConnector)!=null&&t.presentationConnection$.getValue());this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){var e;this.log({message:"destroy"}),(e=this.chromecastConnector)==null||e.destroy(),this.subscription.unsubscribe()}};var zl=G(Xe(),1),Gl=G(bi(),1),Jy=G(oc(),1);var Qg=G(zc(),1);var Ot=require("@vkontakte/videoplayer-shared/es2018"),ae=class{constructor(e){this.transitionStarted$=new Ot.Subject;this.transitionEnded$=new Ot.Subject;this.transitionUpdated$=new Ot.Subject;this.forceChanged$=new Ot.Subject;this.stateChangeStarted$=(0,Ot.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Ot.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,Ot.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 ue=require("@vkontakte/videoplayer-shared/es2018");var fR=5,mR=5,bR=500,Wg=7e3,Da=class{constructor(e){this.subscription=new ue.Subscription;this.loadMediaTimeoutSubscription=new ue.Subscription;this.videoState=new ae("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,ue.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,ue.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,ue.assertNever)(e)}break}default:(0,ue.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(Sa(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 ue.Subscription;this.subscription.add(e),this.subscription.add((0,ue.merge)(this.videoState.stateChangeStarted$.pipe((0,ue.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,ue.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 ue.Subject;e.add(r.pipe((0,ue.debounce)(bR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,ue.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)>fR)&&r.next(o),a=o})),e.add((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,ue.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,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,ue.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<mR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),B(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,ue.assertNever)(n)}}),t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,ue.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=hn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,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()}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,ue.timeout)(Wg).subscribe(()=>a(`timeout(${Wg})`)))});(0,Qg.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:ue.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ul=G(Xe(),1);var Ba=require("@vkontakte/videoplayer-shared/es2018");var zg=require("@vkontakte/videoplayer-shared/es2018"),Gg=s=>{try{s.pause(),s.playbackRate=0,(0,zg.clearVideoElement)(s),s.remove()}catch(e){console.error(e)}};var Gn=require("@vkontakte/videoplayer-shared/es2018"),Gc=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},zn=(0,Ba.getWindow)(),Yc=zn.WeakMap?new zn.WeakMap:new Gc,Kc=zn.WeakMap?new zn.WeakMap:new Map,gR=(s,e=20)=>{let t=0;return(0,Gn.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Je=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?(0,Ba.clearVideoElement)(i):(i=document.createElement("video"),s.appendChild(i)),Yc.set(i,r);let a=new Gn.Subscription;return a.add(gR(i,e)),Kc.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},Ze=s=>{let e=Kc.get(s);e==null||e.unsubscribe(),Kc.delete(s);let t=Yc.get(s);Yc.delete(s),t?(0,Ba.clearVideoElement)(s):Gg(s)};var Xc=G(Hi(),1),z=require("@vkontakte/videoplayer-shared/es2018");var vi=require("@vkontakte/videoplayer-shared/es2018"),Yn=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,vi.isNullable)(r),c=new vi.Subscription;return r&&c.add(r.subscribe(d=>{let l=s.getState();i(d,l)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),c.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),c},Nt=(s,e,t)=>Yn(e,()=>s.loop,i=>{(0,vi.isNonNullable)(i)&&(s.loop=i)},{onError:t}),et=(s,e,t,i)=>Yn(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,vi.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}),ft=(s,e,t,i)=>Yn(e,()=>s.playbackRate,r=>{(0,vi.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Va=Yn;var vR=s=>["__",s.language,s.label].join("|"),SR=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Jc=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(Va(t.internalTextTracks,()=>(0,Xc.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(Va(t.externalTextTracks,()=>(0,Xc.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(Va(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(Va(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 c,d,l,p,h;let u=(d=(c=o.target)==null?void 0:c.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(l=o.target)==null?void 0:l.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,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,c,d,l;let{language:t,label:i}=e,r=e.id?e.id:vR(e),a=this.externalTracks.has(r),n=(c=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?c:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(l=this.internalTracks.get(r))==null?void 0:l.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto: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)||!SR(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)}},mt=Jc;var Xi=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 Yg=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},Zc=s=>{let e=Yg(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Kg=s=>{let e=Yg(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var L=require("@vkontakte/videoplayer-shared/es2018");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 tt=s=>{let e=V=>(0,L.fromEvent)(s,V).pipe((0,L.mapTo)(void 0),(0,L.shareReplay)(1)),t=new L.Subscription,i=()=>t.unsubscribe(),r=(0,L.merge)((0,L.fromEvent)(s,"progress"),(0,L.fromEvent)(s,"timeupdate")).pipe((0,L.map)(()=>Xg(s.buffered,s.currentTime)),(0,L.shareReplay)(1)),a=j.browser.isSafari?(0,L.combine)({play:e("play").pipe((0,L.once)()),playing:e("playing")}).pipe((0,L.mapTo)(void 0),(0,L.shareReplay)(1)):e("playing"),n=(0,L.fromEvent)(s,"volumechange").pipe((0,L.map)(()=>({muted:s.muted,volume:s.volume})),(0,L.shareReplay)(1)),o=(0,L.fromEvent)(s,"ratechange").pipe((0,L.map)(()=>s.playbackRate),(0,L.shareReplay)(1)),u=(0,L.fromEvent)(s,"error").pipe((0,L.filter)(()=>!!(s.error||s.played.length)),(0,L.map)(()=>{var Q;let V=s.error;return{id:V?`MediaError#${V.code}`:"HtmlVideoError",category:L.ErrorCategory.VIDEO_PIPELINE,message:V?V.message:"Error event from HTML video element",thrown:(Q=s.error)!=null?Q:void 0}}),(0,L.shareReplay)(1)),c=(0,L.fromEvent)(s,"timeupdate").pipe((0,L.map)(()=>s.currentTime),(0,L.shareReplay)(1)),d=["waiting","seeking","seeked","timeupdate"],l=new L.Subject,p=.3,h;t.add((0,L.merge)(...d.map(V=>(0,L.fromEvent)(s,V))).subscribe(V=>{let Q=s.currentTime;s.loop&&(0,L.isNonNullable)(h)&&(0,L.isNonNullable)(Q)&&h>=s.duration-p&&Q<=p&&l.next(h),h=Q}));let m=e("pause").pipe((0,L.filter)(()=>!s.error&&h!==s.duration),(0,L.shareReplay)(1)),b=(0,L.fromEvent)(s,"enterpictureinpicture").pipe((0,L.shareReplay)(1)),S=(0,L.fromEvent)(s,"leavepictureinpicture").pipe((0,L.shareReplay)(1)),v=new L.ValueSubject(Kg(s));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let y=new L.ValueSubject(Zc(s)),x=(0,L.fromEvent)(s,"fullscreenchange").pipe((0,L.shareReplay)(1));t.add(x.pipe((0,L.map)(()=>Zc(s))).subscribe(y));let w=.1,M=1e3,_=(0,L.fromEvent)(s,"timeupdate").pipe((0,L.map)(V=>s.duration-s.currentTime<w),(0,L.filterChanged)(),(0,L.shareReplay)(1)),F=(0,L.merge)(_.pipe((0,L.filter)(V=>!s.loop&&V)),(0,L.fromEvent)(s,"ended")).pipe((0,L.throttle)(M),(0,L.mapTo)(void 0),(0,L.shareReplay)(1)),H=(0,L.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(V=>(0,L.fromEvent)(s,V)),_.pipe((0,L.map)(V=>({type:V?"ended":"unknown"})))).pipe((0,L.map)(V=>j.browser.isFirefox&&V.type==="ended"?s.readyState<2:s.readyState<3),(0,L.filterChanged)(),(0,L.shareReplay)(1));return{playing$:a,pause$:m,canplay$:e("canplay"),ended$:F,looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,L.fromEvent)(s,"durationchange").pipe((0,L.map)(()=>s.duration),(0,L.shareReplay)(1)),isBuffering$:H,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:y,enterPip$:b,leavePip$:S,destroy:i}};var Kt=require("@vkontakte/videoplayer-shared/es2018"),Si=s=>{switch(s){case"mobile":return Kt.VideoQuality.Q_144P;case"lowest":return Kt.VideoQuality.Q_240P;case"low":return Kt.VideoQuality.Q_360P;case"sd":case"medium":return Kt.VideoQuality.Q_480P;case"hd":case"high":return Kt.VideoQuality.Q_720P;case"fullhd":case"full":return Kt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Kt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Kt.VideoQuality.Q_2160P}};var Ge=G(bt(),1),tl=G(Xe(),1),Ji=G(bi(),1),D=require("@vkontakte/videoplayer-shared/es2018");var el=!1,Xt={},av=s=>{el=s},sv=()=>{Xt={}},nv=s=>{s(Xt)},_a=(s,e)=>{var t;el&&(Xt.meta=(t=Xt.meta)!=null?t:{},Xt.meta[s]=e)},ze=class{constructor(e){this.name=e}next(e){var i,r;if(!el)return;Xt.series=(i=Xt.series)!=null?i:{};let t=(r=Xt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Xt.series[this.name]=t}};var $e=require("@vkontakte/videoplayer-shared/es2018");function ov(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Br(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 uv({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Br({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 hv=new ze("best_bitrate"),Xn=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Vr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),yi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,D.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Jn='Assertion "ABR Tracks is empty array" failed',Kn=new WeakMap,cv=new WeakMap,lv=new WeakMap,Oa=(s,e,t,i)=>{var u;let r=[...e].sort(Vr(1)),a=[...t].sort(Vr(1)),n=a.filter(c=>(0,D.isNonNullable)(c.bitrate)&&(0,D.isNonNullable)(s.bitrate)?s.bitrate/c.bitrate>i:!0),o=(u=(0,Ge.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Ge.default)(a,-1);return o&&(0,tl.default)(n,o)?o:n.length?(0,Ge.default)(n,-1):(0,Ge.default)(a,0)},Na=(s,e,t,i)=>{var u;let r=Kn.get(e);r||(r=[...e].sort(Vr(1)),Kn.set(e,r));let a=Kn.get(t);a||(a=[...t].sort(Vr(1)),Kn.set(t,a));let n=lv.get(s);n||(n=a.filter(c=>(0,D.isNonNullable)(c.bitrate)&&(0,D.isNonNullable)(s.bitrate)?s.bitrate/c.bitrate>i:!0),lv.set(s,n));let o=(u=(0,Ge.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Ge.default)(a,-1);return o&&(0,tl.default)(n,o)?o:n.length?(0,Ge.default)(n,-1):(0,Ge.default)(a,0)},dv=s=>"quality"in s,Zn=(s,e,t,i)=>{var n;let r=(0,D.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,D.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,D.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=dv(o)?"video":"audio",c=dv(o)?o.quality:o.bitrate;return e({message:`
|
|
7
|
+
\v\f\r \u2028\u2029\uFEFF`});var uS=g((IF,oS)=>{"use strict";var fM=De(),mM=di(),bM=Ga(),Sl=gl(),nS=fM("".replace),gM=RegExp("^["+Sl+"]+"),vM=RegExp("(^|[^"+Sl+"])["+Sl+"]+$"),vl=function(s){return function(e){var t=bM(mM(e));return s&1&&(t=nS(t,gM,"")),s&2&&(t=nS(t,vM,"$1")),t}};oS.exports={start:vl(1),end:vl(2),trim:vl(3)}});var pS=g((EF,dS)=>{"use strict";var SM=Qu().PROPER,yM=Ce(),cS=gl(),lS="
";dS.exports=function(s){return yM(function(){return!!cS[s]()||lS[s]()!==lS||SM&&cS[s].name!==s})}});var yl=g((wF,hS)=>{"use strict";var TM=uS().start,IM=pS();hS.exports=IM("trimStart")?function(){return TM(this)}:"".trimStart});var mS=g(()=>{"use strict";var EM=Me(),fS=yl();EM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==fS},{trimLeft:fS})});var gS=g(()=>{"use strict";mS();var wM=Me(),bS=yl();wM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==bS},{trimStart:bS})});var SS=g((RF,vS)=>{"use strict";gS();var xM=pi();vS.exports=xM("String","trimLeft")});var TS=g((MF,yS)=>{"use strict";var PM=SS();yS.exports=PM});var ES=g(($F,IS)=>{"use strict";var kM=TS();IS.exports=kM});var xS=g(()=>{"use strict"});var PS=g(()=>{"use strict"});var AS=g((pU,kS)=>{"use strict";var AM=Ke(),RM=Ni(),MM=je(),$M=MM("match");kS.exports=function(s){var e;return AM(s)&&((e=s[$M])!==void 0?!!e:RM(s)==="RegExp")}});var $S=g((hU,MS)=>{"use strict";var LM=Pe(),CM=Ce(),RS=LM.RegExp,DM=!CM(function(){var s=!0;try{RS(".","d")}catch(u){s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!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(RS.prototype,"flags").get.call(e);return o!==i||t!==i});MS.exports={correct:DM}});var CS=g((fU,LS)=>{"use strict";var BM=Vt();LS.exports=function(){var s=BM(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 VS=g((mU,BS)=>{"use strict";var VM=ot(),_M=xt(),OM=la(),DS=$S(),NM=CS(),FM=RegExp.prototype;BS.exports=DS.correct?function(s){return s.flags}:function(s){return!DS.correct&&OM(FM,s)&&!_M(s,"flags")?VM(NM,s):s.flags}});var OS=g((bU,_S)=>{"use strict";var wl=De(),UM=vr(),qM=Math.floor,Il=wl("".charAt),jM=wl("".replace),El=wl("".slice),HM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,WM=/\$([$&'`]|\d{1,2})/g;_S.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=WM;return r!==void 0&&(r=UM(r),u=HM),jM(a,u,function(c,d){var l;switch(Il(d,0)){case"$":return"$";case"&":return s;case"`":return El(e,0,t);case"'":return El(e,n);case"<":l=r[El(d,1,-1)];break;default:var p=+d;if(p===0)return c;if(p>o){var h=qM(p/10);return h===0?c:h<=o?i[h-1]===void 0?Il(d,1):i[h-1]+Il(d,1):c}l=i[p-1]}return l===void 0?"":l})}});var US=g(()=>{"use strict";var QM=Me(),zM=ot(),Pl=De(),NS=di(),GM=ke(),YM=Ke(),KM=AS(),qr=Ga(),XM=pa(),JM=VS(),ZM=OS(),e$=je(),t$=wt(),i$=e$("replace"),r$=TypeError,xl=Pl("".indexOf),a$=Pl("".replace),FS=Pl("".slice),s$=Math.max;QM({target:"String",proto:!0},{replaceAll:function(e,t){var i=NS(this),r,a,n,o,u,c,d,l,p,h,m=0,b="";if(YM(e)){if(r=KM(e),r&&(a=qr(NS(JM(e))),!~xl(a,"g")))throw new r$("`.replaceAll` does not allow non-global regexes");if(n=XM(e,i$),n)return zM(n,e,i,t);if(t$&&r)return a$(qr(i),e,t)}for(o=qr(i),u=qr(e),c=GM(t),c||(t=qr(t)),d=u.length,l=s$(1,d),p=xl(o,u);p!==-1;)h=c?qr(t(u,p,o)):ZM(u,o,p,[],void 0,t),b+=FS(o,m,p)+h,m=p+d,p=p+l>o.length?-1:xl(o,u,p+l);return m<o.length&&(b+=FS(o,m)),b}})});var jS=g((SU,qS)=>{"use strict";xS();PS();US();var n$=pi();qS.exports=n$("String","replaceAll")});var WS=g((yU,HS)=>{"use strict";var o$=jS();HS.exports=o$});var zS=g((TU,QS)=>{"use strict";var u$=WS();QS.exports=u$});var YS=g((IU,GS)=>{"use strict";var c$=ba(),l$=Ga(),d$=di(),p$=RangeError;GS.exports=function(e){var t=l$(d$(this)),i="",r=c$(e);if(r<0||r===1/0)throw new p$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var ey=g((EU,ZS)=>{"use strict";var JS=De(),h$=Mu(),KS=Ga(),f$=YS(),m$=di(),b$=JS(f$),g$=JS("".slice),v$=Math.ceil,XS=function(s){return function(e,t,i){var r=KS(m$(e)),a=h$(t),n=r.length,o=i===void 0?" ":KS(i),u,c;return a<=n||o===""?r:(u=a-n,c=b$(o,v$(u/o.length)),c.length>u&&(c=g$(c,0,u)),s?r+c:c+r)}};ZS.exports={start:XS(!1),end:XS(!0)}});var iy=g((wU,ty)=>{"use strict";var S$=qi();ty.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(S$)});var ry=g(()=>{"use strict";var y$=Me(),T$=ey().start,I$=iy();y$({target:"String",proto:!0,forced:I$},{padStart:function(e){return T$(this,e,arguments.length>1?arguments[1]:void 0)}})});var sy=g((kU,ay)=>{"use strict";ry();var E$=pi();ay.exports=E$("String","padStart")});var oy=g((AU,ny)=>{"use strict";var w$=sy();ny.exports=w$});var cy=g((RU,uy)=>{"use strict";var x$=oy();uy.exports=x$});var mL={};wT(mL,{ChromecastState:()=>gr,HttpConnectionType:()=>tn,Observable:()=>jt.Observable,PlaybackState:()=>qe,Player:()=>Ns,PredefinedQualityLimits:()=>sa,SDK_VERSION:()=>fL,Subject:()=>jt.Subject,Subscription:()=>jt.Subscription,Surface:()=>rn,VERSION:()=>Zo,ValueSubject:()=>jt.ValueSubject,VideoFormat:()=>Dt,VideoQuality:()=>jt.VideoQuality,WebmCodecStrategy:()=>Ka,areValidLiveRecordSources:()=>df,clientChecker:()=>j,isMobile:()=>fi});module.exports=xT(mL);var Zo="2.0.151-beta.1";var qe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(qe||{}),Dt=(w=>(w.MPEG="MPEG",w.DASH="DASH",w.DASH_SEP="DASH_SEP",w.DASH_SEP_VK="DASH_SEP",w.DASH_WEBM="DASH_WEBM",w.DASH_WEBM_AV1="DASH_WEBM_AV1",w.DASH_STREAMS="DASH_STREAMS",w.DASH_WEBM_VK="DASH_WEBM",w.DASH_ONDEMAND="DASH_ONDEMAND",w.DASH_ONDEMAND_VK="DASH_ONDEMAND",w.DASH_LIVE="DASH_LIVE",w.DASH_LIVE_CMAF="DASH_LIVE_CMAF",w.DASH_LIVE_WEBM="DASH_LIVE_WEBM",w.HLS="HLS",w.HLS_ONDEMAND="HLS_ONDEMAND",w.HLS_JS="HLS",w.HLS_FMP4="HLS_FMP4",w.HLS_LIVE="HLS_LIVE",w.HLS_LIVE_CMAF="HLS_LIVE_CMAF",w.WEB_RTC_LIVE="WEB_RTC_LIVE",w))(Dt||{});var gr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(gr||{}),tn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(tn||{});var rn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(rn||{}),sa=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(sa||{});var Jl=G(Hi(),1),dT=G(Xe(),1);var re=require("@vkontakte/videoplayer-shared/es2018");var Zh=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 dn=class{constructor(e){this.connection$=new re.ValueSubject(void 0);this.castState$=new re.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new re.Subject;this.realCastState$=new re.ValueSubject("NOT_AVAILABLE");this.subscription=new re.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,re.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||Zh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:re.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,re.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,re.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,re.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,re.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,re.assertNever)(r.sessionState)}})).add((0,re.merge)((0,re.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,re.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,re.map)(r=>r.castState)),(0,re.observableFrom)([i.getCastState()])).pipe((0,re.filterChanged)(),(0,re.map)(yw),(0,re.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=(0,re.isNonNullable)(this.connection$.getValue());if(a&&!n){let c=i.getCurrentSession();(0,re.assertNonNullable)(c);let d=c.getCastDevice(),l=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,re.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,re.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:re.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},yw=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,re.assertNever)(s)}};var se=require("@vkontakte/videoplayer-shared/es2018");var Be=require("@vkontakte/videoplayer-shared/es2018");var Vu=require("@vkontakte/videoplayer-shared/es2018");var Ae=(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,Vu.assertNever)(t)}return s},hi=(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,Vu.assertNever)(e)}};var hn=s=>{var l;let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let p=e[t];(0,Be.assertNonNullable)(p);let h=(0,Be.getHighestQuality)(Object.keys(p));(0,Be.assertNonNullable)(h);let m=p[h];(0,Be.assertNonNullable)(m),a=m,n="video/mp4",o=pn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/x-mpegurl",o=pn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/dash+xml",o=pn();break}case"DASH_LIVE_CMAF":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/dash+xml",o=ef();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];(0,Be.assertNonNullable)(p),a=Ae(p.url),n="application/x-mpegurl",o=ef();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let p="Unsupported format for Chromecast",h=new Error(p);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Be.ErrorCategory.VIDEO_PIPELINE,message:p,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return(0,Be.assertNever)(t)}let u=Tw((l=i.videoId)!=null?l:a,n);u.contentUrl=a,u.streamType=o,u.metadata=Iw();let{title:c,subtitle:d}=i;return(0,Be.isNonNullable)(c)&&(u.metadata.title=c),(0,Be.isNonNullable)(d)&&(u.metadata.subtitle=d),u};function pn(){var s,e,t,i;return(i=(t=(e=(s=chrome.cast)==null?void 0:s.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function ef(){var s,e,t,i;return(i=(t=(e=(s=chrome.cast)==null?void 0:s.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function Tw(s,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:pn()}}function Iw(){var s,e;return(e=(s=chrome.cast)==null?void 0:s.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var B=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var fn=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};var Ou=require("@vkontakte/videoplayer-shared/es2018");var In=require("@vkontakte/videoplayer-shared/es2018");var tf=G(Xe(),1),rf=require("@vkontakte/videoplayer-shared/es2018");var mn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,tf.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,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,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||c||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}=(0,rf.getWindow)().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 af=G(Xe(),1),mi=require("@vkontakte/videoplayer-shared/es2018");var fi=()=>{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 bn=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,af.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=(0,mi.getWindow)();if(!(0,mi.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=fi()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=(0,mi.getWindow)();if(!(0,mi.isBrowserWindow)(e))return;let{userAgentData:t}=e.navigator;if(t!=null&&t.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,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("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r.length>0,o=r.length>1,u="Unknown",c="Unknown";if(n){let d=r[0];typeof d=="number"?d<a.length&&a[d]!==void 0&&(u=a[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<a.length&&a[d]!==void 0&&(c=a[d]):d!==void 0&&(c=d)}else a[2]!==void 0?c=a[2]:a[1]!==void 0&&n&&typeof r[0]=="string"&&(c=a[1]);u=this.normalizeOSName(u),c=this.normalizeOSVersion(c,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:c||"Unknown",full:c&&c!=="Unknown"?`${u} ${c}`:u};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r[0],o=r[1],u=typeof n=="number"?a[n]!==void 0?this.normalizeVendorName(a[n]):"Unknown":this.normalizeVendorName(n),c="Unknown";typeof o=="number"?c=a[o]!==void 0?a[o]:"Unknown":o!==void 0?c=o:a[1]!==void 0?c=a[1]:a[0]!==void 0&&(c=a[0]),c=this.normalizeModelName(c,u),this.details.vendor=u,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=(0,mi.getWindow)();if(!(0,mi.isBrowserWindow)(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t!=null&&t[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var va=require("@vkontakte/videoplayer-shared/es2018"),gn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,va.getWindow)()}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var a;let e=(0,va.getWindow)();if(!(0,va.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((a=e.matchMedia("(dynamic-range: high)"))!=null&&a.matches),this._colorDepth=i.colorDepth}catch(n){console.error(n)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(n){console.error(n)}}};var Wi=require("@vkontakte/videoplayer-shared/es2018");var ut=()=>window.ManagedMediaSource||window.MediaSource,xr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},sf=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},vn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var nf,Ew=(nf=(0,Wi.getWindow)().document)==null?void 0:nf.createElement("video"),ww='video/mp4; codecs="avc1.42000a,mp4a.40.2"',xw='video/mp4; codecs="hev1.1.6.L93.B0"',of='video/webm; codecs="vp09.00.10.08"',uf='video/webm; codecs="av01.0.00M.08"',Pw='audio/mp4; codecs="mp4a.40.2"',kw='audio/webm; codecs="opus"',cf,Aw=async()=>{let s=(0,Wi.getWindow)();if(!(0,Wi.isBrowserWindow)(s))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:uf}}),s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:of}})]);cf={DASH_WEBM_AV1:t,DASH_WEBM:i}};Aw().catch(s=>{console.log(Ew),console.error(s)});var Sn=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return cf}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,a,n,o,u,c,d,l,p,h,m,b,S,v,y,x,w,M,_;let e=(0,Wi.getWindow)();if(!(0,Wi.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:xr(),mse:sf(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(a=this._video).canPlayType)!=null&&n.call(a,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((d=(c=this._video).canPlayType)!=null&&d.call(c,"video/webm")),cmaf:!0};let F=!!((p=(l=ut())==null?void 0:l.isTypeSupported)!=null&&p.call(l,ww)),O=!!((m=(h=ut())==null?void 0:h.isTypeSupported)!=null&&m.call(h,xw)),H=!!((S=(b=ut())==null?void 0:b.isTypeSupported)!=null&&S.call(b,Pw));this._codecs={h264:F,h265:O,vp9:!!((y=(v=ut())==null?void 0:v.isTypeSupported)!=null&&y.call(v,of)),av1:!!((w=(x=ut())==null?void 0:x.isTypeSupported)!=null&&w.call(x,uf)),aac:H,opus:!!((_=(M=ut())==null?void 0:M.isTypeSupported)!=null&&_.call(M,kw)),mpeg:(F||O)&&H},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(F){console.error(F)}try{this.destroyVideoElement()}catch(F){console.error("Error destroying video element:",F)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Tn=require("@vkontakte/videoplayer-shared/es2018");var lf="audio/mpeg",yn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,a,n;let e=(0,Tn.getWindow)();if(!(0,Tn.isBrowserWindow)(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!((r=(i=this._audio).canPlayType)!=null&&r.call(i,lf))},this._codecs={mp3:!!((n=(a=ut())==null?void 0:a.isTypeSupported)!=null&&n.call(a,lf))}}catch(o){console.error(o)}try{this.destroyAudioElement()}catch(o){console.error("Error destroying audio element:",o)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var _u=class{constructor(){this.isInited$=new In.ValueSubject(!1);this._displayChecker=new gn,this._deviceChecker=new bn(this._displayChecker),this._browserChecker=new mn,this._videoChecker=new Sn(this._deviceChecker,this._browserChecker),this._audioChecker=new yn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){(0,In.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},j=new _u;var Nu=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=j.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,Ou.assertNever)(o)}})},Sa=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,Ou.assertNever)(s)}},df=s=>{let t=Object.keys(s).filter(i=>!Sa(i));return Nu(t).length>0};var ya=class{constructor(e){this.subscription=new se.Subscription;this.sessionId$=new se.ValueSubject(null);this.mediaSessionId$=new se.ValueSubject(null);this.contentId$=new se.ValueSubject(null);this.isMobile=fi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var a,n,o;if((0,se.isNullable)(e))return;this.media=e,this.mediaSessionId$.next((a=e.mediaSessionId)!=null?a:null);let t=(n=e.media)==null?void 0:n.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=(o=e.media)==null?void 0:o.duration;(0,se.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,se.isNonNullable)(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let c=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!c?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new fn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Sa(e.format)),this.subscribe()}subscribe(){let e=r=>{var a;this.params.output.error$.next({category:se.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:(a=r==null?void 0:r.message)!=null?a:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,se.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,se.filter)(se.isNonNullable),(0,se.filterChanged)(),(0,se.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,se.filterChanged)(),(0,se.map)(Boolean));this.subscription.add((0,se.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,se.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,se.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,se.filter)(({mediaLoaded:r})=>r),(0,se.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,se.filter)(({mediaLoaded:r,playbackState:{from:a,to:n}})=>!r&&a==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,se.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,se.debounce)(30)),mediaLoaded:t}).pipe((0,se.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:n}=r.to;this.setVolume(n,a)},e))}handleMessage(e){var t,i,r,a,n,o;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let u=(i=(t=e.message)==null?void 0:t.media)==null?void 0:i[0];this.syncMediaState(u);let c=(r=e.message)==null?void 0:r.receiver.volume;this.syncVolumeState(c)}break;case"v2_message":{switch((a=e.message)==null?void 0:a.type){case"MEDIA_STATUS":{let u=(o=(n=e.message)==null?void 0:n.status)==null?void 0:o[0];this.syncMediaState(u);break}}break}}}loadMedia(){var o;let e=hn(this.params),t=(o=this.media)==null?void 0:o.currentTime,i=this.params.desiredState.seekState.getState(),r=t!=null?t:i.state!=="none"?i.position/1e3:0,n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();(0,se.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,se.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,se.assertNonNullable)(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":B(this.params.desiredState.playbackState,"paused");break;case"PLAYING":B(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),B(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):B(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if((0,se.isNullable)(e))return;let{level:t,muted:i}=e,r={muted:i!=null?i:!1,volume:t!=null?t:0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let a=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,a+=`, volume passed to state machine: ${r.volume}`),this.log({message:a}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};var he=require("@vkontakte/videoplayer-shared/es2018");var pf=s=>({castDevice:{friendlyName:s},remotePlayer:{},remotePlayerController:{},session:{}}),hf=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Ta=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new he.ValueSubject(null);this.sessionId$=new he.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new he.Subscription;this.subscriptionEvents=new he.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new he.ValueSubject(!1);this.presentationConnection$=new he.ValueSubject(null);this.message$=new he.ValueSubject(null);this.friendlyName$=new he.ValueSubject(null);this.errorEvent$=new he.Subject;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let a=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add((0,he.fromEvent)(r,"change").subscribe(()=>{a()})),a()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){var e;this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let t=this.presentationRequest$.getValue();(0,he.assertNonNullable)(t,"connect with null presentationRequest");let i=await t.start();this.handleConnection(i)}catch(t){switch(t==null?void 0:t.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:he.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}}subscribe(){this.subscription.add((0,he.fromEvent)(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe((0,he.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,he.filter)(e=>!!e)).subscribe(e=>{let t=(0,he.fromEvent)(e,"message").subscribe(a=>{let n=JSON.parse(a.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${a.data}`}),this.handleMessage(n),this.message$.next(n))}),i=(0,he.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,he.fromEvent)(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:he.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:a});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();(t==null?void 0:t.state)==="connected"&&(t==null||t.send(e))}catch(t){this.errorEvent$.next({category:he.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){var t;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":((t=e.message)==null?void 0:t.action)==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||hf()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new he.Subscription}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};var He=require("@vkontakte/videoplayer-shared/es2018");var Gt=class s{constructor(e){this.subscription=new He.Subscription;this.connection$=new He.ValueSubject(void 0);this.castState$=new He.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new He.Subject;let t=s.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Ta({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,He.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,He.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,He.filterChanged)())});this.subscription.add(e.pipe((0,He.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,He.filterChanged)()).subscribe(t=>{var r,a;let i=(a=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?a:"";this.connection$.next(t?pf(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){var e;this.log({message:"connect"}),(e=this.chromecastConnector)==null||e.connect()}disconnect(){var e;this.log({message:"disconnect"}),(e=this.chromecastConnector)==null||e.disconnect()}async stopMedia(){var e;this.log({message:"stopMedia"}),(e=this.chromecastConnector)==null||e.stopMedia()}toggleConnection(){var t;let e=!!((t=this.chromecastConnector)!=null&&t.presentationConnection$.getValue());this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){var e;this.log({message:"destroy"}),(e=this.chromecastConnector)==null||e.destroy(),this.subscription.unsubscribe()}};var zl=G(Xe(),1),Gl=G(bi(),1),Jy=G(oc(),1);var Qg=G(zc(),1);var Ot=require("@vkontakte/videoplayer-shared/es2018"),ae=class{constructor(e){this.transitionStarted$=new Ot.Subject;this.transitionEnded$=new Ot.Subject;this.transitionUpdated$=new Ot.Subject;this.forceChanged$=new Ot.Subject;this.stateChangeStarted$=(0,Ot.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Ot.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,Ot.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 ue=require("@vkontakte/videoplayer-shared/es2018");var fR=5,mR=5,bR=500,Wg=7e3,Da=class{constructor(e){this.subscription=new ue.Subscription;this.loadMediaTimeoutSubscription=new ue.Subscription;this.videoState=new ae("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,ue.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,ue.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,ue.assertNever)(e)}break}default:(0,ue.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(Sa(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 ue.Subscription;this.subscription.add(e),this.subscription.add((0,ue.merge)(this.videoState.stateChangeStarted$.pipe((0,ue.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,ue.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 ue.Subject;e.add(r.pipe((0,ue.debounce)(bR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,ue.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)>fR)&&r.next(o),a=o})),e.add((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,ue.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,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,ue.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<mR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),B(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,ue.assertNever)(n)}}),t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,ue.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=hn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,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()}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,ue.timeout)(Wg).subscribe(()=>a(`timeout(${Wg})`)))});(0,Qg.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:ue.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ul=G(Xe(),1);var Ba=require("@vkontakte/videoplayer-shared/es2018");var zg=require("@vkontakte/videoplayer-shared/es2018"),Gg=s=>{try{s.pause(),s.playbackRate=0,(0,zg.clearVideoElement)(s),s.remove()}catch(e){console.error(e)}};var Gn=require("@vkontakte/videoplayer-shared/es2018"),Gc=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},zn=(0,Ba.getWindow)(),Yc=zn.WeakMap?new zn.WeakMap:new Gc,Kc=zn.WeakMap?new zn.WeakMap:new Map,gR=(s,e=20)=>{let t=0;return(0,Gn.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Je=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?(0,Ba.clearVideoElement)(i):(i=document.createElement("video"),s.appendChild(i)),Yc.set(i,r);let a=new Gn.Subscription;return a.add(gR(i,e)),Kc.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},Ze=s=>{let e=Kc.get(s);e==null||e.unsubscribe(),Kc.delete(s);let t=Yc.get(s);Yc.delete(s),t?(0,Ba.clearVideoElement)(s):Gg(s)};var Xc=G(Hi(),1),z=require("@vkontakte/videoplayer-shared/es2018");var vi=require("@vkontakte/videoplayer-shared/es2018"),Yn=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,vi.isNullable)(r),c=new vi.Subscription;return r&&c.add(r.subscribe(d=>{let l=s.getState();i(d,l)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),c.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),c},Nt=(s,e,t)=>Yn(e,()=>s.loop,i=>{(0,vi.isNonNullable)(i)&&(s.loop=i)},{onError:t}),et=(s,e,t,i)=>Yn(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,vi.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}),ft=(s,e,t,i)=>Yn(e,()=>s.playbackRate,r=>{(0,vi.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Va=Yn;var vR=s=>["__",s.language,s.label].join("|"),SR=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Jc=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(Va(t.internalTextTracks,()=>(0,Xc.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(Va(t.externalTextTracks,()=>(0,Xc.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(Va(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(Va(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 c,d,l,p,h;let u=(d=(c=o.target)==null?void 0:c.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(l=o.target)==null?void 0:l.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,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,c,d,l;let{language:t,label:i}=e,r=e.id?e.id:vR(e),a=this.externalTracks.has(r),n=(c=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?c:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(l=this.internalTracks.get(r))==null?void 0:l.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto: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)||!SR(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)}},mt=Jc;var Xi=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 Yg=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},Zc=s=>{let e=Yg(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Kg=s=>{let e=Yg(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var L=require("@vkontakte/videoplayer-shared/es2018");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 tt=s=>{let e=V=>(0,L.fromEvent)(s,V).pipe((0,L.mapTo)(void 0),(0,L.shareReplay)(1)),t=new L.Subscription,i=()=>t.unsubscribe(),r=(0,L.merge)((0,L.fromEvent)(s,"progress"),(0,L.fromEvent)(s,"timeupdate")).pipe((0,L.map)(()=>Xg(s.buffered,s.currentTime)),(0,L.shareReplay)(1)),a=j.browser.isSafari?(0,L.combine)({play:e("play").pipe((0,L.once)()),playing:e("playing")}).pipe((0,L.mapTo)(void 0),(0,L.shareReplay)(1)):e("playing"),n=(0,L.fromEvent)(s,"volumechange").pipe((0,L.map)(()=>({muted:s.muted,volume:s.volume})),(0,L.shareReplay)(1)),o=(0,L.fromEvent)(s,"ratechange").pipe((0,L.map)(()=>s.playbackRate),(0,L.shareReplay)(1)),u=(0,L.fromEvent)(s,"error").pipe((0,L.filter)(()=>!!(s.error||s.played.length)),(0,L.map)(()=>{var Q;let V=s.error;return{id:V?`MediaError#${V.code}`:"HtmlVideoError",category:L.ErrorCategory.VIDEO_PIPELINE,message:V?V.message:"Error event from HTML video element",thrown:(Q=s.error)!=null?Q:void 0}}),(0,L.shareReplay)(1)),c=(0,L.fromEvent)(s,"timeupdate").pipe((0,L.map)(()=>s.currentTime),(0,L.shareReplay)(1)),d=["waiting","seeking","seeked","timeupdate"],l=new L.Subject,p=.3,h;t.add((0,L.merge)(...d.map(V=>(0,L.fromEvent)(s,V))).subscribe(V=>{let Q=s.currentTime;s.loop&&(0,L.isNonNullable)(h)&&(0,L.isNonNullable)(Q)&&h>=s.duration-p&&Q<=p&&l.next(h),h=Q}));let m=e("pause").pipe((0,L.filter)(()=>!s.error&&h!==s.duration),(0,L.shareReplay)(1)),b=(0,L.fromEvent)(s,"enterpictureinpicture").pipe((0,L.shareReplay)(1)),S=(0,L.fromEvent)(s,"leavepictureinpicture").pipe((0,L.shareReplay)(1)),v=new L.ValueSubject(Kg(s));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let y=new L.ValueSubject(Zc(s)),x=(0,L.fromEvent)(s,"fullscreenchange").pipe((0,L.shareReplay)(1));t.add(x.pipe((0,L.map)(()=>Zc(s))).subscribe(y));let w=.1,M=1e3,_=(0,L.fromEvent)(s,"timeupdate").pipe((0,L.map)(V=>s.duration-s.currentTime<w),(0,L.filterChanged)(),(0,L.shareReplay)(1)),F=(0,L.merge)(_.pipe((0,L.filter)(V=>!s.loop&&V)),(0,L.fromEvent)(s,"ended")).pipe((0,L.throttle)(M),(0,L.mapTo)(void 0),(0,L.shareReplay)(1)),H=(0,L.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(V=>(0,L.fromEvent)(s,V)),_.pipe((0,L.map)(V=>({type:V?"ended":"unknown"})))).pipe((0,L.map)(V=>j.browser.isFirefox&&V.type==="ended"?s.readyState<2:s.readyState<3),(0,L.filterChanged)(),(0,L.shareReplay)(1));return{playing$:a,pause$:m,canplay$:e("canplay"),ended$:F,looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,L.fromEvent)(s,"durationchange").pipe((0,L.map)(()=>s.duration),(0,L.shareReplay)(1)),isBuffering$:H,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:y,enterPip$:b,leavePip$:S,destroy:i}};var Kt=require("@vkontakte/videoplayer-shared/es2018"),Si=s=>{switch(s){case"mobile":return Kt.VideoQuality.Q_144P;case"lowest":return Kt.VideoQuality.Q_240P;case"low":return Kt.VideoQuality.Q_360P;case"sd":case"medium":return Kt.VideoQuality.Q_480P;case"hd":case"high":return Kt.VideoQuality.Q_720P;case"fullhd":case"full":return Kt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Kt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Kt.VideoQuality.Q_2160P}};var Ge=G(bt(),1),tl=G(Xe(),1),Ji=G(bi(),1),D=require("@vkontakte/videoplayer-shared/es2018");var el=!1,Xt={},av=s=>{el=s},sv=()=>{Xt={}},nv=s=>{s(Xt)},_a=(s,e)=>{var t;el&&(Xt.meta=(t=Xt.meta)!=null?t:{},Xt.meta[s]=e)},ze=class{constructor(e){this.name=e}next(e){var i,r;if(!el)return;Xt.series=(i=Xt.series)!=null?i:{};let t=(r=Xt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Xt.series[this.name]=t}};var $e=require("@vkontakte/videoplayer-shared/es2018");function ov(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Br(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 uv({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Br({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 hv=new ze("best_bitrate"),Xn=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Vr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),yi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,D.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Jn='Assertion "ABR Tracks is empty array" failed',Kn=new WeakMap,cv=new WeakMap,lv=new WeakMap,Oa=(s,e,t,i)=>{var u;let r=[...e].sort(Vr(1)),a=[...t].sort(Vr(1)),n=a.filter(c=>(0,D.isNonNullable)(c.bitrate)&&(0,D.isNonNullable)(s.bitrate)?s.bitrate/c.bitrate>i:!0),o=(u=(0,Ge.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Ge.default)(a,-1);return o&&(0,tl.default)(n,o)?o:n.length?(0,Ge.default)(n,-1):(0,Ge.default)(a,0)},Na=(s,e,t,i)=>{var u;let r=Kn.get(e);r||(r=[...e].sort(Vr(1)),Kn.set(e,r));let a=Kn.get(t);a||(a=[...t].sort(Vr(1)),Kn.set(t,a));let n=lv.get(s);n||(n=a.filter(c=>(0,D.isNonNullable)(c.bitrate)&&(0,D.isNonNullable)(s.bitrate)?s.bitrate/c.bitrate>i:!0),lv.set(s,n));let o=(u=(0,Ge.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Ge.default)(a,-1);return o&&(0,tl.default)(n,o)?o:n.length?(0,Ge.default)(n,-1):(0,Ge.default)(a,0)},dv=s=>"quality"in s,Zn=(s,e,t,i)=>{var n;let r=(0,D.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,D.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,D.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=dv(o)?"video":"audio",c=dv(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${c}
|
|
9
9
|
`}),o}return i==null||i.recordSwitch(t),t},RR=(s,e)=>Math.log(e)/Math.log(s),fv=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&j.display.pixelRatio){let a=j.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,c=0]=s.pixelRatioLogCoefficients,d=RR(n,o*a+u)+c;Number.isFinite(d)&&(r*=d)}}return(0,D.isNonNullable)(t==null?void 0:t.min)&&(0,D.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}},pv=new WeakMap,Ft=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{var ie,le,oe,A,$;(0,D.assertNotEmptyArray)(s,Jn);let{containerSizeFactor:S,containerSizeLimit:v}=fv({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,D.isNonNullable)(o)?o:1,x=pv.get(s);x||(x=s.filter(k=>!(0,D.isInvariantQuality)(k.quality)).sort((k,R)=>(0,D.isHigher)(k.quality,R.quality)?-1:1),pv.set(s,x));let w=(ie=(0,Ge.default)(x,-1))==null?void 0:ie.quality,M=(le=(0,Ge.default)(x,0))==null?void 0:le.quality,_=Br(r,M,w),F=y*Xn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),O={},H=null;for(let k of x){let R=!0;if(v)if(k.size)R=k.size.width<=v.width&&k.size.height<=v.height;else{let st=v&&(0,D.videoSizeToQuality)(v);R=st?(0,D.isLowerOrEqual)(k.quality,st):!0}if(!R){O[k.quality]="FitsContainer";continue}let Z=h||t,K=(0,D.isNonNullable)(Z)&&isFinite(Z)&&(0,D.isNonNullable)(k.bitrate)?Z-a>=k.bitrate*F:!0,Mt=(r==null?void 0:r.min)===k.quality;if(!K&&!Mt){O[k.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,D.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,D.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,D.isHigher)(k.quality,u.quality)){O[k.quality]="Buffer";continue}if(!!l&&(0,D.isHigherOrEqual)(k.quality,l)&&!Mt){O[k.quality]="DroppedFramesLimit";continue}if(!!p&&(0,D.isHigherOrEqual)(k.quality,p)&&!Mt){O[k.quality]="StallsLimit";continue}let Fe=_||((0,D.isNullable)(r==null?void 0:r.max)||(0,D.isLowerOrEqual)(k.quality,r.max))&&((0,D.isNullable)(r==null?void 0:r.min)||(0,D.isHigherOrEqual)(k.quality,r.min)),Ue=(0,D.isNonNullable)(d)&&!d?(0,D.isLowerOrEqual)(k.quality,i.backgroundVideoQualityLimit):!0;if(!Fe||!Ue){O[k.quality]="FitsQualityLimits";continue}H||(H=k)}H&&H.bitrate&&hv.next(H.bitrate);let V=(oe=H!=null?H:(0,Ge.default)(x,-1))!=null?oe:s[0],Q=c==null?void 0:c.last,N=Zn(i,m,V,c);return(0,D.isNonNullable)(c)&&N.quality!==(Q==null?void 0:Q.quality)&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
@@ -175,7 +175,7 @@ void main(void) {
|
|
|
175
175
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
176
176
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
177
177
|
(?:-(?<privateuse>(?:${e})))?
|
|
178
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var hy=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,Al.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,fy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Al.default)(t,n,(o,u)=>(0,Ya.isNullable)(a)?o:(0,Ya.isNullable)(u)?a:(0,my.default)(a,parseInt(u,10),"0"))}return t},yo=(s,e)=>{var H,V,Q,N,ie,le,oe,A,$,k,R,Z,K,Mt,$t,pe,Ne,Fe,Ue,st,Ht,Wt,$i,lr,Li,Zl,ed,td,id,rd,ad,sd,nd,od,ud,cd,ld,dd,pd,hd,fd,md,bd,gd,vd,Sd,yd,Td,Id,Ed,wd,xd,Pd,kd,Ad,Rd,Md,$d,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(yt=>{var ve,Ci;return(Ci=(ve=yt.textContent)==null?void 0:ve.trim())!=null?Ci:""}),o=(H=(0,by.default)(n,0))!=null?H:"",u=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),l=a.getElementsByTagName("vk:Attrs")[0],p=l==null?void 0:l.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=l==null?void 0:l.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=l==null?void 0:l.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=l==null?void 0:l.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:c?new Date(c).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,y=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],w=x.reduce((yt,ve)=>({...yt,[ve.id]:ve.children}),{}),M=x.reduce((yt,ve)=>({...yt,[ve.id]:ve.getAttribute("duration")}),{});y?v=hy(y):(0,Rl.default)(M).filter(yt=>yt).length&&!u?v=(0,Rl.default)(M).reduce((yt,ve)=>{var Ci;return yt+((Ci=hy(ve))!=null?Ci:0)},0):b&&(v=parseInt(b,10));let _=0,F=(Q=(V=a.getAttribute("profiles"))==null?void 0:V.split(","))!=null?Q:[];for(let yt of x.map(ve=>ve.id))for(let ve of w[yt]){let Ci=(N=ve.getAttribute("id"))!=null?N:"id"+(_++).toString(10),ea=(ie=ve.getAttribute("mimeType"))!=null?ie:"",Go=(le=ve.getAttribute("codecs"))!=null?le:"",Yo=(oe=ve.getAttribute("contentType"))!=null?oe:ea==null?void 0:ea.split("/")[0],pT=($=(A=ve.getAttribute("profiles"))==null?void 0:A.split(","))!=null?$:[],Bd=(R=py((k=ve.getAttribute("lang"))!=null?k:""))!=null?R:{},Fs=(Mt=(K=(Z=ve.querySelector("Label"))==null?void 0:Z.textContent)==null?void 0:K.trim())!=null?Mt:void 0,hT=ve.querySelectorAll("Representation"),fT=ve.querySelector("SegmentTemplate"),mT=(pe=($t=ve.querySelector("Role"))==null?void 0:$t.getAttribute("value"))!=null?pe:void 0,dr=Yo,Re={id:Ci,language:Bd.language,isDefault:mT==="main",label:Fs,codecs:Go,hdr:dr==="video"&&kl(Go),mime:ea,representations:[]};for(let me of hT){let si=(Ne=me.getAttribute("lang"))!=null?Ne:void 0,Us=(Ue=(Fe=Fs!=null?Fs:ve.getAttribute("label"))!=null?Fe:me.getAttribute("label"))!=null?Ue:void 0,qs=(Wt=(Ht=(st=me.querySelector("BaseURL"))==null?void 0:st.textContent)==null?void 0:Ht.trim())!=null?Wt:"",Di=new URL(qs||o,e).toString(),ni=($i=me.getAttribute("mimeType"))!=null?$i:ea,js=(Li=(lr=me.getAttribute("codecs"))!=null?lr:Go)!=null?Li:"",Hs;if(Yo==="text"){let oi=me.getAttribute("id")||"",Ws=((Zl=Bd.privateuse)==null?void 0:Zl.includes("x-auto"))||oi.includes("_auto"),Bi=me.querySelector("SegmentTemplate");if(Bi){let ta={representationId:(ed=me.getAttribute("id"))!=null?ed:void 0,bandwidth:(td=me.getAttribute("bandwidth"))!=null?td:void 0},Qs=parseInt((id=me.getAttribute("bandwidth"))!=null?id:"",10)/1e3,zs=(ad=parseInt((rd=Bi.getAttribute("startNumber"))!=null?rd:"",10))!=null?ad:1,pr=parseInt((sd=Bi.getAttribute("timescale"))!=null?sd:"",10),Ko=(nd=Bi.querySelectorAll("SegmentTimeline S"))!=null?nd:[],hr=Bi.getAttribute("media");if(!hr)continue;let Gs=[],Ys=0,Ks="",fr=0,ia=zs,Qe=0;for(let Tt of Ko){let Vi=parseInt((od=Tt.getAttribute("d"))!=null?od:"",10),ht=parseInt((ud=Tt.getAttribute("r"))!=null?ud:"",10)||0,ui=parseInt((cd=Tt.getAttribute("t"))!=null?cd:"",10);Qe=Number.isFinite(ui)?ui:Qe;let _i=Vi/pr*1e3,ci=Qe/pr*1e3;for(let Lt=0;Lt<ht+1;Lt++){let li=At(hr,{...ta,segmentNumber:ia.toString(10),segmentTime:(Qe+Lt*Vi).toString(10)}),mr=(ci!=null?ci:0)+Lt*_i,aa=mr+_i;ia++,Gs.push({time:{from:mr,to:aa},url:li})}Qe+=(ht+1)*Vi,Ys+=(ht+1)*_i}fr=Qe/pr*1e3,Ks=At(hr,{...ta,segmentNumber:ia.toString(10),segmentTime:Qe.toString(10)});let ra={time:{from:fr,to:1/0},url:Ks},Qt={type:"template",baseUrl:Di,segmentTemplateUrl:hr,initUrl:"",totalSegmentsDurationMs:Ys,segments:Gs,nextSegmentBeyondManifest:ra,timescale:pr};Hs={id:oi,kind:"text",segmentReference:Qt,profiles:[],duration:v,bitrate:Qs,mime:"",codecs:"",width:0,height:0,isAuto:Ws}}else Hs={id:oi,isAuto:Ws,kind:"text",url:Di}}else{let oi=(dd=(ld=me.getAttribute("contentType"))!=null?ld:ni==null?void 0:ni.split("/")[0])!=null?dd:Yo,Ws=(hd=(pd=ve.getAttribute("profiles"))==null?void 0:pd.split(","))!=null?hd:[],Bi=parseInt((fd=me.getAttribute("width"))!=null?fd:"",10),ta=parseInt((md=me.getAttribute("height"))!=null?md:"",10),Qs=parseInt((bd=me.getAttribute("bandwidth"))!=null?bd:"",10)/1e3,zs=(gd=me.getAttribute("frameRate"))!=null?gd:"",pr=(vd=me.getAttribute("quality"))!=null?vd:void 0,Ko=zs?dy(zs):void 0,hr=(Sd=me.getAttribute("id"))!=null?Sd:"id"+(_++).toString(10),Gs=oi==="video"?`${ta}p`:oi==="audio"?`${Qs}Kbps`:js,Ys=`${hr}@${Gs}`,Ks=[...F,...pT,...Ws],fr,ia=me.querySelector("SegmentBase"),Qe=(yd=me.querySelector("SegmentTemplate"))!=null?yd:fT;if(ia){let Qt=(Id=(Td=me.querySelector("SegmentBase Initialization"))==null?void 0:Td.getAttribute("range"))!=null?Id:"",[Tt,Vi]=Qt.split("-").map(li=>parseInt(li,10)),ht={from:Tt,to:Vi},ui=(Ed=me.querySelector("SegmentBase"))==null?void 0:Ed.getAttribute("indexRange"),[_i,ci]=ui?ui.split("-").map(li=>parseInt(li,10)):[],Lt=ui?{from:_i,to:ci}:void 0;fr={type:"byteRange",url:Di,initRange:ht,indexRange:Lt}}else if(Qe){let Qt={representationId:(wd=me.getAttribute("id"))!=null?wd:void 0,bandwidth:(xd=me.getAttribute("bandwidth"))!=null?xd:void 0},Tt=parseInt((Pd=Qe.getAttribute("timescale"))!=null?Pd:"",10),Vi=(kd=Qe.getAttribute("initialization"))!=null?kd:"",ht=Qe.getAttribute("media"),ui=(Rd=parseInt((Ad=Qe.getAttribute("startNumber"))!=null?Ad:"",10))!=null?Rd:1,_i=At(Vi,Qt);if(!ht)throw new ReferenceError("No media attribute in SegmentTemplate");let ci=(Md=Qe.querySelectorAll("SegmentTimeline S"))!=null?Md:[],Lt=[],li=0,mr="",aa=0;if(ci.length){let Xs=ui,It=0;for(let br of ci){let Ct=parseInt(($d=br.getAttribute("d"))!=null?$d:"",10),Oi=parseInt((Ld=br.getAttribute("r"))!=null?Ld:"",10)||0,Js=parseInt((Cd=br.getAttribute("t"))!=null?Cd:"",10);It=Number.isFinite(Js)?Js:It;let Xo=Ct/Tt*1e3,Jo=It/Tt*1e3;for(let Zs=0;Zs<Oi+1;Zs++){let gT=At(ht,{...Qt,segmentNumber:Xs.toString(10),segmentTime:(It+Zs*Ct).toString(10)}),Vd=(Jo!=null?Jo:0)+Zs*Xo,vT=Vd+Xo;Xs++,Lt.push({time:{from:Vd,to:vT},url:gT})}It+=(Oi+1)*Ct,li+=(Oi+1)*Xo}aa=It/Tt*1e3,mr=At(ht,{...Qt,segmentNumber:Xs.toString(10),segmentTime:It.toString(10)})}else if((0,Ya.isNonNullable)(v)){let It=parseInt((Dd=Qe.getAttribute("duration"))!=null?Dd:"",10)/Tt*1e3,br=Math.ceil(v/It),Ct=0;for(let Oi=1;Oi<br;Oi++){let Js=At(ht,{...Qt,segmentNumber:Oi.toString(10),segmentTime:Ct.toString(10)});Lt.push({time:{from:Ct,to:Ct+It},url:Js}),Ct+=It}aa=Ct,mr=At(ht,{...Qt,segmentNumber:br.toString(10),segmentTime:Ct.toString(10)})}let bT={time:{from:aa,to:1/0},url:mr};fr={type:"template",baseUrl:Di,segmentTemplateUrl:ht,initUrl:_i,totalSegmentsDurationMs:li,segments:Lt,nextSegmentBeyondManifest:bT,timescale:Tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!oi||!ni)continue;let ra={video:"video",audio:"audio",text:"text"}[oi];if(!ra)continue;dr||(dr=ra),Hs={id:Ys,kind:ra,segmentReference:fr,profiles:Ks,duration:v,bitrate:Qs,mime:ni,codecs:js,width:Bi,height:ta,fps:Ko,quality:pr}}Re.language||(Re.language=si),Re.label||(Re.label=Us),Re.mime||(Re.mime=ni),Re.codecs||(Re.codecs=js),Re.hdr||(Re.hdr=dr==="video"&&kl(js)),Re.representations.push(Hs)}if(dr){let me=r[dr].find(si=>si.id===Re.id);if(me&&Re.representations.every(si=>si.segmentReference.type==="template"))for(let si of me.representations){let Us=Re.representations.find(ni=>ni.id===si.id);if(!Us)continue;let qs=Us.segmentReference,Di=si.segmentReference;Di.segments.push(...qs.segments),Di.nextSegmentBeyondManifest=qs.nextSegmentBeyondManifest}else r[dr].push(Re)}}return{duration:v,streams:r,baseUrls:n,live:S}};var Io=G(bt(),1),Ml=G(Xe(),1),Xa=require("@vkontakte/videoplayer-shared/es2018");var Ka=(a=>(a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient",a))(Ka||{});var To=s=>{let{webmDecodingInfo:e}=j.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,Xa.assertNever)(s)}},gy=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...To(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(j.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",...To(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...To(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...To(s),...a,"HLS","HLS_ONDEMAND"];default:(0,Xa.assertNever)(e)}if(j.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,Xa.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},vy=({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=j.device.isMac&&j.browser.isSafari;if(j.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,Xa.assertNever)(s)}else j.video.nativeHlsSupported&&!u&&!j.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},$l=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Eo=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Io.default)(t.value.split("."),0)}for(let t of s){let i=(0,Io.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Io.default)(e.value.split("."),0)},wo=s=>{let e=s.map(i=>jr(i)),{codecs:t}=j.video;return R$().filter(i=>{if((0,Ml.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})},xo=s=>{let e=s.map(i=>jr(i)),{codecs:t}=j.video;return M$().filter(i=>{if((0,Ml.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},jr=s=>s.split(".")[0].replace("0",""),R$=()=>["av1","vp9","hev1","avc1"],M$=()=>["opus","mp4a"];var Cy=G(bt(),1);var $$=(s,e={})=>{let i=e.timeout||1,r=performance.now();return Le.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},L$=s=>Le.clearTimeout(s),Sy=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),yy=!Sy(Le.requestIdleCallback)||!Sy(Le.cancelIdleCallback),ir=yy?$$:Le.requestIdleCallback,rr=yy?L$:Le.cancelIdleCallback;var C=require("@vkontakte/videoplayer-shared/es2018");var Iy=G(bt(),1);var Po=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 Hr=class extends ce{};var Ty=require("@vkontakte/videoplayer-shared/es2018");var Ja=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,Ty.assertNever)(e)}}};var Za=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 es=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ie=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 ts=class extends Ie{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 is=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rs=class extends ce{constructor(e,t){super(e,t),this.data=this.content}};var ar=class extends Ie{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,c=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var as=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ss=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ns=class extends Ie{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 os=class extends Ie{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var us=class extends Ie{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 cs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ls=class extends Ie{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 ds=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ps=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hs=class extends Ie{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var fs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ms=class extends Ie{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 bs=class extends Ie{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 gs=class extends Ie{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 vs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ss=class extends Ie{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 ys=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 D$={ftyp:Za,moov:es,mvhd:ts,moof:is,mdat:rs,sidx:ar,trak:as,mdia:cs,mfhd:hs,tkhd:ls,traf:fs,tfhd:ms,tfdt:bs,trun:gs,minf:ds,sv3d:ss,st3d:ns,prhd:os,proj:ps,equi:us,uuid:Ja,stbl:vs,stsd:Ss,avc1:ys,unknown:Hr},Zt=class s{constructor(e={}){this.options={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||!Po(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=D$[e];return i?new i(t,new s):new Hr(t,new s)}};var wi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;Po(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 V$=new TextDecoder("ascii"),_$=s=>V$.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",O$=s=>{let e=new ar(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})},N$=(s,e)=>{let i=new Zt().parse(s),r=new wi(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],c=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,c,l)},F$=s=>{let t=new Zt().parse(s),i=new wi(t),r={},a=i.findAll("uuid"),n=(0,Iy.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},U$=s=>{var r;let t=new Zt().parse(s);return(r=new wi(t).find("sidx"))==null?void 0:r.timescale},q$=(s,e)=>{let i=new Zt().parse(s),a=new wi(i).findAll("traf"),n=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),u=a[a.length-1].children.find(l=>l.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((l,p)=>l+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},j$=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 wi(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},Ey={validateData:_$,parseInit:j$,getIndexRange:()=>{},parseSegments:O$,parseFeedableSegmentChunk:N$,getChunkEndTime:q$,getServerLatencyTimestamps:F$,getTimescaleFromIndex:U$};var Is=G(Xe(),1),ei=require("@vkontakte/videoplayer-shared/es2018");var xy=require("@vkontakte/videoplayer-shared/es2018");var wy={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"}},Py=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=Ts(s,t),r=i in wy,a=r?wy[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),c=n&255>>o,d=Ts(u),l=c*2**((o-1)*8)+d,p=t+o,h;return p+l>s.byteLength?h=new DataView(s.buffer,s.byteOffset+p):h=new DataView(s.buffer,s.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},Ts=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*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},Rt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Ts(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,xy.assertNever)(e)}},sr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Py(i);if(!e(r))return;r.type==="master"&&sr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},ky=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Py(s);return sr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Rt(o,n):a===17026?t=Rt(o,n):a===17029&&(i=Rt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ay=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],H$=[231,22612,22743,167,171,163,160,175],W$=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,c,d=!1,l=0;return sr(s,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=Rt(m,h);c=Ts(S)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?a=!0:p===290298740?n=!0:p===2807729?i=Rt(m,h):p===17545?r=Rt(m,h):p===21420&&c===475249515?u=Rt(m,h):p===374648427?sr(m,({tag:S,type:v,value:y})=>S===30321?(d=Rt(y,v)===1,!1):!0):a&&n&&(0,Is.default)(Ay,p)&&(o=!0),!o}),(0,ei.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,ei.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,ei.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Q$=s=>{if((0,ei.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},z$=(s,e)=>{let t=!1,i=!1,r=o=>(0,ei.isNonNullable)(o.time)&&(0,ei.isNonNullable)(o.position),a=[],n;return sr(s,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Rt(c,u));break;case 183:break;case 241:n&&(n.position=Rt(c,u));break;default:t&&(0,Is.default)(Ay,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:c,position:d}=o,l=a[u+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},G$=s=>{let e=0,t=!1;try{sr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Is.default)(H$,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,Is.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},Ry={validateData:ky,parseInit:W$,getIndexRange:Q$,parseSegments:z$,parseFeedableSegmentChunk:G$};var nr=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ry;case"mp4":return Ey}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Ll=G(bt(),1);var My=require("@vkontakte/videoplayer-shared/es2018"),xi=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Si(a):void 0)!=null?u:(0,My.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Es=({id:s,bitrate:e})=>({id:s,bitrate:e}),$y=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ly=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Cl=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Ll.default)(i.split("."),0),isDefault:r}),Dl=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Ll.default)(r.split("."),0)}),Bl=s=>"url"in s,dt=s=>s.type==="template";var Wr=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,getCurrentStallDuration:o,manifest:u}){this.error$=new C.Subject;this.playingRepresentation$=new C.ValueSubject(void 0);this.playingRepresentationInit$=new C.ValueSubject(void 0);this.currentSegmentLength$=new C.ValueSubject(0);this.onLastSegment$=new C.ValueSubject(!1);this.fullyBuffered$=new C.ValueSubject(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new ye;this.downloadAbortController=new ye;this.subscription=new C.Subscription;this.startWith=(0,C.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,C.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=nr(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,C.assertNonNullable)(i,"No init buffer for starting representation"),(0,C.assertNonNullable)(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a)}.bind(this));this.switchTo=(0,C.abortable)(this.destroyAbortController.signal,async function*(e,t=!0){var l;if((0,C.isNullable)(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);(0,C.assertNonNullable)(r,`No such representation ${e}`),(0,C.assertNonNullable)(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let a=this.initData.get(r.id),n=this.segments.get(r.id);(0,C.assertNonNullable)(a,"No init buffer for switching representation"),(0,C.assertNonNullable)(n,"No segments for switching representation");let o=(l=this.getCurrentPosition())!=null?l:0,u=p=>p.segment.bufferStatus!=="fed",c=p=>{let h=this.representations.get(p.representationId);return(0,C.assertNonNullable)(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},d=p=>t?u(p)&&c(p):u(p);this.bufferPlaybackQueue.filter(d).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!d(p)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=(0,C.abortable)(this.downloadAbortController.signal,async function*(){let e=(0,C.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,C.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,C.fromEvent)(i,"online").pipe((0,C.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));var c;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=n,this.getCurrentStallDuration=o,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=(c=u==null?void 0:u.baseUrls)!=null?c:[],this.representations=new Map(i.map(d=>[d.id,d]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){(0,C.isNullable)(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.bufferPlaybackQueue.filter(a=>a.segment.networkStatus==="downloaded"),i=t[t.length-1],r=(0,C.isNonNullable)(e)&&(0,C.isNonNullable)(i)?i.segment.time.to-e:0;return Math.max(r,0)}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){var a,n;let t=(n=(a=this.downloadingRepresentationId)!=null?a:this.playingRepresentationId)!=null?n:"",i=this.segments.get(t),r=i==null?void 0:i.find(o=>o.time.from<=e&&o.time.to>=e);return r==null?void 0:r.time.from}getRepresentationInitialTime(){var t;if((0,C.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return((t=e==null?void 0:e[0].time.from)!=null?t:0)/1e3}calculateDurationFromSegments(e){var i;let t=this.segments.get(e);return(t?(i=(0,Cy.default)(t,-1))==null?void 0:i.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,C.getWindow)();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.__polyfill_cancelIdleCallback_b64fbheibhf)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_b64fbheibhf(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=xi(e),a=xi(t);i=(0,C.isNonNullable)(r)&&(0,C.isNonNullable)(a)&&(0,C.isHigher)(a.quality,r.quality)}else if(this.kind==="audio"){let r=Es(e),a=Es(t);i=(0,C.isNonNullable)(r==null?void 0:r.bitrate)&&(0,C.isNonNullable)(a==null?void 0:a.bitrate)&&a.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new ye,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,ir(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),a;this.initData.has(e.id)&&this.segments.has(e.id)?a=Promise.resolve():(0,C.isNonNullable)(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){var r;try{let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a);this.initDataPromises.set(e.id,n);let{initMetadata:o,initDataView:u,segments:c}=(r=await n)!=null?r:{};if(this.initDataPromises.delete(e.id),(0,C.isNullable)(u)||(0,C.isNullable)(c))return;o&&this.parsedInitData.set(e.id,o);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d),this.segments.set(e.id,c),this.failedDownloads=0}catch(a){i&&this.error$.next({id:"LoadInits",category:C.ErrorCategory.WTF,message:"loadInit threw",thrown:a})}}async maintainNativeBuffer(){var h,m,b;let e=this.getCurrentPosition(),t=this.segments.get((h=this.downloadingRepresentationId)!=null?h:""),i=t==null?void 0:t[(t==null?void 0:t.length)-1];if((0,C.isNullable)(e)||(0,C.isNullable)(i)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let r=this.bufferPlaybackQueue.find(S=>this.withinInterval(e,S.segment.time)),a=this.bufferPlaybackQueue.find(S=>S.segment.bufferStatus!=="fed"),n=this.initData.get((m=a==null?void 0:a.representationId)!=null?m:""),o=this.bufferPlaybackQueue[0],u=this.downloadAbortController.signal,d=((b=this.getCurrentStallDuration())!=null?b:0)>0;this.tuning.dash.useBufferHoldingOnlyOnStall&&d&&(d=e>0);let l=Math.min(this.tuning.dash.minSafeBufferToPlay,i.time.to-e),p=d?this.getForwardPlaybackBufferDuration()>=l:!0;(0,C.isNonNullable)(n)&&(0,C.isNonNullable)(a)&&(0,C.isNonNullable)(r)&&this.playingRepresentationId!==a.representationId&&this.withinAppendInterval(e,a.segment.time)&&(a===r||r.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(n,this.downloadAbortController.signal),this.playingRepresentationId=a.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,C.isNonNullable)(a)&&this.withinAppendInterval(e,a.segment.time)&&p&&(a.segment.loadedBytes===a.segment.size&&a.segment.bufferStatus==="none"?await this.appendSegmentFully(a,u):await this.appendSegmentPartially(a,u)),(0,C.isNonNullable)(o)&&this.withinRemoveInterval(e,o.segment.time)&&await this.removeSegment(o,u),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){(0,C.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,C.isNullable)(t)||(0,C.isNullable)(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);(0,C.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let a=this.selectItemsToLoad();await this.loadItems(a,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if((0,C.isNullable)(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];(0,C.isNullable)(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){(0,C.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;(0,C.isNonNullable)(i)&&this.withinInterval(e,i)?(a=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(a=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&a>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;a-=u-o,r++}return n}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return(0,C.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,C.isNonNullable)(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return(0,C.isNonNullable)(e)?e-i>t:!1}async appendSegmentFully(e,t){if((0,C.isNullable)(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if((0,C.isNullable)(e.segment.data)||(0,C.isNullable)(e.segment.loadedBytes)||(0,C.isNullable)(e.segment.feedingBytes)||(0,C.isNullable)(e.segment.fedBytes)||(0,C.isNullable)(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),a=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;a!=null&&a.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=a.byteLength,await this.nativeBufferManager.append(a,t)&&(e.segment.fedBytes+=a.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,a=(r-i)/4;await this.nativeBufferManager.remove(0,r-a,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||(0,C.isNonNullable)(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let a=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)(0,C.isNonNullable)(o.size)&&a>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())(0,C.isNonNullable)(o.size)&&a>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size)}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())this.updateRepresentationBaseUrl(t,e)}};var qt=require("@vkontakte/videoplayer-shared/es2018");var ko=class extends Wr{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(a,{...n,priority:i}),this.lastDataObtainedTimestampMs=(0,qt.now)(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),kt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,a=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=a);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(_e(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,a={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:a,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=(0,qt.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:qt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:a,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||(0,qt.isNullable)(o)||(0,qt.isNullable)(r)||n.aborted))for(let u of e){let{segment:c}=u,d=c.byte.from-r,l=c.byte.to-r,p=l-d+1,h=d<a,m=l<=a;c.size=p,h&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&m?(c.data=new DataView(t.buffer,t.byteOffset+d,p),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u),c.loadedBytes=Math.min(p,a-d),await this.onDownloadItem(u)):(0,qt.isNonNullable)(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,a-d),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+d,c.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(_e(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var ti=require("@vkontakte/videoplayer-shared/es2018");var Qr=class extends Wr{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(a,{...n,priority:i});if(this.lastDataObtainedTimestampMs=(0,ti.now)(),(0,ti.isNullable)(o))return;let u=e[0],c=new DataView(o);u.segment.size=c.byteLength,u.segment.loadedBytes=c.byteLength,u.segment.data=c,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),kt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(n,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=(0,ti.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:ti.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!_e(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:a}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||(0,ti.isNullable)(u)||(0,ti.isNullable)(o.feedingBytes)||o.networkStatus!=="downloading"||a.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(n)))}updateRepresentationBaseUrl(e,t){if(!_e(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var Vl=G(Qa(),1),Dy=G(bt(),1);var Oe=require("@vkontakte/videoplayer-shared/es2018");var Ao=class extends Qr{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new Oe.ValueSubject(0);this.currentLowLatencySegmentLength$=new Oe.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){var r,a,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,Vl.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if((0,Oe.isNullable)(o)||!_e(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),c=100,d=(r=this.segments.get(o.id))!=null?r:[],l=(n=(a=(0,Dy.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>l>=h.time.from+c&&l<=h.time.to+c);if(p===-1){let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...d,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Oe.assertNonNullable)(t);let i=this.segments.get(t);if(i!=null&&i.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t==null?void 0:t.streams[this.kind],r=(0,Vl.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Oe.isNullable)(r))return;let a=this.segments.get(r.id);if(a!=null&&a.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){var r;if((0,Oe.isNullable)(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return(0,Oe.isNullable)(t)||!_e(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),(0,Oe.isNullable)(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:a,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);a&&n&&this.currentLiveSegmentServerLatency$.next(n-a),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){var n;let i=t.segment.data,r=(n=this.representations.get(t.representationId))==null?void 0:n.segmentReference;if((0,Oe.isNullable)(t.segment.data)||(0,Oe.isNullable)(r)||!_e(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=a.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let a of this.representations.values()){let n=a.segmentReference;if(!_e(n))return;let o=(r=this.segments.get(a.id))!=null?r:[],u=o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.from));if(u!=null&&u.isCurrentLowLatency&&(u.time.to=t.segment.time.to,i=u.time.to-u.time.from,u.isCurrentLowLatency=!1),!!!o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let d=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),l=At(n.segmentTemplateUrl,{segmentTime:d});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:l,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){var a;try{let n=this.tuning.dash.useFetchPriorityHints?i:"auto",o=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,n);this.initDataPromises.set(t.id,o);let{initMetadata:u,initDataView:c,segments:d}=(a=await o)!=null?a:{};if(this.initDataPromises.delete(t.id),(0,Oe.isNullable)(c)||(0,Oe.isNullable)(d))return;u&&this.parsedInitData.set(t.id,u);let l=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,l);let p=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(t.id,p),this.failedDownloads=0}catch(n){r&&this.error$.next({id:"LoadInits",category:Oe.ErrorCategory.WTF,message:"loadInit threw",thrown:n})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],n=0,o=i.length-1;do a.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[a[0]]:a}};var ws=class{static getBufferManager(e,t,i,r){var a;return(a=r.manifest)!=null&&a.live?new Ao(e,t,i,r):_e(i[0].segmentReference)?new Qr(e,t,i,r):new ko(e,t,i,r)}};var Ye=require("@vkontakte/videoplayer-shared/es2018");var Pi=require("@vkontakte/videoplayer-shared/es2018");var Y$=18,By=!1;try{By=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=Y$}catch(s){console.error(s)}var _l=class{constructor(e,t=!1){this.bufferFull$=new Pi.Subject;this.error$=new Pi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Pi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){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()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};By&&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.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:Pi.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,Pi.assertNever)(t)}}},Vy=_l;var ki=(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 xs=class{constructor(e){this.error$=new Ye.Subject;this.subscription=new Ye.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Vy(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,Ye.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ye.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if((0,Ye.isNullable)(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&(i=await this.sourceBufferTaskQueue.remove(r.from,r.to,e));return i}warmUpMediaSource(){!(0,Ye.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,Ye.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return(0,Ye.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,Ye.isNullable)(e)?0:ki(this.sourceBuffer.buffered,e)}async abortBuffer(e){return(0,Ye.isNullable)(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){var e;if(this.subscription.unsubscribe(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null}};var Ro=(s,e)=>{s.video.forEach(t=>{let i=t.representations.filter(({fps:r,height:a})=>{var o;let n=(o=e.find(([u])=>u===`${a}p`))==null?void 0:o[1];return n&&Number.isInteger(n)&&r&&Number.isInteger(r)?r<=n:!0});t.representations=i})};var K$=["timeupdate","progress","play","seeked","stalled","waiting"],_y=["timeupdate","progress","loadeddata","playing","seeked"],zr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new I.Subscription;this.subscriptionRemovable=new I.SubscriptionRemovable;this.representationSubscription=new I.Subscription;this.forceEnded$=new I.Subject;this.destroyController=new ye;this.state$=new ae("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.lastConnectionMetrics$=new I.ValueSubject(void 0);this.lastDownloadMetrics$=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.currentBuffer$=new I.ValueSubject({from:0,to:0});this.bufferLength$=new I.ValueSubject(0);this.nativeBufferLength$=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.initRepresentations=(0,I.abortable)(this.destroyController.signal,async function*(e,t,i){var a;this.tracer.log("initRepresentationsStart",(0,I.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,getCurrentStallDuration:()=>this.currentStallDuration$.getValue(),isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),(0,I.assertNonNullable)(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?(a=this.audioBufferManager)==null?void 0:a.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=(0,I.abortable)(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){(0,I.isNullable)(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new go({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){var r;this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await 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"})}initBuffer(){var t,i;(0,I.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,I.merge)(...K$.map(r=>(0,I.fromEvent)(this.element,r)),(0,I.fromEvent)((0,I.getWindow)(),"online"),(0,I.interval)(this.tuning.dash.tickMaintainInterval)).subscribe(()=>this.tick(),r=>this.error$.next({id:"DashVKPlayer",category:I.ErrorCategory.WTF,message:"Internal logic error",thrown:r})));let e=[...(i=(t=this.source)==null?void 0:t.activeSourceBuffers)!=null?i:[]];this.subscription.add((0,I.merge)(...e.map(r=>(0,I.fromEvent)(r,"updateend"))).subscribe(r=>this.reinitDecoderIfNeeded())),this.subscription.add((0,I.fromEvent)(this.element,"waiting").subscribe(r=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,I.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),a=>this.error$.next({id:"StallWatchdogCallback",category:I.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:a})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}async seek(e,t=!1){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),this.element.currentTime=i/1e3,j.browser.isSafari?(await((o=this.audioBufferManager)==null?void 0:o.seek(i)),await this.videoBufferManager.seek(i)):(await this.videoBufferManager.seek(i),await((u=this.audioBufferManager)==null?void 0:u.seek(i))),this.tracer.log("seek",(0,I.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){(0,I.isNonNullable)(this.element)&&(0,I.isNonNullable)(this.source)&&(0,I.isNonNullable)(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(i=>i.warmUpMediaSource())}calculateDurationFromSegments(e){var t,i;return Math.max(((t=this.videoBufferManager)==null?void 0:t.calculateDurationFromSegments(e))||0,((i=this.audioBufferManager)==null?void 0:i.calculateDurationFromSegments(e))||0)}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(r=>r.destroy()),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&(0,I.getWindow)().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),(0,I.isNonNullable)(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){var e;return((e=this.source)==null?void 0:e.readyState)!=="open"}async reinitDecoderIfNeeded(e=!1){var r,a;let t=(a=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?a:[];if((0,I.isNullable)(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(n=>i>=n.from&&i<=n.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){(0,I.assertNonNullable)(this.element),(0,I.assertNonNullable)(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t)){if(this.tuning.dash.useNewStallExitPolicy)return this.seek(this.element.currentTime*1e3);throw new Error(`Stall timeout exceeded: ${t} ms`)}await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",(0,I.flattenObject)(i))}isStallExceeded(e){var p,h,m,b,S,v,y,x;let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=(0,I.now)(),a=100,n=(h=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?h:0;this.videoLastDataObtainedTimestamp$.next(n);let o=(b=(m=this.audioBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0,u=(v=(S=this.videoBufferManager)==null?void 0:S.getForwardPlaybackBufferDuration())!=null?v:0,c=(x=(y=this.audioBufferManager)==null?void 0:y.getForwardPlaybackBufferDuration())!=null?x:0,d=(0,I.isNonNullable)(this.videoBufferManager)&&u<a&&r-n>i,l=(0,I.isNonNullable)(this.audioBufferManager)&&c<a&&r-o>i;return(d||l)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if((0,I.isNullable)(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",(0,I.flattenObject)(i)),i}parseManifest(e){var t;try{return yo(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=ho(e))!=null?t:{id:"ManifestParsing",category:I.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:i};this.error$.next(r)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,c)=>{var d,l,p,h;return!!((l=(d=this.element)==null?void 0:d.canPlayType)!=null&&l.call(d,u)&&((h=(p=ut())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${c}"`))||o==="text")},r,a;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));t[o]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);o==="audio"&&(a=xo(l),d=a[0]),o==="video"&&(r=wo(l),this.forceVideoCodec&&(0,Oy.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=c.filter(({codecs:p})=>jr(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=Eo(l),d&&(t[o]=c.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=t.video.some(b=>b.hdr),h=t.video.some(b=>!b.hdr);j.display.isHDR&&l&&p?t.video=t.video.filter(b=>b.hdr):h&&(t.video=t.video.filter(b=>!b.hdr));let{videoStreamRepresentaionsFilter:m}=this.tuning.dash;m.length&&Ro(t,m)}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:a}),n}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){(0,I.assertNonNullable)(this.manifest),(0,I.assertNonNullable)(this.element);let a=c=>{this.representationSubscription.add((0,I.fromEvent)(c,"error").pipe((0,I.filter)(d=>{var l;return!!((l=this.element)!=null&&l.played.length)})).subscribe(d=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=vn();let n=(0,I.getWindow)().document,o=n.createElement("source");if(a(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),xr())if(r){let c=n.createElement("source");a(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new xs(this.source),this.videoBufferManager=ws.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,I.isNonNullable)(i)){this.audioNativeBufferManager=new xs(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=ws.getBufferManager("audio",this.audioNativeBufferManager,c,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{var i;e&&(this.timeoutSourceOpenId=(0,I.getWindow)().setTimeout(()=>{if(this.isStreamNotOpen){t();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)),(i=this.source)==null||i.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&(0,I.getWindow)().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add((0,I.merge)(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),(0,I.assertNonNullable)(this.videoBufferManager),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add((0,I.merge)(..._y.map(e=>(0,I.fromEvent)(this.element,e))).pipe((0,I.map)(e=>{var t;return(t=this.videoBufferManager)==null?void 0:t.getPlaybackBufferState()}),(0,I.filter)(I.isNonNullable),(0,I.map)(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add((0,I.merge)(..._y.map(e=>(0,I.fromEvent)(this.element,e))).pipe((0,I.map)(e=>{var t,i,r,a,n,o;return Math.min((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(a=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?a:0,(o=(n=this.audioBufferManager)==null?void 0:n.getForwardPlaybackBufferDuration())!=null?o:0)}),(0,I.filterChanged)()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe((0,I.filter)(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=(0,I.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){var r,a,n;if((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((a=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?a:[]).find(o=>e>=o.from&&e<=o.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await((n=this.audioBufferManager)==null?void 0:n.maintain(e))}};var fe=require("@vkontakte/videoplayer-shared/es2018");var Mo=class extends zr{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;(0,fe.assertNonNullable)(this.manifest),(0,fe.assertNonNullable)(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,Ol.default)((0,Ol.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),_e(i.segmentReference)&&i.segmentReference.totalSegmentsDurationMs&&r.push(i.segmentReference.totalSegmentsDurationMs),r})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){var i,r;(0,fe.assertNonNullable)(this.element);let t=this.element.currentTime*1e3;await Promise.all([(i=this.videoBufferManager)==null?void 0:i.maintain(t),(r=this.audioBufferManager)==null?void 0:r.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){(0,fe.assertNonNullable)(this.element);let e=(0,fe.merge)((0,fe.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,fe.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,fe.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,fe.merge)(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe((0,fe.map)(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=(0,fe.merge)(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe((0,fe.map)(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=(0,fe.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,fe.filterChanged)(),(0,fe.map)(({allBuffersFull:a,someBufferEnded:n})=>a&&n),(0,fe.filter)(a=>a)),r=()=>{var a;try{(a=this.source)==null||a.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:fe.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add((0,fe.merge)(this.forceEnded$,i).pipe((0,fe.filter)(a=>(0,fe.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var Ps=class extends Zi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,Gr.filterChanged)(),(0,Gr.filter)(a=>(0,Gr.isNonNullable)(a))).subscribe(a=>{let n=this.player.calculateDurationFromSegments(a);n&&this.params.output.duration$.next(n/1e3)},r))}getPlayer(){return new Mo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var be=require("@vkontakte/videoplayer-shared/es2018");var ks=require("@vkontakte/videoplayer-shared/es2018"),Ai=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 ks.ValueSubject(e.initial),this.debounced$=new ks.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ze(`raw_${t}`),this.smoothedSeries$=new ze(`smoothed_${t}`),this.reportedSeries$=new ze(`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+=(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,ks.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 $o=class extends Ai{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Jt(this.slow,e,this.params.emaAlphaSlow),this.fast=Jt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Lo=class extends Ai{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=pl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Jt(this.emaSmoothed,e,this.params.emaAlpha);let i=Dv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Co=class extends Ai{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?Jt(this.smoothed,t,this.params.emaAlpha):t}};var ii=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new $o({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Lo({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 Co({initial:e,label:"liveEdgeDelay",...t})}};var Y=require("@vkontakte/videoplayer-shared/es2018");var Yr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var Do=require("@vkontakte/videoplayer-shared/es2018");var As=class s{constructor(e,t){this.currentRepresentation$=new Do.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,Do.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 c=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.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&&_e(t.segmentReference))}};var Bo=class extends zr{constructor(t){super(t);this.liveStreamEndTimestamp=0;this.liveWasInterrupted=!1;this.liveBuffer=ii.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...t.tuning.dashCmafLive.lowLatency.bufferEstimator})}async seek(t){(0,Y.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(t),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()}initBuffer(){super.initBuffer(),this.forcePositionToRepresentationInitialTime()}async forcePositionToRepresentationInitialTime(){var r;let t=this.videoBufferManager,i=(r=t==null?void 0:t.getRepresentationInitialTime())!=null?r:0;await super.seek(i,!1)}async tick(){var i,r,a;await super.tick();let t=((r=(i=this.element)==null?void 0:i.currentTime)!=null?r:0)*1e3;(a=this.liveTextManager)==null||a.maintain(t)}setSourceDuration(){(0,Y.assertNonNullable)(this.source),this.source.duration=Number.MAX_SAFE_INTEGER}isStallExceeded(t){let{keepSilentStallWatchdogWhenNotActive:i}=this.tuning.dashCmafLive,a=this.liveStreamStatus$.getValue()==="active";return(!i||a)&&super.isStallExceeded(t)}async restoreAfterDeepStall(t){let{liveStallReinitInterval:i}=this.tuning.dash,{keepSilentStallWatchdogWhenNotActive:r}=this.tuning.dashCmafLive,a=this.currentStallDuration$.getValue(),o=this.liveStreamStatus$.getValue()==="active";if(a%i===0){let u=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);t.liveLastOffset=u,!o&&r?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(u),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()):this.seek(u).catch(c=>{this.error$.next({id:"stallIntervalCallback",category:Y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:c})})}}async updateManifest(){var d,l;let t=await super.updateManifest();if((0,Y.isNullable)(t))return null;if((0,Y.isNullable)(t.live))return this.error$.next({id:"ManifestParsing",category:Y.ErrorCategory.PARSER,message:"MPD doesnt contain live section for live stream"}),null;this.isLive$.next(!0);let{availabilityStartTime:i,latestSegmentPublishTime:r,streamIsUnpublished:a,streamIsAlive:n}=t.live,o=((d=t.duration)!=null?d:0)/1e3;this.liveSeekableDuration$.next(-1*o),this.liveDuration$.next((r-i)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let u="active";if(n||(u=a?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(u),this.bufferManagers.forEach(p=>p.updateManifest(t)),(l=this.liveTextManager)==null||l.updateLive(t),n&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let p=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seek(p).catch(h=>{this.error$.next({id:"updateManifest",category:Y.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:h})})}return t}prepareManifestUrlString(t,i){return Ae(t,i,2)}updateManifestUrlWithTimeOffset(t){let i=this.liveStreamStatus$.getValue()!=="active"?(0,Y.now)()-this.liveStreamEndTimestamp:0,r=this.normalizeLiveOffset(t+i);this.isActiveLive$.next(r===0),this.manifestUrlString=Ae(this.manifestUrlString,r,2)}createBuffers(t,i,r,a){(0,Y.assertNonNullable)(this.manifest),super.createBuffers(t,i,r,a),As.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new As(this.manifest.streams.text,t))}initRepresentationSubscriptions(){(0,Y.assertNonNullable)(this.element),(0,Y.assertNonNullable)(this.videoBufferManager),this.isActiveLive$.next(this.isLive$.getValue()),super.initRepresentationSubscriptions();let t=this.videoBufferManager,i=this.bufferManagers;this.initStreamDurationOnPauseSubscription(),this.initLiveChangePlaybackRateSubscriptions(),this.initLiveDurationSubscriptions(t),this.initLiveBufferInfoSubscriptions(t,i),this.initLiveMaintainSubscription(i),(0,Y.isNonNullable)(this.liveTextManager)&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$))}initStreamDurationOnPauseSubscription(){(0,Y.assertNonNullable)(this.element);let{liveUpdateInterval:t}=this.tuning.dash,i=()=>(0,Y.interval)(t).subscribe(async r=>{let a=hi(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,a+t,2),this.liveStreamStatus$.getValue()==="active"&&(this.manifest=await this.updateManifest())});this.representationSubscription.add((0,Y.fromEvent)(this.element,"pause").subscribe(r=>{this.livePauseWatchdogSubscription=i(),this.representationSubscription.add(this.livePauseWatchdogSubscription)})),this.representationSubscription.add((0,Y.fromEvent)(this.element,"play").subscribe(r=>{var a;return(a=this.livePauseWatchdogSubscription)==null?void 0:a.unsubscribe()}))}initLiveDurationSubscriptions(t){this.representationSubscription.add(this.liveDuration$.pipe((0,Y.filterChanged)()).subscribe(i=>this.liveStreamEndTimestamp=(0,Y.now)())),this.representationSubscription.add(t.currentLowLatencySegmentLength$.subscribe(i=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!i)return;let r=this.liveSeekableDuration$.getValue()-i/1e3;this.liveSeekableDuration$.next(Math.max(r,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+i/1e3)}))}initLiveChangePlaybackRateSubscriptions(){this.representationSubscription.add((0,Y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.map)(({isActiveLive:t,isLowLatency:i})=>t&&i),(0,Y.filterChanged)(),(0,Y.filter)(t=>!this.isManualDecreasePlaybackInLive())).subscribe(t=>Yr(this.element,1))),this.representationSubscription.add((0,Y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.filter)(t=>!this.isManualDecreasePlaybackInLive())).subscribe(({liveBuffer:t,isActiveLive:i,isLowLatency:r})=>{if(!r||!i)return;let a=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,n=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,o=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,u=t-a,c=1;Math.abs(u)>n&&(c=1+Math.sign(u)*o),Yr(this.element,c)}))}initLiveBufferInfoSubscriptions(t,i){this.representationSubscription.add((0,Y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.filter)(({bufferLength:r,isActiveLive:a,isLowLatency:n})=>a&&n&&!!r),(0,Y.map)(({bufferLength:r})=>r)).subscribe(this.liveBuffer)),this.representationSubscription.add(this.bufferLength$.subscribe(r=>{var n,o;let a=0;if(r){let u=((o=(n=this.element)==null?void 0:n.currentTime)!=null?o:0)*1e3;a=Math.min(...i.map(d=>{var l,p;return(p=(l=d.getLiveSegmentsToLoadState(this.manifest))==null?void 0:l.to)!=null?p:u}))-u}this.liveLoadBufferLength$.getValue()!==a&&this.liveLoadBufferLength$.next(a)})),this.representationSubscription.add((0,Y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:t.currentLiveSegmentServerLatency$}).pipe((0,Y.filter)(({isLive:r})=>r),(0,Y.filterChanged)((r,a)=>a.bufferLength<r.bufferLength),(0,Y.map)(({rtt:r,bufferLength:a,segmentServerLatency:n})=>{let o=hi(this.manifestUrlString,2);return(r/2+a+n+o)/1e3})).subscribe(this.liveLatency$))}initLiveMaintainSubscription(t){let i=0;this.representationSubscription.add((0,Y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,Y.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:r,bufferLength:a})=>{(0,Y.assertNonNullable)(this.element);let n=this.element.playbackRate,o=hi(this.manifestUrlString,2),u=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,c=Math.min(u,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*n),d=this.tuning.dashCmafLive.normalizedActualBufferOffset*n,l=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*n,p=isFinite(r)?r:a,h=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),m=u<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(m);let b="none";if(h?b="active_low_latency":this.isLowLatency$.getValue()&&m?(t.forEach(S=>S.proceedLowLatencyLive()),b="active_low_latency"):o!==0&&p<c?b="live_forward_buffering":p<c+l&&(b="live_with_target_offset"),isFinite(r)&&(i=r>i?r:i),b==="live_forward_buffering"||b==="live_with_target_offset"){let S=i-(c+d),v=this.normalizeLiveOffset(Math.trunc(o+S/n)),y=Math.abs(v-o),x=0;!r||y<=this.tuning.dashCmafLive.offsetCalculationError?x=o:v>0&&y>this.tuning.dashCmafLive.offsetCalculationError&&(x=v),this.manifestUrlString=Ae(this.manifestUrlString,x,2)}(b==="live_with_target_offset"||b==="live_forward_buffering")&&(i=0,this.manifest=await this.updateManifest())},r=>{this.error$.next({id:"updateLive",category:Y.ErrorCategory.VIDEO_PIPELINE,thrown:r,message:"Failed to update live with subscription"})}))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let t=1-this.element.playbackRate;return Number(t.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(t){return Math.trunc(t/1e3)*1e3}};var Kr=class extends Zi{constructor(e){super(e),this.textTracksManager.destroy()}getPlayer(){return new Bo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}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);let o=new be.ValueSubject(1);n(r.playbackRateState$,o),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,be.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(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:c})=>u&&c?u+c:void 0)).subscribe(i.liveTime$)).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:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||(0,be.isNullable)(d)||(t=u-d)})).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,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||(0,be.isNullable)(u)||(0,be.isNullable)(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=$v(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,be.filter)(u=>(0,be.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seek(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var W=require("@vkontakte/videoplayer-shared/es2018");var jy=G(Xe(),1),Ul=G(Qa(),1);var Ri=(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 T=require("@vkontakte/videoplayer-shared/es2018");var Vo=G(Xe(),1),or=G(bt(),1),_o=G(Qa(),1);var qy=G(zc(),1);var Mi=require("@vkontakte/videoplayer-shared/es2018");var J$=18,Fy=!1;try{Fy=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=J$}catch(s){console.error(s)}var Nl=class{constructor(e,t=!1){this.bufferFull$=new Mi.Subject;this.error$=new Mi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){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()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Fy&&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.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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)}}},Uy=Nl;var Fl=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var P=require("@vkontakte/videoplayer-shared/es2018");var Rs=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new P.ValueSubject(0);this.currentLowLatencySegmentLength$=new P.ValueSubject(0);this.currentSegmentLength$=new P.ValueSubject(0);this.onLastSegment$=new P.ValueSubject(!1);this.fullyBuffered$=new P.ValueSubject(!1);this.playingRepresentation$=new P.ValueSubject(void 0);this.playingRepresentationInit$=new P.ValueSubject(void 0);this.error$=new P.Subject;this.gaps=[];this.subscription=new P.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ye;this.switchAbortController=new ye;this.destroyAbortController=new ye;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,P.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 Uy(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Se(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Fl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<d).catch(l=>{this.handleAsyncError(l,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,P.assertNonNullable)(i,"No init buffer for starting representation"),(0,P.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,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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,P.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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,P.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){var u;let t=(0,_o.default)(e,c=>c.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let l=this.representations.get(c);if(!l||!dt(l.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,p)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);(0,P.assertNonNullable)(r,`Representation not found by id ${i}`);let a=this.segments.get(i);(0,P.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,P.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.live),this.baseUrls=(d=c==null?void 0:c.baseUrls)!=null?d:[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ye,(0,P.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,P.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,P.isNullable)(o)||(0,P.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,P.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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,P.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,P.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ye,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var p;if((0,P.isNullable)(e)||(0,P.isNullable)(this.downloadingRepresentationId)||(0,P.isNullable)(this.playingRepresentationId)||(0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||(0,P.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if((0,P.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,P.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,P.isNullable)(r)||(0,P.isNullable)(a))return;let n=r.find(h=>e>=h.time.from&&e<h.time.to);(0,P.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=this.getForwardBufferDuration(e),m=xi(i),b=xi(t),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,P.isNonNullable)(m)&&(0,P.isNonNullable)(b)&&(0,P.isHigher)(m.quality,b.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(S||v?o+=Math.min(h,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let x=(p=[...this.segments.entries()].map(([w,M])=>{let _=M.find(F=>e>=F.time.from&&e<F.time.to);return{representationId:w,status:_==null?void 0:_.status}}).find(w=>w.status==="fed"))==null?void 0:p.representationId;x&&(this.playingRepresentationId=x,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Fl(this.sourceBuffer.buffered)>=this.bufferLimit){let h=this.getForwardBufferDuration(e),m=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<m).catch(b=>{this.handleAsyncError(b,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Vo.default)(d,n))h="high";else{let m=(0,or.default)(d,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(d,t,h).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,or.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let 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,P.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=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,_o.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,a;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,_o.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!dt(n.segmentReference))return;let o=n.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),u=100,c=(i=this.segments.get(n.id))!=null?i:[],d=(a=(r=(0,or.default)(c,-1))==null?void 0:r.time.to)!=null?a:0,l=o==null?void 0:o.findIndex(p=>d>=p.time.from+u&&d<=p.time.to+u);if(l===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(l+1);this.segments.set(n.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,P.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,or.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!dt(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let c=Math.round(e.time.to*a.timescale/1e3).toString(10),d=At(a.segmentTemplateUrl,{segmentTime:c});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}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&&rr&&rr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&rr&&rr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:p,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+y||r<y&&m-h>=y||m<=i+y;return(p==="none"||p==="partially_ejected"&&v&&x&&this.sourceBuffer&&Se(this.mediaSource,this.sourceBuffer)&&!(Ri(this.sourceBuffer.buffered,h)&&Ri(this.sourceBuffer.buffered,m)))&&v&&x});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=a;p<n.length&&(o<=d||u<=l);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")c.push(h);else break}return c}async loadSegments(e,t,i="auto"){dt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){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:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,P.abortable)(o,async function*(){let d=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,P.now)(),!d)return;let l=new DataView(d),p=nr(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,b)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(l);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),kt(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())dt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,P.abortable)(n,async function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,P.fromEvent)(window,"online").pipe((0,P.once)()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,P.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),kt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(dt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,or.default)(e,0).byte.from,to:(0,or.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!dt(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?(c,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Vo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!Se(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=nr(n.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Se(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let d=c.byte.from-i,l=c.byte.to-i,p=l-d+1,h=d<r,m=l<=r;if(!h)continue;let b=nr(o.mime);if(c.status==="downloading"&&m){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?S:b.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(c.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!((0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ri(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ri(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Bl(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=ir(()=>(0,qy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?(0,P.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,nr(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:c,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=l;this.isLive&&dt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,u=>{a||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:P.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Se(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,P.isNullable)(e))return!1;let r=[],a=0,n=u=>{u.sort((d,l)=>d.from-l.from);let c=[u[0]];for(let d=1;d<u.length;d++){let{from:l,to:p}=u[d],h=c[c.length-1];h.to>=l?h.to=Math.max(h.to,p):c.push(u[d])}return c},o=u=>{var d;if(a>=t)return r;r.push({...u.time}),r=n(r);let c=Bl(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){let d=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let p of this.segments.values())for(let h of p)(0,Vo.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:c,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,d)=>c||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Se(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||!Se(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||!Se(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:ki(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Se(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:a}=this.sourceBuffer;for(let n=0;n<a.length;n++){let o=a.start(n)*1e3,u=a.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!Se(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(a=>{if(r&&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}),this.gapDetectionIdleCallback=ir(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||(0,P.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(d=>d.from-t<=n&&d.to+t>=o),c=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:P.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var q=require("@vkontakte/videoplayer-shared/es2018");var No=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new q.Subject;this.firstBytesManifest$=new q.Subject;this.firstBytesRequested$=new q.Subject;this.firstBytesReceived$=new q.Subject;this.lastConnectionType$=new q.ValueSubject(void 0);this.lastConnectionReused$=new q.ValueSubject(void 0);this.lastRequestFirstBytes$=new q.ValueSubject(void 0);this.lastConnectionMetrics$=new q.ValueSubject(void 0);this.lastDownloadMetrics$=new q.ValueSubject(void 0);this.recoverableError$=new q.Subject;this.error$=new q.Subject;this.abortAllController=new ye;this.subscription=new q.SubscriptionRemovable;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,q.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mo(i)),this.trackRequestStart(i,performance.now());let r=(0,q.now)();this.manifestRequested$.next();let a=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Oo);if(a){let n=(0,q.now)();t.log("success",(0,q.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),this.firstBytesManifest$.next();let o=a.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=await a.text();if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",(0,q.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=(0,q.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:d=!1}={}){var le,oe,A;let l=e,p=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(l,(0,q.getWindow)().location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),l=$.toString();break}default:(0,q.assertNever)(t)}this.requestQuic&&(l=Ei(l));let m=this.abortAllController.signal,b;if(n){let $=new ye;if(b=(0,q.merge)((0,q.fromEvent)(this.abortAllController.signal,"abort"),(0,q.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(k){Oo(k)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(k){Oo(k)}m=$.signal}let S=0,v=(0,q.now)();h.log("startRequest",(0,q.flattenObject)({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested$.next();let y=yield this.doFetch(l,{priority:a,headers:p,signal:m},{ignoreNetworkErrors:d}),x=(0,q.now)();if(!y)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(b),null;if((le=this.throughputEstimator)==null||le.addRawRtt(x-v),!y.ok||!y.body){this.unsubscribeAbortSubscription(b);let $=`Fetch error ${y.status}: ${y.statusText}`;return h.error("error",{message:$}),h.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){this.unsubscribeAbortSubscription(b);let $=(0,q.now)(),k={requestStartedAt:v,requestEndedAt:$,duration:$-v};return h.log("endRequest",(0,q.flattenObject)(k)),h.end(),y.arrayBuffer()}let w=y.body;if(o){let $;[w,$]=y.body.tee(),(oe=this.throughputEstimator)==null||oe.trackStream($,u)}let M=w.getReader(),_,F=parseInt((A=y.headers.get("content-length"))!=null?A:"",10);Number.isFinite(F)&&(_=F),!_&&i&&(_=i.to-i.from+1);let O=_?new Uint8Array(_):new Uint8Array(0),H=!1,V=$=>{this.unsubscribeAbortSubscription(b),H=!0,Oo($)},Q=(0,q.abortable)(m,async function*({done:$,value:k}){if(S===0&&(this.lastRequestFirstBytes$.next((0,q.now)()-v),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(b);return}if(!$&&k){if(c&&_)O.set(k,S),S+=k.byteLength;else{let R=new Uint8Array(O.length+k.length);R.set(O),R.set(k,O.length),O=R,S+=k.byteLength}r==null||r(new DataView(O.buffer),S),yield M==null?void 0:M.read().then(Q,V)}}.bind(this));yield M==null?void 0:M.read().then(Q,V),this.unsubscribeAbortSubscription(b);let N=(0,q.now)(),ie={failed:H,requestStartedAt:v,requestEndedAt:N,duration:N-v};if(H)return h.error("endRequest",(0,q.flattenObject)(ie)),h.end(),null;if(S>0){let $=N-v,R=S/($/1e3)*8/1024,Z={bytes:S,speed:R,url:e};this.lastDownloadMetrics$.next(Z)}return h.log("endRequest",(0,q.flattenObject)(ie)),h.end(),O.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,q.abortable)(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=a+1===c,u&&(n=Math.min(c,r),o=Math.max(d,a))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!l)return null;let p=new DataView(l,r-n,a-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(l,m.from-n,m.to-m.from+1);else{let y=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(l),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,q.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...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,(0,q.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=fo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,q.getWindow)()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processPerformanceResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in(0,q.getWindow)().navigator))return"unknown";let e=(0,q.getWindow)().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,a=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(a=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=a),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,a),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),a=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(a===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch(t){this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:q.ErrorCategory.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}async fetchRepresentation(e,t,i){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,q.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}async doFetch(e,t,i){let r=await vt(e,t);if(r.ok)return r;if(i!=null&&i.ignoreNetworkErrors)return;let a=await r.text(),n=parseInt(a);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:q.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:q.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:q.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:q.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:q.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Oo=s=>{if(!kt(s))throw s};var Fo=require("@vkontakte/videoplayer-shared/es2018");var Ms=class s{constructor(e,t){this.currentRepresentation$=new Fo.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,Fo.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 c=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.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&&dt(t.segmentReference))}};var eL=["timeupdate","progress","play","seeked","stalled","waiting"],tL=["timeupdate","progress","loadeddata","playing","seeked"];var Uo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;this.subscriptionRemovable=new T.SubscriptionRemovable;this.representationSubscription=new T.Subscription;this.state$=new ae("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested$=new T.Subject;this.firstBytesManifest$=new T.Subject;this.manifestReceived$=new T.Subject;this.firstBytesRequested$=new T.Subject;this.firstBytesReceived$=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.lastConnectionMetrics$=new T.ValueSubject(void 0);this.lastDownloadMetrics$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new ye;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ae(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,async function*(){var u,c;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=yo(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(d){let l=(u=ho(e))!=null?u:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(l)}if(!t)return null;let i=(d,l,p)=>{var h,m,b,S;return!!((m=(h=this.element)==null?void 0:h.canPlayType)!=null&&m.call(h,l)&&((S=(b=ut())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${l}; codecs="${p}"`))||d==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:d,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:h}=t.live,m=((c=t.duration)!=null?c:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((l-d)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let b="active";if(h||(b=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(b),h&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let S=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(S).catch(v=>{this.error$.next({id:"updateManifest",category:T.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:v})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let d of["video","audio"]){let p=t.streams[d].filter(({mime:m,codecs:b})=>i(d,m,b));r[d]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let m=p.map(({codecs:b})=>b);d==="audio"&&(n=xo(m),h=n[0]),d==="video"&&(a=wo(m),this.forceVideoCodec&&(0,jy.default)(a,this.forceVideoCodec)?h=this.forceVideoCodec:h=a[0]),h&&(r[d]=p.filter(({codecs:b})=>jr(b)===h))}else{let m=new Set(p.map(({codecs:b})=>b));h=Eo(m),h&&(r[d]=p.filter(({codecs:b})=>b.startsWith(h)))}if(d==="video"){let m=this.tuning.preferHDR,b=r.video.some(y=>y.hdr),S=r.video.some(y=>!y.hdr);j.display.isHDR&&m&&b?r.video=r.video.filter(y=>y.hdr):S&&(r.video=r.video.filter(y=>!y.hdr));let{videoStreamRepresentaionsFilter:v}=this.tuning.dash;v.length&&Ro(r,v)}}let o={...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,async function*(e,t,i){var l;this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,T.fromEvent)(p,"error").pipe((0,T.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=vn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),xr())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 Rs("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Rs("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(Ms.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ms(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.merge)(...tL.map(p=>(0,T.fromEvent)(this.element,p))).pipe((0,T.map)(p=>this.element?ki(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:h}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,T.interval)(h).subscribe(m=>{let b=hi(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,b+h,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,T.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Yr(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:h})=>h),(0,T.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,T.map)(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=hi(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(x)>v&&(w=1+Math.sign(x)*y),Yr(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let v=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(x=>{var w,M;return(M=(w=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?M:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=hi(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,M=isFinite(h)?h:m,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),F=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(F);let O="none";if(_?O="active_low_latency":this.isLowLatency$.getValue()&&F?(this.bufferManagers.forEach(H=>H.proceedLowLatencyLive()),O="active_low_latency"):S!==0&&M<y?O="live_forward_buffering":M<y+w&&(O="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),O==="live_forward_buffering"||O==="live_with_target_offset"){let H=p-(y+x),V=this.normalizeLiveOffset(Math.trunc(S+H/b)),Q=Math.abs(V-S),N=0;!h||Q<=this.tuning.dashCmafLive.offsetCalculationError?N=S:V>0&&Q>this.tuning.dashCmafLive.offsetCalculationError&&(N=V),this.manifestUrlString=Ae(this.manifestUrlString,N,2)}(O==="live_with_target_offset"||O==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let u=(0,T.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,T.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=(0,T.combine)({allBuffersFull:u,someBufferEnded:c}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,T.filter)(p=>p));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(l=this.manifest.duration)!=null?l:0,...(0,Ul.default)((0,Ul.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),dt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,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 No({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=ii.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){(0,T.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ae(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){var t,i,r;await((t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio)),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...eL.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Ri(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var w,M,_,F,O,H,V,Q,N,ie,le;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||((w=this.source)==null?void 0:w.readyState)!=="open")return;let d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=(0,T.now)(),h=100,m=(_=(M=this.videoBufferManager)==null?void 0:M.lastDataObtainedTimestamp)!=null?_:0;this.videoLastDataObtainedTimestamp$.next(m);let b=(O=(F=this.audioBufferManager)==null?void 0:F.lastDataObtainedTimestamp)!=null?O:0,S=(V=(H=this.videoBufferManager)==null?void 0:H.getForwardBufferDuration())!=null?V:0,v=(N=(Q=this.audioBufferManager)==null?void 0:Q.getForwardBufferDuration())!=null?N:0,y=S<h&&p-m>r,x=this.audioBufferManager&&v<h&&p-b>r;if((!t||c)&&((y||x)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%a===0){let oe=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(oe),this.updateManifest()):this.seekLive(oe).catch(A=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),l.liveLastOffset=oe}else{let oe=this.element.currentTime*1e3;(ie=this.videoBufferManager)==null||ie.maintain(oe),(le=this.audioBufferManager)==null||le.maintain(oe),l.position=oe}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){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)}async seek(e,t){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),Ri(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let c of u.gaps)(r&&c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=a&&c.to+o>a&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?n.push(1/0):n.push(c.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,T.flattenObject)(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var at=require("@vkontakte/videoplayer-shared/es2018"),qo=class{constructor(){this.subscription=new at.Subscription;this.pipSize$=new at.ValueSubject(void 0);this.videoSize$=new at.ValueSubject(void 0);this.elementSize$=new at.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=at.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,at.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,at.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,at.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 ur=class{constructor(e){this.subscription=new W.Subscription;this.videoState=new ae("stopped");this.observableVideo=null;this.droppedFramesManager=new Or;this.stallsManager=new uo;this.elementSizeManager=new qo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yi;this.audioTrackSwitchHistory=new yi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,W.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Nr(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 mt(e.source.url),this.params=e,this.video=Je(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Uo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,W.isNullable)(this.observableVideo)&&(this.observableVideo=tt(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:W.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,W.filter)(l=>!!l.length),(0,W.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,W.map)(l=>l.to.state!=="none"),(0,W.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),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.currentBuffer$,e.currentNativeBuffer$),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.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),a(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,W.filter)(W.isNonNullable),(0,W.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,W.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(Nt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Ii({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(et(this.video,t.volume,i.volumeState$,r)),this.subscription.add(ft(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(gt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams(),h=this.player.getCodecs();if((0,W.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of p.audio){b.push(Cl(S));let v=[];for(let y of S.representations){let x=Es(y);v.push(x),this.audioTracksMap.set(x,{stream:S,representation:y})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of p.video){m.push(Dl(b));let S=[];for(let v of b.representations){let y=xi({...v,streamId:b.id});y&&(S.push(y),this.videoTracksMap.set(y,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of p.text)for(let S of b.representations){let v=$y(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,W.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,W.fromEvent)(this.video,"progress")).pipe((0,W.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,W.throttle)(u))),this.subscription.add(o.subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,S=[...this.videoTracksMap.keys()].find(y=>{var x;return((x=this.videoTracksMap.get(y))==null?void 0:x.representation.id)===m.id});(0,W.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),l==="manifest_ready")await this.player.initRepresentations(m.id,b==null?void 0:b.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),b){let y=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",b.id,y)}},r)),this.subscription.add((0,W.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,W.merge)((0,W.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,W.map)(l=>l.to)))}).pipe((0,W.map)(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),(0,W.filterChanged)()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,W.filterChanged)()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Dl(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,W.filterChanged)()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Cl(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var p,h;if(l!=null&&l.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe((0,W.map)(({to:l})=>l==="ready"),(0,W.filterChanged)());this.subscription.add((0,W.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,W.merge)(c,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,W.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,W.observableFrom)(["init"])).pipe((0,W.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var O,H,V,Q,N,ie,le,oe,A,$,k,R,Z;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Na:Oa,t=this.params.tuning.useNewAutoSelectVideoTrack?io:to,i=this.params.tuning.useNewAutoSelectVideoTrack?Ft:eo,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(O=r.videoTrack.getState())==null?void 0:O.id,u=[...this.videoTracksMap.keys()].find(({id:K})=>K===o),c=a.currentVideoTrack$.getValue(),d=((Q=(V=r.videoStream.getState())!=null?V:u&&((H=this.videoTracksMap.get(u))==null?void 0:H.stream))!=null?Q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:K})=>K===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=ki(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=(N=r.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(ie=[...this.audioStreamsMap.keys()].find(({id:K})=>K===(v==null?void 0:v.id)))!=null?ie:this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let K=e(u,p,(le=this.audioStreamsMap.get(y))!=null?le:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(oe=K==null?void 0:K.bitrate)!=null?oe:-1/0)}if(c){let K=e(c,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,($=K==null?void 0:K.bitrate)!=null?$:-1/0)}}let w=u;(n||!w)&&(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:x,forwardBufferHealth:S,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let M=y&&t(w,p,(k=this.audioStreamsMap.get(y))!=null?k:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),_=(R=this.videoTracksMap.get(w))==null?void 0:R.representation,F=M&&((Z=this.audioTracksMap.get(M))==null?void 0:Z.representation);if(_&&F)return[_,F];if(_&&!F&&this.audioTracksMap.size===0)return[_,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:W.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),Ze(this.video),this.tracer.end()}};var $s=class extends ur{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/es2018");var Ls=class extends ur{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 c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(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:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).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:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||(0,ge.isNullable)(d)||(t=u-d)})).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,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||(0,ge.isNullable)(u)||(0,ge.isNullable)(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=Ly(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,ge.filter)(u=>(0,ge.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Hy="X-Playback-Duration",ql=async s=>{var r;let e=await vt(s),t=await 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(Hy)?parseInt(e.headers.get(Hy),10):void 0};var ne=require("@vkontakte/videoplayer-shared/es2018");var Hl=G(oc(),1);var jo=require("@vkontakte/videoplayer-shared/es2018");var rL=s=>{let e=null;if(s.QUALITY&&(e=Si(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,jo.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},aL=(s,e)=>{var a,n;let t=s.split(`
|
|
178
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var hy=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,Al.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,fy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Al.default)(t,n,(o,u)=>(0,Ya.isNullable)(a)?o:(0,Ya.isNullable)(u)?a:(0,my.default)(a,parseInt(u,10),"0"))}return t},yo=(s,e)=>{var H,V,Q,N,ie,le,oe,A,$,k,R,Z,K,Mt,$t,pe,Ne,Fe,Ue,st,Ht,Wt,$i,lr,Li,Zl,ed,td,id,rd,ad,sd,nd,od,ud,cd,ld,dd,pd,hd,fd,md,bd,gd,vd,Sd,yd,Td,Id,Ed,wd,xd,Pd,kd,Ad,Rd,Md,$d,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(yt=>{var ve,Ci;return(Ci=(ve=yt.textContent)==null?void 0:ve.trim())!=null?Ci:""}),o=(H=(0,by.default)(n,0))!=null?H:"",u=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),l=a.getElementsByTagName("vk:Attrs")[0],p=l==null?void 0:l.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=l==null?void 0:l.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=l==null?void 0:l.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=l==null?void 0:l.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:c?new Date(c).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,y=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],w=x.reduce((yt,ve)=>({...yt,[ve.id]:ve.children}),{}),M=x.reduce((yt,ve)=>({...yt,[ve.id]:ve.getAttribute("duration")}),{});y?v=hy(y):(0,Rl.default)(M).filter(yt=>yt).length&&!u?v=(0,Rl.default)(M).reduce((yt,ve)=>{var Ci;return yt+((Ci=hy(ve))!=null?Ci:0)},0):b&&(v=parseInt(b,10));let _=0,F=(Q=(V=a.getAttribute("profiles"))==null?void 0:V.split(","))!=null?Q:[];for(let yt of x.map(ve=>ve.id))for(let ve of w[yt]){let Ci=(N=ve.getAttribute("id"))!=null?N:"id"+(_++).toString(10),ea=(ie=ve.getAttribute("mimeType"))!=null?ie:"",Go=(le=ve.getAttribute("codecs"))!=null?le:"",Yo=(oe=ve.getAttribute("contentType"))!=null?oe:ea==null?void 0:ea.split("/")[0],pT=($=(A=ve.getAttribute("profiles"))==null?void 0:A.split(","))!=null?$:[],Bd=(R=py((k=ve.getAttribute("lang"))!=null?k:""))!=null?R:{},Fs=(Mt=(K=(Z=ve.querySelector("Label"))==null?void 0:Z.textContent)==null?void 0:K.trim())!=null?Mt:void 0,hT=ve.querySelectorAll("Representation"),fT=ve.querySelector("SegmentTemplate"),mT=(pe=($t=ve.querySelector("Role"))==null?void 0:$t.getAttribute("value"))!=null?pe:void 0,dr=Yo,Re={id:Ci,language:Bd.language,isDefault:mT==="main",label:Fs,codecs:Go,hdr:dr==="video"&&kl(Go),mime:ea,representations:[]};for(let me of hT){let si=(Ne=me.getAttribute("lang"))!=null?Ne:void 0,Us=(Ue=(Fe=Fs!=null?Fs:ve.getAttribute("label"))!=null?Fe:me.getAttribute("label"))!=null?Ue:void 0,qs=(Wt=(Ht=(st=me.querySelector("BaseURL"))==null?void 0:st.textContent)==null?void 0:Ht.trim())!=null?Wt:"",Di=new URL(qs||o,e).toString(),ni=($i=me.getAttribute("mimeType"))!=null?$i:ea,js=(Li=(lr=me.getAttribute("codecs"))!=null?lr:Go)!=null?Li:"",Hs;if(Yo==="text"){let oi=me.getAttribute("id")||"",Ws=((Zl=Bd.privateuse)==null?void 0:Zl.includes("x-auto"))||oi.includes("_auto"),Bi=me.querySelector("SegmentTemplate");if(Bi){let ta={representationId:(ed=me.getAttribute("id"))!=null?ed:void 0,bandwidth:(td=me.getAttribute("bandwidth"))!=null?td:void 0},Qs=parseInt((id=me.getAttribute("bandwidth"))!=null?id:"",10)/1e3,zs=(ad=parseInt((rd=Bi.getAttribute("startNumber"))!=null?rd:"",10))!=null?ad:1,pr=parseInt((sd=Bi.getAttribute("timescale"))!=null?sd:"",10),Ko=(nd=Bi.querySelectorAll("SegmentTimeline S"))!=null?nd:[],hr=Bi.getAttribute("media");if(!hr)continue;let Gs=[],Ys=0,Ks="",fr=0,ia=zs,Qe=0;for(let Tt of Ko){let Vi=parseInt((od=Tt.getAttribute("d"))!=null?od:"",10),ht=parseInt((ud=Tt.getAttribute("r"))!=null?ud:"",10)||0,ui=parseInt((cd=Tt.getAttribute("t"))!=null?cd:"",10);Qe=Number.isFinite(ui)?ui:Qe;let _i=Vi/pr*1e3,ci=Qe/pr*1e3;for(let Lt=0;Lt<ht+1;Lt++){let li=At(hr,{...ta,segmentNumber:ia.toString(10),segmentTime:(Qe+Lt*Vi).toString(10)}),mr=(ci!=null?ci:0)+Lt*_i,aa=mr+_i;ia++,Gs.push({time:{from:mr,to:aa},url:li})}Qe+=(ht+1)*Vi,Ys+=(ht+1)*_i}fr=Qe/pr*1e3,Ks=At(hr,{...ta,segmentNumber:ia.toString(10),segmentTime:Qe.toString(10)});let ra={time:{from:fr,to:1/0},url:Ks},Qt={type:"template",baseUrl:Di,segmentTemplateUrl:hr,initUrl:"",totalSegmentsDurationMs:Ys,segments:Gs,nextSegmentBeyondManifest:ra,timescale:pr};Hs={id:oi,kind:"text",segmentReference:Qt,profiles:[],duration:v,bitrate:Qs,mime:"",codecs:"",width:0,height:0,isAuto:Ws}}else Hs={id:oi,isAuto:Ws,kind:"text",url:Di}}else{let oi=(dd=(ld=me.getAttribute("contentType"))!=null?ld:ni==null?void 0:ni.split("/")[0])!=null?dd:Yo,Ws=(hd=(pd=ve.getAttribute("profiles"))==null?void 0:pd.split(","))!=null?hd:[],Bi=parseInt((fd=me.getAttribute("width"))!=null?fd:"",10),ta=parseInt((md=me.getAttribute("height"))!=null?md:"",10),Qs=parseInt((bd=me.getAttribute("bandwidth"))!=null?bd:"",10)/1e3,zs=(gd=me.getAttribute("frameRate"))!=null?gd:"",pr=(vd=me.getAttribute("quality"))!=null?vd:void 0,Ko=zs?dy(zs):void 0,hr=(Sd=me.getAttribute("id"))!=null?Sd:"id"+(_++).toString(10),Gs=oi==="video"?`${ta}p`:oi==="audio"?`${Qs}Kbps`:js,Ys=`${hr}@${Gs}`,Ks=[...F,...pT,...Ws],fr,ia=me.querySelector("SegmentBase"),Qe=(yd=me.querySelector("SegmentTemplate"))!=null?yd:fT;if(ia){let Qt=(Id=(Td=me.querySelector("SegmentBase Initialization"))==null?void 0:Td.getAttribute("range"))!=null?Id:"",[Tt,Vi]=Qt.split("-").map(li=>parseInt(li,10)),ht={from:Tt,to:Vi},ui=(Ed=me.querySelector("SegmentBase"))==null?void 0:Ed.getAttribute("indexRange"),[_i,ci]=ui?ui.split("-").map(li=>parseInt(li,10)):[],Lt=ui?{from:_i,to:ci}:void 0;fr={type:"byteRange",url:Di,initRange:ht,indexRange:Lt}}else if(Qe){let Qt={representationId:(wd=me.getAttribute("id"))!=null?wd:void 0,bandwidth:(xd=me.getAttribute("bandwidth"))!=null?xd:void 0},Tt=parseInt((Pd=Qe.getAttribute("timescale"))!=null?Pd:"",10),Vi=(kd=Qe.getAttribute("initialization"))!=null?kd:"",ht=Qe.getAttribute("media"),ui=(Rd=parseInt((Ad=Qe.getAttribute("startNumber"))!=null?Ad:"",10))!=null?Rd:1,_i=At(Vi,Qt);if(!ht)throw new ReferenceError("No media attribute in SegmentTemplate");let ci=(Md=Qe.querySelectorAll("SegmentTimeline S"))!=null?Md:[],Lt=[],li=0,mr="",aa=0;if(ci.length){let Xs=ui,It=0;for(let br of ci){let Ct=parseInt(($d=br.getAttribute("d"))!=null?$d:"",10),Oi=parseInt((Ld=br.getAttribute("r"))!=null?Ld:"",10)||0,Js=parseInt((Cd=br.getAttribute("t"))!=null?Cd:"",10);It=Number.isFinite(Js)?Js:It;let Xo=Ct/Tt*1e3,Jo=It/Tt*1e3;for(let Zs=0;Zs<Oi+1;Zs++){let gT=At(ht,{...Qt,segmentNumber:Xs.toString(10),segmentTime:(It+Zs*Ct).toString(10)}),Vd=(Jo!=null?Jo:0)+Zs*Xo,vT=Vd+Xo;Xs++,Lt.push({time:{from:Vd,to:vT},url:gT})}It+=(Oi+1)*Ct,li+=(Oi+1)*Xo}aa=It/Tt*1e3,mr=At(ht,{...Qt,segmentNumber:Xs.toString(10),segmentTime:It.toString(10)})}else if((0,Ya.isNonNullable)(v)){let It=parseInt((Dd=Qe.getAttribute("duration"))!=null?Dd:"",10)/Tt*1e3,br=Math.ceil(v/It),Ct=0;for(let Oi=1;Oi<br;Oi++){let Js=At(ht,{...Qt,segmentNumber:Oi.toString(10),segmentTime:Ct.toString(10)});Lt.push({time:{from:Ct,to:Ct+It},url:Js}),Ct+=It}aa=Ct,mr=At(ht,{...Qt,segmentNumber:br.toString(10),segmentTime:Ct.toString(10)})}let bT={time:{from:aa,to:1/0},url:mr};fr={type:"template",baseUrl:Di,segmentTemplateUrl:ht,initUrl:_i,totalSegmentsDurationMs:li,segments:Lt,nextSegmentBeyondManifest:bT,timescale:Tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!oi||!ni)continue;let ra={video:"video",audio:"audio",text:"text"}[oi];if(!ra)continue;dr||(dr=ra),Hs={id:Ys,kind:ra,segmentReference:fr,profiles:Ks,duration:v,bitrate:Qs,mime:ni,codecs:js,width:Bi,height:ta,fps:Ko,quality:pr}}Re.language||(Re.language=si),Re.label||(Re.label=Us),Re.mime||(Re.mime=ni),Re.codecs||(Re.codecs=js),Re.hdr||(Re.hdr=dr==="video"&&kl(js)),Re.representations.push(Hs)}if(dr){let me=r[dr].find(si=>si.id===Re.id);if(me&&Re.representations.every(si=>si.segmentReference.type==="template"))for(let si of me.representations){let Us=Re.representations.find(ni=>ni.id===si.id);if(!Us)continue;let qs=Us.segmentReference,Di=si.segmentReference;Di.segments.push(...qs.segments),Di.nextSegmentBeyondManifest=qs.nextSegmentBeyondManifest}else r[dr].push(Re)}}return{duration:v,streams:r,baseUrls:n,live:S}};var Io=G(bt(),1),Ml=G(Xe(),1),Xa=require("@vkontakte/videoplayer-shared/es2018");var Ka=(a=>(a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient",a))(Ka||{});var To=s=>{let{webmDecodingInfo:e}=j.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,Xa.assertNever)(s)}},gy=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...To(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(j.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",...To(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...To(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...To(s),...a,"HLS","HLS_ONDEMAND"];default:(0,Xa.assertNever)(e)}if(j.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,Xa.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},vy=({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=j.device.isMac&&j.browser.isSafari;if(j.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,Xa.assertNever)(s)}else j.video.nativeHlsSupported&&!u&&!j.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},$l=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Eo=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Io.default)(t.value.split("."),0)}for(let t of s){let i=(0,Io.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Io.default)(e.value.split("."),0)},wo=s=>{let e=s.map(i=>jr(i)),{codecs:t}=j.video;return R$().filter(i=>{if((0,Ml.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})},xo=s=>{let e=s.map(i=>jr(i)),{codecs:t}=j.video;return M$().filter(i=>{if((0,Ml.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},jr=s=>s.split(".")[0].replace("0",""),R$=()=>["av1","vp9","hev1","avc1"],M$=()=>["opus","mp4a"];var Cy=G(bt(),1);var $$=(s,e={})=>{let i=e.timeout||1,r=performance.now();return Le.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},L$=s=>Le.clearTimeout(s),Sy=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),yy=!Sy(Le.requestIdleCallback)||!Sy(Le.cancelIdleCallback),ir=yy?$$:Le.requestIdleCallback,rr=yy?L$:Le.cancelIdleCallback;var C=require("@vkontakte/videoplayer-shared/es2018");var Iy=G(bt(),1);var Po=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 Hr=class extends ce{};var Ty=require("@vkontakte/videoplayer-shared/es2018");var Ja=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,Ty.assertNever)(e)}}};var Za=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 es=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ie=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 ts=class extends Ie{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 is=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rs=class extends ce{constructor(e,t){super(e,t),this.data=this.content}};var ar=class extends Ie{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,c=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var as=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ss=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ns=class extends Ie{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 os=class extends Ie{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var us=class extends Ie{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 cs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ls=class extends Ie{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 ds=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ps=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hs=class extends Ie{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var fs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ms=class extends Ie{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 bs=class extends Ie{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 gs=class extends Ie{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 vs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ss=class extends Ie{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 ys=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 D$={ftyp:Za,moov:es,mvhd:ts,moof:is,mdat:rs,sidx:ar,trak:as,mdia:cs,mfhd:hs,tkhd:ls,traf:fs,tfhd:ms,tfdt:bs,trun:gs,minf:ds,sv3d:ss,st3d:ns,prhd:os,proj:ps,equi:us,uuid:Ja,stbl:vs,stsd:Ss,avc1:ys,unknown:Hr},Zt=class s{constructor(e={}){this.options={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||!Po(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=D$[e];return i?new i(t,new s):new Hr(t,new s)}};var wi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;Po(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 V$=new TextDecoder("ascii"),_$=s=>V$.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",O$=s=>{let e=new ar(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})},N$=(s,e)=>{let i=new Zt().parse(s),r=new wi(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],c=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,c,l)},F$=s=>{let t=new Zt().parse(s),i=new wi(t),r={},a=i.findAll("uuid"),n=(0,Iy.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},U$=s=>{var r;let t=new Zt().parse(s);return(r=new wi(t).find("sidx"))==null?void 0:r.timescale},q$=(s,e)=>{let i=new Zt().parse(s),a=new wi(i).findAll("traf"),n=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),u=a[a.length-1].children.find(l=>l.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((l,p)=>l+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},j$=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 wi(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},Ey={validateData:_$,parseInit:j$,getIndexRange:()=>{},parseSegments:O$,parseFeedableSegmentChunk:N$,getChunkEndTime:q$,getServerLatencyTimestamps:F$,getTimescaleFromIndex:U$};var Is=G(Xe(),1),ei=require("@vkontakte/videoplayer-shared/es2018");var xy=require("@vkontakte/videoplayer-shared/es2018");var wy={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"}},Py=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=Ts(s,t),r=i in wy,a=r?wy[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),c=n&255>>o,d=Ts(u),l=c*2**((o-1)*8)+d,p=t+o,h;return p+l>s.byteLength?h=new DataView(s.buffer,s.byteOffset+p):h=new DataView(s.buffer,s.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},Ts=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*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},Rt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Ts(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,xy.assertNever)(e)}},sr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Py(i);if(!e(r))return;r.type==="master"&&sr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},ky=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Py(s);return sr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Rt(o,n):a===17026?t=Rt(o,n):a===17029&&(i=Rt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ay=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],H$=[231,22612,22743,167,171,163,160,175],W$=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,c,d=!1,l=0;return sr(s,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=Rt(m,h);c=Ts(S)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?a=!0:p===290298740?n=!0:p===2807729?i=Rt(m,h):p===17545?r=Rt(m,h):p===21420&&c===475249515?u=Rt(m,h):p===374648427?sr(m,({tag:S,type:v,value:y})=>S===30321?(d=Rt(y,v)===1,!1):!0):a&&n&&(0,Is.default)(Ay,p)&&(o=!0),!o}),(0,ei.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,ei.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,ei.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Q$=s=>{if((0,ei.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},z$=(s,e)=>{let t=!1,i=!1,r=o=>(0,ei.isNonNullable)(o.time)&&(0,ei.isNonNullable)(o.position),a=[],n;return sr(s,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Rt(c,u));break;case 183:break;case 241:n&&(n.position=Rt(c,u));break;default:t&&(0,Is.default)(Ay,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:c,position:d}=o,l=a[u+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},G$=s=>{let e=0,t=!1;try{sr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Is.default)(H$,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,Is.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},Ry={validateData:ky,parseInit:W$,getIndexRange:Q$,parseSegments:z$,parseFeedableSegmentChunk:G$};var nr=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ry;case"mp4":return Ey}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Ll=G(bt(),1);var My=require("@vkontakte/videoplayer-shared/es2018"),xi=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Si(a):void 0)!=null?u:(0,My.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Es=({id:s,bitrate:e})=>({id:s,bitrate:e}),$y=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ly=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Cl=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Ll.default)(i.split("."),0),isDefault:r}),Dl=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Ll.default)(r.split("."),0)}),Bl=s=>"url"in s,dt=s=>s.type==="template";var Wr=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,getCurrentStallDuration:o,manifest:u}){this.error$=new C.Subject;this.playingRepresentation$=new C.ValueSubject(void 0);this.playingRepresentationInit$=new C.ValueSubject(void 0);this.currentSegmentLength$=new C.ValueSubject(0);this.onLastSegment$=new C.ValueSubject(!1);this.fullyBuffered$=new C.ValueSubject(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new ye;this.downloadAbortController=new ye;this.subscription=new C.Subscription;this.startWith=(0,C.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,C.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=nr(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,C.assertNonNullable)(i,"No init buffer for starting representation"),(0,C.assertNonNullable)(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a)}.bind(this));this.switchTo=(0,C.abortable)(this.destroyAbortController.signal,async function*(e,t=!0){var l;if((0,C.isNullable)(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);(0,C.assertNonNullable)(r,`No such representation ${e}`),(0,C.assertNonNullable)(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let a=this.initData.get(r.id),n=this.segments.get(r.id);(0,C.assertNonNullable)(a,"No init buffer for switching representation"),(0,C.assertNonNullable)(n,"No segments for switching representation");let o=(l=this.getCurrentPosition())!=null?l:0,u=p=>p.segment.bufferStatus!=="fed",c=p=>{let h=this.representations.get(p.representationId);return(0,C.assertNonNullable)(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},d=p=>t?u(p)&&c(p):u(p);this.bufferPlaybackQueue.filter(d).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!d(p)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=(0,C.abortable)(this.downloadAbortController.signal,async function*(){let e=(0,C.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,C.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,C.fromEvent)(i,"online").pipe((0,C.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));var c;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=n,this.getCurrentStallDuration=o,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=(c=u==null?void 0:u.baseUrls)!=null?c:[],this.representations=new Map(i.map(d=>[d.id,d]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){(0,C.isNullable)(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.bufferPlaybackQueue.filter(a=>a.segment.networkStatus==="downloaded"),i=t[t.length-1],r=(0,C.isNonNullable)(e)&&(0,C.isNonNullable)(i)?i.segment.time.to-e:0;return Math.max(r,0)}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){var a,n;let t=(n=(a=this.downloadingRepresentationId)!=null?a:this.playingRepresentationId)!=null?n:"",i=this.segments.get(t),r=i==null?void 0:i.find(o=>o.time.from<=e&&o.time.to>=e);return r==null?void 0:r.time.from}getRepresentationInitialTime(){var t;if((0,C.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return((t=e==null?void 0:e[0].time.from)!=null?t:0)/1e3}calculateDurationFromSegments(e){var i;let t=this.segments.get(e);return(t?(i=(0,Cy.default)(t,-1))==null?void 0:i.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,C.getWindow)();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.__polyfill_cancelIdleCallback_gj5gb0nlfie)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_gj5gb0nlfie(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=xi(e),a=xi(t);i=(0,C.isNonNullable)(r)&&(0,C.isNonNullable)(a)&&(0,C.isHigher)(a.quality,r.quality)}else if(this.kind==="audio"){let r=Es(e),a=Es(t);i=(0,C.isNonNullable)(r==null?void 0:r.bitrate)&&(0,C.isNonNullable)(a==null?void 0:a.bitrate)&&a.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new ye,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,ir(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),a;this.initData.has(e.id)&&this.segments.has(e.id)?a=Promise.resolve():(0,C.isNonNullable)(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){var r;try{let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a);this.initDataPromises.set(e.id,n);let{initMetadata:o,initDataView:u,segments:c}=(r=await n)!=null?r:{};if(this.initDataPromises.delete(e.id),(0,C.isNullable)(u)||(0,C.isNullable)(c))return;o&&this.parsedInitData.set(e.id,o);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d),this.segments.set(e.id,c),this.failedDownloads=0}catch(a){i&&this.error$.next({id:"LoadInits",category:C.ErrorCategory.WTF,message:"loadInit threw",thrown:a})}}async maintainNativeBuffer(){var h,m,b;let e=this.getCurrentPosition(),t=this.segments.get((h=this.downloadingRepresentationId)!=null?h:""),i=t==null?void 0:t[(t==null?void 0:t.length)-1];if((0,C.isNullable)(e)||(0,C.isNullable)(i)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let r=this.bufferPlaybackQueue.find(S=>this.withinInterval(e,S.segment.time)),a=this.bufferPlaybackQueue.find(S=>S.segment.bufferStatus!=="fed"),n=this.initData.get((m=a==null?void 0:a.representationId)!=null?m:""),o=this.bufferPlaybackQueue[0],u=this.downloadAbortController.signal,d=((b=this.getCurrentStallDuration())!=null?b:0)>0;this.tuning.dash.useBufferHoldingOnlyOnStall&&d&&(d=e>0);let l=Math.min(this.tuning.dash.minSafeBufferToPlay,i.time.to-e),p=d?this.getForwardPlaybackBufferDuration()>=l:!0;(0,C.isNonNullable)(n)&&(0,C.isNonNullable)(a)&&(0,C.isNonNullable)(r)&&this.playingRepresentationId!==a.representationId&&this.withinAppendInterval(e,a.segment.time)&&(a===r||r.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(n,this.downloadAbortController.signal),this.playingRepresentationId=a.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,C.isNonNullable)(a)&&this.withinAppendInterval(e,a.segment.time)&&p&&(a.segment.loadedBytes===a.segment.size&&a.segment.bufferStatus==="none"?await this.appendSegmentFully(a,u):await this.appendSegmentPartially(a,u)),(0,C.isNonNullable)(o)&&this.withinRemoveInterval(e,o.segment.time)&&await this.removeSegment(o,u),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){(0,C.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,C.isNullable)(t)||(0,C.isNullable)(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);(0,C.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let a=this.selectItemsToLoad();await this.loadItems(a,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if((0,C.isNullable)(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];(0,C.isNullable)(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){(0,C.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;(0,C.isNonNullable)(i)&&this.withinInterval(e,i)?(a=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(a=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&a>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;a-=u-o,r++}return n}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return(0,C.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,C.isNonNullable)(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return(0,C.isNonNullable)(e)?e-i>t:!1}async appendSegmentFully(e,t){if((0,C.isNullable)(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if((0,C.isNullable)(e.segment.data)||(0,C.isNullable)(e.segment.loadedBytes)||(0,C.isNullable)(e.segment.feedingBytes)||(0,C.isNullable)(e.segment.fedBytes)||(0,C.isNullable)(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),a=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;a!=null&&a.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=a.byteLength,await this.nativeBufferManager.append(a,t)&&(e.segment.fedBytes+=a.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,a=(r-i)/4;await this.nativeBufferManager.remove(0,r-a,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||(0,C.isNonNullable)(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let a=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)(0,C.isNonNullable)(o.size)&&a>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())(0,C.isNonNullable)(o.size)&&a>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size)}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())this.updateRepresentationBaseUrl(t,e)}};var qt=require("@vkontakte/videoplayer-shared/es2018");var ko=class extends Wr{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(a,{...n,priority:i}),this.lastDataObtainedTimestampMs=(0,qt.now)(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),kt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,a=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=a);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(_e(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,a={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:a,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=(0,qt.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:qt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:a,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||(0,qt.isNullable)(o)||(0,qt.isNullable)(r)||n.aborted))for(let u of e){let{segment:c}=u,d=c.byte.from-r,l=c.byte.to-r,p=l-d+1,h=d<a,m=l<=a;c.size=p,h&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&m?(c.data=new DataView(t.buffer,t.byteOffset+d,p),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u),c.loadedBytes=Math.min(p,a-d),await this.onDownloadItem(u)):(0,qt.isNonNullable)(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,a-d),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+d,c.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(_e(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var ti=require("@vkontakte/videoplayer-shared/es2018");var Qr=class extends Wr{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(a,{...n,priority:i});if(this.lastDataObtainedTimestampMs=(0,ti.now)(),(0,ti.isNullable)(o))return;let u=e[0],c=new DataView(o);u.segment.size=c.byteLength,u.segment.loadedBytes=c.byteLength,u.segment.data=c,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),kt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(n,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=(0,ti.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:ti.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!_e(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:a}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||(0,ti.isNullable)(u)||(0,ti.isNullable)(o.feedingBytes)||o.networkStatus!=="downloading"||a.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(n)))}updateRepresentationBaseUrl(e,t){if(!_e(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var Vl=G(Qa(),1),Dy=G(bt(),1);var Oe=require("@vkontakte/videoplayer-shared/es2018");var Ao=class extends Qr{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new Oe.ValueSubject(0);this.currentLowLatencySegmentLength$=new Oe.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){var r,a,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,Vl.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if((0,Oe.isNullable)(o)||!_e(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),c=100,d=(r=this.segments.get(o.id))!=null?r:[],l=(n=(a=(0,Dy.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>l>=h.time.from+c&&l<=h.time.to+c);if(p===-1){let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...d,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Oe.assertNonNullable)(t);let i=this.segments.get(t);if(i!=null&&i.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t==null?void 0:t.streams[this.kind],r=(0,Vl.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Oe.isNullable)(r))return;let a=this.segments.get(r.id);if(a!=null&&a.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){var r;if((0,Oe.isNullable)(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return(0,Oe.isNullable)(t)||!_e(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),(0,Oe.isNullable)(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:a,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);a&&n&&this.currentLiveSegmentServerLatency$.next(n-a),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){var n;let i=t.segment.data,r=(n=this.representations.get(t.representationId))==null?void 0:n.segmentReference;if((0,Oe.isNullable)(t.segment.data)||(0,Oe.isNullable)(r)||!_e(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=a.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let a of this.representations.values()){let n=a.segmentReference;if(!_e(n))return;let o=(r=this.segments.get(a.id))!=null?r:[],u=o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.from));if(u!=null&&u.isCurrentLowLatency&&(u.time.to=t.segment.time.to,i=u.time.to-u.time.from,u.isCurrentLowLatency=!1),!!!o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let d=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),l=At(n.segmentTemplateUrl,{segmentTime:d});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:l,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){var a;try{let n=this.tuning.dash.useFetchPriorityHints?i:"auto",o=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,n);this.initDataPromises.set(t.id,o);let{initMetadata:u,initDataView:c,segments:d}=(a=await o)!=null?a:{};if(this.initDataPromises.delete(t.id),(0,Oe.isNullable)(c)||(0,Oe.isNullable)(d))return;u&&this.parsedInitData.set(t.id,u);let l=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,l);let p=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(t.id,p),this.failedDownloads=0}catch(n){r&&this.error$.next({id:"LoadInits",category:Oe.ErrorCategory.WTF,message:"loadInit threw",thrown:n})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],n=0,o=i.length-1;do a.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[a[0]]:a}};var ws=class{static getBufferManager(e,t,i,r){var a;return(a=r.manifest)!=null&&a.live?new Ao(e,t,i,r):_e(i[0].segmentReference)?new Qr(e,t,i,r):new ko(e,t,i,r)}};var Ye=require("@vkontakte/videoplayer-shared/es2018");var Pi=require("@vkontakte/videoplayer-shared/es2018");var Y$=18,By=!1;try{By=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=Y$}catch(s){console.error(s)}var _l=class{constructor(e,t=!1){this.bufferFull$=new Pi.Subject;this.error$=new Pi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Pi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){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()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};By&&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.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:Pi.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,Pi.assertNever)(t)}}},Vy=_l;var ki=(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 xs=class{constructor(e){this.error$=new Ye.Subject;this.subscription=new Ye.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Vy(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,Ye.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ye.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if((0,Ye.isNullable)(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&(i=await this.sourceBufferTaskQueue.remove(r.from,r.to,e));return i}warmUpMediaSource(){!(0,Ye.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,Ye.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return(0,Ye.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,Ye.isNullable)(e)?0:ki(this.sourceBuffer.buffered,e)}async abortBuffer(e){return(0,Ye.isNullable)(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){var e;if(this.subscription.unsubscribe(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null}};var Ro=(s,e)=>{s.video.forEach(t=>{let i=t.representations.filter(({fps:r,height:a})=>{var o;let n=(o=e.find(([u])=>u===`${a}p`))==null?void 0:o[1];return n&&Number.isInteger(n)&&r&&Number.isInteger(r)?r<=n:!0});t.representations=i})};var K$=["timeupdate","progress","play","seeked","stalled","waiting"],_y=["timeupdate","progress","loadeddata","playing","seeked"],zr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new I.Subscription;this.subscriptionRemovable=new I.SubscriptionRemovable;this.representationSubscription=new I.Subscription;this.forceEnded$=new I.Subject;this.destroyController=new ye;this.state$=new ae("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.lastConnectionMetrics$=new I.ValueSubject(void 0);this.lastDownloadMetrics$=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.currentBuffer$=new I.ValueSubject({from:0,to:0});this.bufferLength$=new I.ValueSubject(0);this.nativeBufferLength$=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.initRepresentations=(0,I.abortable)(this.destroyController.signal,async function*(e,t,i){var a;this.tracer.log("initRepresentationsStart",(0,I.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,getCurrentStallDuration:()=>this.currentStallDuration$.getValue(),isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),(0,I.assertNonNullable)(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?(a=this.audioBufferManager)==null?void 0:a.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=(0,I.abortable)(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){(0,I.isNullable)(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new go({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){var r;this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await 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"})}initBuffer(){var t,i;(0,I.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,I.merge)(...K$.map(r=>(0,I.fromEvent)(this.element,r)),(0,I.fromEvent)((0,I.getWindow)(),"online"),(0,I.interval)(this.tuning.dash.tickMaintainInterval)).subscribe(()=>this.tick(),r=>this.error$.next({id:"DashVKPlayer",category:I.ErrorCategory.WTF,message:"Internal logic error",thrown:r})));let e=[...(i=(t=this.source)==null?void 0:t.activeSourceBuffers)!=null?i:[]];this.subscription.add((0,I.merge)(...e.map(r=>(0,I.fromEvent)(r,"updateend"))).subscribe(r=>this.reinitDecoderIfNeeded())),this.subscription.add((0,I.fromEvent)(this.element,"waiting").subscribe(r=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,I.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),a=>this.error$.next({id:"StallWatchdogCallback",category:I.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:a})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}async seek(e,t=!1){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),this.element.currentTime=i/1e3,j.browser.isSafari?(await((o=this.audioBufferManager)==null?void 0:o.seek(i)),await this.videoBufferManager.seek(i)):(await this.videoBufferManager.seek(i),await((u=this.audioBufferManager)==null?void 0:u.seek(i))),this.tracer.log("seek",(0,I.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){(0,I.isNonNullable)(this.element)&&(0,I.isNonNullable)(this.source)&&(0,I.isNonNullable)(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(i=>i.warmUpMediaSource())}calculateDurationFromSegments(e){var t,i;return Math.max(((t=this.videoBufferManager)==null?void 0:t.calculateDurationFromSegments(e))||0,((i=this.audioBufferManager)==null?void 0:i.calculateDurationFromSegments(e))||0)}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(r=>r.destroy()),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&(0,I.getWindow)().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),(0,I.isNonNullable)(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){var e;return((e=this.source)==null?void 0:e.readyState)!=="open"}async reinitDecoderIfNeeded(e=!1){var r,a;let t=(a=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?a:[];if((0,I.isNullable)(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(n=>i>=n.from&&i<=n.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){(0,I.assertNonNullable)(this.element),(0,I.assertNonNullable)(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t)){if(this.tuning.dash.useNewStallExitPolicy)return this.seek(this.element.currentTime*1e3);throw new Error(`Stall timeout exceeded: ${t} ms`)}await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",(0,I.flattenObject)(i))}isStallExceeded(e){var p,h,m,b,S,v,y,x;let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=(0,I.now)(),a=100,n=(h=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?h:0;this.videoLastDataObtainedTimestamp$.next(n);let o=(b=(m=this.audioBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0,u=(v=(S=this.videoBufferManager)==null?void 0:S.getForwardPlaybackBufferDuration())!=null?v:0,c=(x=(y=this.audioBufferManager)==null?void 0:y.getForwardPlaybackBufferDuration())!=null?x:0,d=(0,I.isNonNullable)(this.videoBufferManager)&&u<a&&r-n>i,l=(0,I.isNonNullable)(this.audioBufferManager)&&c<a&&r-o>i;return(d||l)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if((0,I.isNullable)(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",(0,I.flattenObject)(i)),i}parseManifest(e){var t;try{return yo(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=ho(e))!=null?t:{id:"ManifestParsing",category:I.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:i};this.error$.next(r)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,c)=>{var d,l,p,h;return!!((l=(d=this.element)==null?void 0:d.canPlayType)!=null&&l.call(d,u)&&((h=(p=ut())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${c}"`))||o==="text")},r,a;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));t[o]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);o==="audio"&&(a=xo(l),d=a[0]),o==="video"&&(r=wo(l),this.forceVideoCodec&&(0,Oy.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=c.filter(({codecs:p})=>jr(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=Eo(l),d&&(t[o]=c.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=t.video.some(b=>b.hdr),h=t.video.some(b=>!b.hdr);j.display.isHDR&&l&&p?t.video=t.video.filter(b=>b.hdr):h&&(t.video=t.video.filter(b=>!b.hdr));let{videoStreamRepresentaionsFilter:m}=this.tuning.dash;m.length&&Ro(t,m)}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:a}),n}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){(0,I.assertNonNullable)(this.manifest),(0,I.assertNonNullable)(this.element);let a=c=>{this.representationSubscription.add((0,I.fromEvent)(c,"error").pipe((0,I.filter)(d=>{var l;return!!((l=this.element)!=null&&l.played.length)})).subscribe(d=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=vn();let n=(0,I.getWindow)().document,o=n.createElement("source");if(a(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),xr())if(r){let c=n.createElement("source");a(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new xs(this.source),this.videoBufferManager=ws.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,I.isNonNullable)(i)){this.audioNativeBufferManager=new xs(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=ws.getBufferManager("audio",this.audioNativeBufferManager,c,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{var i;e&&(this.timeoutSourceOpenId=(0,I.getWindow)().setTimeout(()=>{if(this.isStreamNotOpen){t();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)),(i=this.source)==null||i.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&(0,I.getWindow)().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add((0,I.merge)(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),(0,I.assertNonNullable)(this.videoBufferManager),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add((0,I.merge)(..._y.map(e=>(0,I.fromEvent)(this.element,e))).pipe((0,I.map)(e=>{var t;return(t=this.videoBufferManager)==null?void 0:t.getPlaybackBufferState()}),(0,I.filter)(I.isNonNullable),(0,I.map)(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add((0,I.merge)(..._y.map(e=>(0,I.fromEvent)(this.element,e))).pipe((0,I.map)(e=>{var t,i,r,a,n,o;return Math.min((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(a=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?a:0,(o=(n=this.audioBufferManager)==null?void 0:n.getForwardPlaybackBufferDuration())!=null?o:0)}),(0,I.filterChanged)()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe((0,I.filter)(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=(0,I.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){var r,a,n;if((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((a=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?a:[]).find(o=>e>=o.from&&e<=o.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await((n=this.audioBufferManager)==null?void 0:n.maintain(e))}};var fe=require("@vkontakte/videoplayer-shared/es2018");var Mo=class extends zr{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;(0,fe.assertNonNullable)(this.manifest),(0,fe.assertNonNullable)(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,Ol.default)((0,Ol.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),_e(i.segmentReference)&&i.segmentReference.totalSegmentsDurationMs&&r.push(i.segmentReference.totalSegmentsDurationMs),r})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){var i,r;(0,fe.assertNonNullable)(this.element);let t=this.element.currentTime*1e3;await Promise.all([(i=this.videoBufferManager)==null?void 0:i.maintain(t),(r=this.audioBufferManager)==null?void 0:r.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){(0,fe.assertNonNullable)(this.element);let e=(0,fe.merge)((0,fe.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,fe.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,fe.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,fe.merge)(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe((0,fe.map)(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=(0,fe.merge)(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe((0,fe.map)(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=(0,fe.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,fe.filterChanged)(),(0,fe.map)(({allBuffersFull:a,someBufferEnded:n})=>a&&n),(0,fe.filter)(a=>a)),r=()=>{var a;try{(a=this.source)==null||a.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:fe.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add((0,fe.merge)(this.forceEnded$,i).pipe((0,fe.filter)(a=>(0,fe.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var Ps=class extends Zi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,Gr.filterChanged)(),(0,Gr.filter)(a=>(0,Gr.isNonNullable)(a))).subscribe(a=>{let n=this.player.calculateDurationFromSegments(a);n&&this.params.output.duration$.next(n/1e3)},r))}getPlayer(){return new Mo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var be=require("@vkontakte/videoplayer-shared/es2018");var ks=require("@vkontakte/videoplayer-shared/es2018"),Ai=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 ks.ValueSubject(e.initial),this.debounced$=new ks.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ze(`raw_${t}`),this.smoothedSeries$=new ze(`smoothed_${t}`),this.reportedSeries$=new ze(`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+=(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,ks.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 $o=class extends Ai{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Jt(this.slow,e,this.params.emaAlphaSlow),this.fast=Jt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Lo=class extends Ai{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=pl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Jt(this.emaSmoothed,e,this.params.emaAlpha);let i=Dv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Co=class extends Ai{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?Jt(this.smoothed,t,this.params.emaAlpha):t}};var ii=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new $o({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Lo({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 Co({initial:e,label:"liveEdgeDelay",...t})}};var Y=require("@vkontakte/videoplayer-shared/es2018");var Yr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var Do=require("@vkontakte/videoplayer-shared/es2018");var As=class s{constructor(e,t){this.currentRepresentation$=new Do.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,Do.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 c=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.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&&_e(t.segmentReference))}};var Bo=class extends zr{constructor(t){super(t);this.liveStreamEndTimestamp=0;this.liveWasInterrupted=!1;this.liveBuffer=ii.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...t.tuning.dashCmafLive.lowLatency.bufferEstimator})}async seek(t){(0,Y.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(t),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()}initBuffer(){super.initBuffer(),this.forcePositionToRepresentationInitialTime()}async forcePositionToRepresentationInitialTime(){var r;let t=this.videoBufferManager,i=(r=t==null?void 0:t.getRepresentationInitialTime())!=null?r:0;await super.seek(i,!1)}async tick(){var i,r,a;await super.tick();let t=((r=(i=this.element)==null?void 0:i.currentTime)!=null?r:0)*1e3;(a=this.liveTextManager)==null||a.maintain(t)}setSourceDuration(){(0,Y.assertNonNullable)(this.source),this.source.duration=Number.MAX_SAFE_INTEGER}isStallExceeded(t){let{keepSilentStallWatchdogWhenNotActive:i}=this.tuning.dashCmafLive,a=this.liveStreamStatus$.getValue()==="active";return(!i||a)&&super.isStallExceeded(t)}async restoreAfterDeepStall(t){let{liveStallReinitInterval:i}=this.tuning.dash,{keepSilentStallWatchdogWhenNotActive:r}=this.tuning.dashCmafLive,a=this.currentStallDuration$.getValue(),o=this.liveStreamStatus$.getValue()==="active";if(a%i===0){let u=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);t.liveLastOffset=u,!o&&r?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(u),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()):this.seek(u).catch(c=>{this.error$.next({id:"stallIntervalCallback",category:Y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:c})})}}async updateManifest(){var d,l;let t=await super.updateManifest();if((0,Y.isNullable)(t))return null;if((0,Y.isNullable)(t.live))return this.error$.next({id:"ManifestParsing",category:Y.ErrorCategory.PARSER,message:"MPD doesnt contain live section for live stream"}),null;this.isLive$.next(!0);let{availabilityStartTime:i,latestSegmentPublishTime:r,streamIsUnpublished:a,streamIsAlive:n}=t.live,o=((d=t.duration)!=null?d:0)/1e3;this.liveSeekableDuration$.next(-1*o),this.liveDuration$.next((r-i)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let u="active";if(n||(u=a?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(u),this.bufferManagers.forEach(p=>p.updateManifest(t)),(l=this.liveTextManager)==null||l.updateLive(t),n&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let p=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seek(p).catch(h=>{this.error$.next({id:"updateManifest",category:Y.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:h})})}return t}prepareManifestUrlString(t,i){return Ae(t,i,2)}updateManifestUrlWithTimeOffset(t){let i=this.liveStreamStatus$.getValue()!=="active"?(0,Y.now)()-this.liveStreamEndTimestamp:0,r=this.normalizeLiveOffset(t+i);this.isActiveLive$.next(r===0),this.manifestUrlString=Ae(this.manifestUrlString,r,2)}createBuffers(t,i,r,a){(0,Y.assertNonNullable)(this.manifest),super.createBuffers(t,i,r,a),As.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new As(this.manifest.streams.text,t))}initRepresentationSubscriptions(){(0,Y.assertNonNullable)(this.element),(0,Y.assertNonNullable)(this.videoBufferManager),this.isActiveLive$.next(this.isLive$.getValue()),super.initRepresentationSubscriptions();let t=this.videoBufferManager,i=this.bufferManagers;this.initStreamDurationOnPauseSubscription(),this.initLiveChangePlaybackRateSubscriptions(),this.initLiveDurationSubscriptions(t),this.initLiveBufferInfoSubscriptions(t,i),this.initLiveMaintainSubscription(i),(0,Y.isNonNullable)(this.liveTextManager)&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$))}initStreamDurationOnPauseSubscription(){(0,Y.assertNonNullable)(this.element);let{liveUpdateInterval:t}=this.tuning.dash,i=()=>(0,Y.interval)(t).subscribe(async r=>{let a=hi(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,a+t,2),this.liveStreamStatus$.getValue()==="active"&&(this.manifest=await this.updateManifest())});this.representationSubscription.add((0,Y.fromEvent)(this.element,"pause").subscribe(r=>{this.livePauseWatchdogSubscription=i(),this.representationSubscription.add(this.livePauseWatchdogSubscription)})),this.representationSubscription.add((0,Y.fromEvent)(this.element,"play").subscribe(r=>{var a;return(a=this.livePauseWatchdogSubscription)==null?void 0:a.unsubscribe()}))}initLiveDurationSubscriptions(t){this.representationSubscription.add(this.liveDuration$.pipe((0,Y.filterChanged)()).subscribe(i=>this.liveStreamEndTimestamp=(0,Y.now)())),this.representationSubscription.add(t.currentLowLatencySegmentLength$.subscribe(i=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!i)return;let r=this.liveSeekableDuration$.getValue()-i/1e3;this.liveSeekableDuration$.next(Math.max(r,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+i/1e3)}))}initLiveChangePlaybackRateSubscriptions(){this.representationSubscription.add((0,Y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.map)(({isActiveLive:t,isLowLatency:i})=>t&&i),(0,Y.filterChanged)(),(0,Y.filter)(t=>!this.isManualDecreasePlaybackInLive())).subscribe(t=>Yr(this.element,1))),this.representationSubscription.add((0,Y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.filter)(t=>!this.isManualDecreasePlaybackInLive())).subscribe(({liveBuffer:t,isActiveLive:i,isLowLatency:r})=>{if(!r||!i)return;let a=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,n=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,o=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,u=t-a,c=1;Math.abs(u)>n&&(c=1+Math.sign(u)*o),Yr(this.element,c)}))}initLiveBufferInfoSubscriptions(t,i){this.representationSubscription.add((0,Y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.filter)(({bufferLength:r,isActiveLive:a,isLowLatency:n})=>a&&n&&!!r),(0,Y.map)(({bufferLength:r})=>r)).subscribe(this.liveBuffer)),this.representationSubscription.add(this.bufferLength$.subscribe(r=>{var n,o;let a=0;if(r){let u=((o=(n=this.element)==null?void 0:n.currentTime)!=null?o:0)*1e3;a=Math.min(...i.map(d=>{var l,p;return(p=(l=d.getLiveSegmentsToLoadState(this.manifest))==null?void 0:l.to)!=null?p:u}))-u}this.liveLoadBufferLength$.getValue()!==a&&this.liveLoadBufferLength$.next(a)})),this.representationSubscription.add((0,Y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:t.currentLiveSegmentServerLatency$}).pipe((0,Y.filter)(({isLive:r})=>r),(0,Y.filterChanged)((r,a)=>a.bufferLength<r.bufferLength),(0,Y.map)(({rtt:r,bufferLength:a,segmentServerLatency:n})=>{let o=hi(this.manifestUrlString,2);return(r/2+a+n+o)/1e3})).subscribe(this.liveLatency$))}initLiveMaintainSubscription(t){let i=0;this.representationSubscription.add((0,Y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,Y.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:r,bufferLength:a})=>{(0,Y.assertNonNullable)(this.element);let n=this.element.playbackRate,o=hi(this.manifestUrlString,2),u=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,c=Math.min(u,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*n),d=this.tuning.dashCmafLive.normalizedActualBufferOffset*n,l=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*n,p=isFinite(r)?r:a,h=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),m=u<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(m);let b="none";if(h?b="active_low_latency":this.isLowLatency$.getValue()&&m?(t.forEach(S=>S.proceedLowLatencyLive()),b="active_low_latency"):o!==0&&p<c?b="live_forward_buffering":p<c+l&&(b="live_with_target_offset"),isFinite(r)&&(i=r>i?r:i),b==="live_forward_buffering"||b==="live_with_target_offset"){let S=i-(c+d),v=this.normalizeLiveOffset(Math.trunc(o+S/n)),y=Math.abs(v-o),x=0;!r||y<=this.tuning.dashCmafLive.offsetCalculationError?x=o:v>0&&y>this.tuning.dashCmafLive.offsetCalculationError&&(x=v),this.manifestUrlString=Ae(this.manifestUrlString,x,2)}(b==="live_with_target_offset"||b==="live_forward_buffering")&&(i=0,this.manifest=await this.updateManifest())},r=>{this.error$.next({id:"updateLive",category:Y.ErrorCategory.VIDEO_PIPELINE,thrown:r,message:"Failed to update live with subscription"})}))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let t=1-this.element.playbackRate;return Number(t.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(t){return Math.trunc(t/1e3)*1e3}};var Kr=class extends Zi{constructor(e){super(e),this.textTracksManager.destroy()}getPlayer(){return new Bo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}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);let o=new be.ValueSubject(1);n(r.playbackRateState$,o),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,be.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(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:c})=>u&&c?u+c:void 0)).subscribe(i.liveTime$)).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:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||(0,be.isNullable)(d)||(t=u-d)})).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,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||(0,be.isNullable)(u)||(0,be.isNullable)(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=$v(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,be.filter)(u=>(0,be.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seek(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var W=require("@vkontakte/videoplayer-shared/es2018");var jy=G(Xe(),1),Ul=G(Qa(),1);var Ri=(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 T=require("@vkontakte/videoplayer-shared/es2018");var Vo=G(Xe(),1),or=G(bt(),1),_o=G(Qa(),1);var qy=G(zc(),1);var Mi=require("@vkontakte/videoplayer-shared/es2018");var J$=18,Fy=!1;try{Fy=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=J$}catch(s){console.error(s)}var Nl=class{constructor(e,t=!1){this.bufferFull$=new Mi.Subject;this.error$=new Mi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){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()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Fy&&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.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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)}}},Uy=Nl;var Fl=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var P=require("@vkontakte/videoplayer-shared/es2018");var Rs=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new P.ValueSubject(0);this.currentLowLatencySegmentLength$=new P.ValueSubject(0);this.currentSegmentLength$=new P.ValueSubject(0);this.onLastSegment$=new P.ValueSubject(!1);this.fullyBuffered$=new P.ValueSubject(!1);this.playingRepresentation$=new P.ValueSubject(void 0);this.playingRepresentationInit$=new P.ValueSubject(void 0);this.error$=new P.Subject;this.gaps=[];this.subscription=new P.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ye;this.switchAbortController=new ye;this.destroyAbortController=new ye;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,P.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 Uy(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Se(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Fl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<d).catch(l=>{this.handleAsyncError(l,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,P.assertNonNullable)(i,"No init buffer for starting representation"),(0,P.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,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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,P.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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,P.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){var u;let t=(0,_o.default)(e,c=>c.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let l=this.representations.get(c);if(!l||!dt(l.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,p)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);(0,P.assertNonNullable)(r,`Representation not found by id ${i}`);let a=this.segments.get(i);(0,P.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,P.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.live),this.baseUrls=(d=c==null?void 0:c.baseUrls)!=null?d:[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ye,(0,P.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,P.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,P.isNullable)(o)||(0,P.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,P.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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,P.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,P.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ye,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var p;if((0,P.isNullable)(e)||(0,P.isNullable)(this.downloadingRepresentationId)||(0,P.isNullable)(this.playingRepresentationId)||(0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||(0,P.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if((0,P.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,P.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,P.isNullable)(r)||(0,P.isNullable)(a))return;let n=r.find(h=>e>=h.time.from&&e<h.time.to);(0,P.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=this.getForwardBufferDuration(e),m=xi(i),b=xi(t),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,P.isNonNullable)(m)&&(0,P.isNonNullable)(b)&&(0,P.isHigher)(m.quality,b.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(S||v?o+=Math.min(h,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let x=(p=[...this.segments.entries()].map(([w,M])=>{let _=M.find(F=>e>=F.time.from&&e<F.time.to);return{representationId:w,status:_==null?void 0:_.status}}).find(w=>w.status==="fed"))==null?void 0:p.representationId;x&&(this.playingRepresentationId=x,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Fl(this.sourceBuffer.buffered)>=this.bufferLimit){let h=this.getForwardBufferDuration(e),m=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<m).catch(b=>{this.handleAsyncError(b,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Vo.default)(d,n))h="high";else{let m=(0,or.default)(d,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(d,t,h).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,or.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let 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,P.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=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,_o.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,a;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,_o.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!dt(n.segmentReference))return;let o=n.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),u=100,c=(i=this.segments.get(n.id))!=null?i:[],d=(a=(r=(0,or.default)(c,-1))==null?void 0:r.time.to)!=null?a:0,l=o==null?void 0:o.findIndex(p=>d>=p.time.from+u&&d<=p.time.to+u);if(l===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(l+1);this.segments.set(n.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,P.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,or.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!dt(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let c=Math.round(e.time.to*a.timescale/1e3).toString(10),d=At(a.segmentTemplateUrl,{segmentTime:c});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}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&&rr&&rr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&rr&&rr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:p,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+y||r<y&&m-h>=y||m<=i+y;return(p==="none"||p==="partially_ejected"&&v&&x&&this.sourceBuffer&&Se(this.mediaSource,this.sourceBuffer)&&!(Ri(this.sourceBuffer.buffered,h)&&Ri(this.sourceBuffer.buffered,m)))&&v&&x});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=a;p<n.length&&(o<=d||u<=l);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")c.push(h);else break}return c}async loadSegments(e,t,i="auto"){dt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){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:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,P.abortable)(o,async function*(){let d=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,P.now)(),!d)return;let l=new DataView(d),p=nr(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,b)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(l);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),kt(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())dt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,P.abortable)(n,async function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,P.fromEvent)(window,"online").pipe((0,P.once)()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,P.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),kt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(dt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,or.default)(e,0).byte.from,to:(0,or.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!dt(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?(c,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Vo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!Se(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=nr(n.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Se(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let d=c.byte.from-i,l=c.byte.to-i,p=l-d+1,h=d<r,m=l<=r;if(!h)continue;let b=nr(o.mime);if(c.status==="downloading"&&m){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?S:b.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(c.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!((0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ri(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ri(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Bl(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=ir(()=>(0,qy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?(0,P.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,nr(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:c,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=l;this.isLive&&dt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,u=>{a||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:P.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Se(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,P.isNullable)(e))return!1;let r=[],a=0,n=u=>{u.sort((d,l)=>d.from-l.from);let c=[u[0]];for(let d=1;d<u.length;d++){let{from:l,to:p}=u[d],h=c[c.length-1];h.to>=l?h.to=Math.max(h.to,p):c.push(u[d])}return c},o=u=>{var d;if(a>=t)return r;r.push({...u.time}),r=n(r);let c=Bl(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){let d=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let p of this.segments.values())for(let h of p)(0,Vo.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:c,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,d)=>c||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Se(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||!Se(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||!Se(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:ki(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Se(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:a}=this.sourceBuffer;for(let n=0;n<a.length;n++){let o=a.start(n)*1e3,u=a.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!Se(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(a=>{if(r&&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}),this.gapDetectionIdleCallback=ir(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||(0,P.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(d=>d.from-t<=n&&d.to+t>=o),c=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:P.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var q=require("@vkontakte/videoplayer-shared/es2018");var No=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new q.Subject;this.firstBytesManifest$=new q.Subject;this.firstBytesRequested$=new q.Subject;this.firstBytesReceived$=new q.Subject;this.lastConnectionType$=new q.ValueSubject(void 0);this.lastConnectionReused$=new q.ValueSubject(void 0);this.lastRequestFirstBytes$=new q.ValueSubject(void 0);this.lastConnectionMetrics$=new q.ValueSubject(void 0);this.lastDownloadMetrics$=new q.ValueSubject(void 0);this.recoverableError$=new q.Subject;this.error$=new q.Subject;this.abortAllController=new ye;this.subscription=new q.SubscriptionRemovable;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,q.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mo(i)),this.trackRequestStart(i,performance.now());let r=(0,q.now)();this.manifestRequested$.next();let a=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Oo);if(a){let n=(0,q.now)();t.log("success",(0,q.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),this.firstBytesManifest$.next();let o=a.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=await a.text();if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",(0,q.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=(0,q.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:d=!1}={}){var le,oe,A;let l=e,p=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(l,(0,q.getWindow)().location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),l=$.toString();break}default:(0,q.assertNever)(t)}this.requestQuic&&(l=Ei(l));let m=this.abortAllController.signal,b;if(n){let $=new ye;if(b=(0,q.merge)((0,q.fromEvent)(this.abortAllController.signal,"abort"),(0,q.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(k){Oo(k)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(k){Oo(k)}m=$.signal}let S=0,v=(0,q.now)();h.log("startRequest",(0,q.flattenObject)({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested$.next();let y=yield this.doFetch(l,{priority:a,headers:p,signal:m},{ignoreNetworkErrors:d}),x=(0,q.now)();if(!y)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(b),null;if((le=this.throughputEstimator)==null||le.addRawRtt(x-v),!y.ok||!y.body){this.unsubscribeAbortSubscription(b);let $=`Fetch error ${y.status}: ${y.statusText}`;return h.error("error",{message:$}),h.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){this.unsubscribeAbortSubscription(b);let $=(0,q.now)(),k={requestStartedAt:v,requestEndedAt:$,duration:$-v};return h.log("endRequest",(0,q.flattenObject)(k)),h.end(),y.arrayBuffer()}let w=y.body;if(o){let $;[w,$]=y.body.tee(),(oe=this.throughputEstimator)==null||oe.trackStream($,u)}let M=w.getReader(),_,F=parseInt((A=y.headers.get("content-length"))!=null?A:"",10);Number.isFinite(F)&&(_=F),!_&&i&&(_=i.to-i.from+1);let O=_?new Uint8Array(_):new Uint8Array(0),H=!1,V=$=>{this.unsubscribeAbortSubscription(b),H=!0,Oo($)},Q=(0,q.abortable)(m,async function*({done:$,value:k}){if(S===0&&(this.lastRequestFirstBytes$.next((0,q.now)()-v),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(b);return}if(!$&&k){if(c&&_)O.set(k,S),S+=k.byteLength;else{let R=new Uint8Array(O.length+k.length);R.set(O),R.set(k,O.length),O=R,S+=k.byteLength}r==null||r(new DataView(O.buffer),S),yield M==null?void 0:M.read().then(Q,V)}}.bind(this));yield M==null?void 0:M.read().then(Q,V),this.unsubscribeAbortSubscription(b);let N=(0,q.now)(),ie={failed:H,requestStartedAt:v,requestEndedAt:N,duration:N-v};if(H)return h.error("endRequest",(0,q.flattenObject)(ie)),h.end(),null;if(S>0){let $=N-v,R=S/($/1e3)*8/1024,Z={bytes:S,speed:R,url:e};this.lastDownloadMetrics$.next(Z)}return h.log("endRequest",(0,q.flattenObject)(ie)),h.end(),O.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,q.abortable)(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=a+1===c,u&&(n=Math.min(c,r),o=Math.max(d,a))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!l)return null;let p=new DataView(l,r-n,a-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(l,m.from-n,m.to-m.from+1);else{let y=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(l),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,q.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...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,(0,q.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=fo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,q.getWindow)()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processPerformanceResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in(0,q.getWindow)().navigator))return"unknown";let e=(0,q.getWindow)().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,a=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(a=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=a),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,a),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),a=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(a===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch(t){this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:q.ErrorCategory.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}async fetchRepresentation(e,t,i){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,q.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}async doFetch(e,t,i){let r=await vt(e,t);if(r.ok)return r;if(i!=null&&i.ignoreNetworkErrors)return;let a=await r.text(),n=parseInt(a);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:q.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:q.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:q.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:q.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:q.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Oo=s=>{if(!kt(s))throw s};var Fo=require("@vkontakte/videoplayer-shared/es2018");var Ms=class s{constructor(e,t){this.currentRepresentation$=new Fo.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,Fo.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 c=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.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&&dt(t.segmentReference))}};var eL=["timeupdate","progress","play","seeked","stalled","waiting"],tL=["timeupdate","progress","loadeddata","playing","seeked"];var Uo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;this.subscriptionRemovable=new T.SubscriptionRemovable;this.representationSubscription=new T.Subscription;this.state$=new ae("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested$=new T.Subject;this.firstBytesManifest$=new T.Subject;this.manifestReceived$=new T.Subject;this.firstBytesRequested$=new T.Subject;this.firstBytesReceived$=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.lastConnectionMetrics$=new T.ValueSubject(void 0);this.lastDownloadMetrics$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new ye;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ae(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,async function*(){var u,c;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=yo(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(d){let l=(u=ho(e))!=null?u:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(l)}if(!t)return null;let i=(d,l,p)=>{var h,m,b,S;return!!((m=(h=this.element)==null?void 0:h.canPlayType)!=null&&m.call(h,l)&&((S=(b=ut())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${l}; codecs="${p}"`))||d==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:d,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:h}=t.live,m=((c=t.duration)!=null?c:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((l-d)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let b="active";if(h||(b=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(b),h&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let S=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(S).catch(v=>{this.error$.next({id:"updateManifest",category:T.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:v})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let d of["video","audio"]){let p=t.streams[d].filter(({mime:m,codecs:b})=>i(d,m,b));r[d]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let m=p.map(({codecs:b})=>b);d==="audio"&&(n=xo(m),h=n[0]),d==="video"&&(a=wo(m),this.forceVideoCodec&&(0,jy.default)(a,this.forceVideoCodec)?h=this.forceVideoCodec:h=a[0]),h&&(r[d]=p.filter(({codecs:b})=>jr(b)===h))}else{let m=new Set(p.map(({codecs:b})=>b));h=Eo(m),h&&(r[d]=p.filter(({codecs:b})=>b.startsWith(h)))}if(d==="video"){let m=this.tuning.preferHDR,b=r.video.some(y=>y.hdr),S=r.video.some(y=>!y.hdr);j.display.isHDR&&m&&b?r.video=r.video.filter(y=>y.hdr):S&&(r.video=r.video.filter(y=>!y.hdr));let{videoStreamRepresentaionsFilter:v}=this.tuning.dash;v.length&&Ro(r,v)}}let o={...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,async function*(e,t,i){var l;this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,T.fromEvent)(p,"error").pipe((0,T.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=vn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),xr())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 Rs("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Rs("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(Ms.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ms(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.merge)(...tL.map(p=>(0,T.fromEvent)(this.element,p))).pipe((0,T.map)(p=>this.element?ki(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:h}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,T.interval)(h).subscribe(m=>{let b=hi(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,b+h,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,T.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Yr(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:h})=>h),(0,T.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,T.map)(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=hi(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(x)>v&&(w=1+Math.sign(x)*y),Yr(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let v=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(x=>{var w,M;return(M=(w=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?M:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=hi(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,M=isFinite(h)?h:m,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),F=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(F);let O="none";if(_?O="active_low_latency":this.isLowLatency$.getValue()&&F?(this.bufferManagers.forEach(H=>H.proceedLowLatencyLive()),O="active_low_latency"):S!==0&&M<y?O="live_forward_buffering":M<y+w&&(O="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),O==="live_forward_buffering"||O==="live_with_target_offset"){let H=p-(y+x),V=this.normalizeLiveOffset(Math.trunc(S+H/b)),Q=Math.abs(V-S),N=0;!h||Q<=this.tuning.dashCmafLive.offsetCalculationError?N=S:V>0&&Q>this.tuning.dashCmafLive.offsetCalculationError&&(N=V),this.manifestUrlString=Ae(this.manifestUrlString,N,2)}(O==="live_with_target_offset"||O==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let u=(0,T.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,T.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=(0,T.combine)({allBuffersFull:u,someBufferEnded:c}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,T.filter)(p=>p));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(l=this.manifest.duration)!=null?l:0,...(0,Ul.default)((0,Ul.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),dt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,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 No({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=ii.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){(0,T.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ae(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){var t,i,r;await((t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio)),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...eL.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Ri(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var w,M,_,F,O,H,V,Q,N,ie,le;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||((w=this.source)==null?void 0:w.readyState)!=="open")return;let d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=(0,T.now)(),h=100,m=(_=(M=this.videoBufferManager)==null?void 0:M.lastDataObtainedTimestamp)!=null?_:0;this.videoLastDataObtainedTimestamp$.next(m);let b=(O=(F=this.audioBufferManager)==null?void 0:F.lastDataObtainedTimestamp)!=null?O:0,S=(V=(H=this.videoBufferManager)==null?void 0:H.getForwardBufferDuration())!=null?V:0,v=(N=(Q=this.audioBufferManager)==null?void 0:Q.getForwardBufferDuration())!=null?N:0,y=S<h&&p-m>r,x=this.audioBufferManager&&v<h&&p-b>r;if((!t||c)&&((y||x)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%a===0){let oe=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(oe),this.updateManifest()):this.seekLive(oe).catch(A=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),l.liveLastOffset=oe}else{let oe=this.element.currentTime*1e3;(ie=this.videoBufferManager)==null||ie.maintain(oe),(le=this.audioBufferManager)==null||le.maintain(oe),l.position=oe}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){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)}async seek(e,t){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),Ri(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let c of u.gaps)(r&&c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=a&&c.to+o>a&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?n.push(1/0):n.push(c.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,T.flattenObject)(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var at=require("@vkontakte/videoplayer-shared/es2018"),qo=class{constructor(){this.subscription=new at.Subscription;this.pipSize$=new at.ValueSubject(void 0);this.videoSize$=new at.ValueSubject(void 0);this.elementSize$=new at.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=at.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,at.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,at.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,at.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 ur=class{constructor(e){this.subscription=new W.Subscription;this.videoState=new ae("stopped");this.observableVideo=null;this.droppedFramesManager=new Or;this.stallsManager=new uo;this.elementSizeManager=new qo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yi;this.audioTrackSwitchHistory=new yi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,W.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Nr(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 mt(e.source.url),this.params=e,this.video=Je(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Uo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,W.isNullable)(this.observableVideo)&&(this.observableVideo=tt(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:W.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,W.filter)(l=>!!l.length),(0,W.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,W.map)(l=>l.to.state!=="none"),(0,W.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),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.currentBuffer$,e.currentNativeBuffer$),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.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),a(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,W.filter)(W.isNonNullable),(0,W.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,W.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(Nt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Ii({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(et(this.video,t.volume,i.volumeState$,r)),this.subscription.add(ft(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(gt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams(),h=this.player.getCodecs();if((0,W.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of p.audio){b.push(Cl(S));let v=[];for(let y of S.representations){let x=Es(y);v.push(x),this.audioTracksMap.set(x,{stream:S,representation:y})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of p.video){m.push(Dl(b));let S=[];for(let v of b.representations){let y=xi({...v,streamId:b.id});y&&(S.push(y),this.videoTracksMap.set(y,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of p.text)for(let S of b.representations){let v=$y(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,W.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,W.fromEvent)(this.video,"progress")).pipe((0,W.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,W.throttle)(u))),this.subscription.add(o.subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,S=[...this.videoTracksMap.keys()].find(y=>{var x;return((x=this.videoTracksMap.get(y))==null?void 0:x.representation.id)===m.id});(0,W.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),l==="manifest_ready")await this.player.initRepresentations(m.id,b==null?void 0:b.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),b){let y=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",b.id,y)}},r)),this.subscription.add((0,W.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,W.merge)((0,W.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,W.map)(l=>l.to)))}).pipe((0,W.map)(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),(0,W.filterChanged)()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,W.filterChanged)()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Dl(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,W.filterChanged)()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Cl(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var p,h;if(l!=null&&l.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe((0,W.map)(({to:l})=>l==="ready"),(0,W.filterChanged)());this.subscription.add((0,W.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,W.merge)(c,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,W.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,W.observableFrom)(["init"])).pipe((0,W.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var O,H,V,Q,N,ie,le,oe,A,$,k,R,Z;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Na:Oa,t=this.params.tuning.useNewAutoSelectVideoTrack?io:to,i=this.params.tuning.useNewAutoSelectVideoTrack?Ft:eo,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(O=r.videoTrack.getState())==null?void 0:O.id,u=[...this.videoTracksMap.keys()].find(({id:K})=>K===o),c=a.currentVideoTrack$.getValue(),d=((Q=(V=r.videoStream.getState())!=null?V:u&&((H=this.videoTracksMap.get(u))==null?void 0:H.stream))!=null?Q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:K})=>K===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=ki(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=(N=r.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(ie=[...this.audioStreamsMap.keys()].find(({id:K})=>K===(v==null?void 0:v.id)))!=null?ie:this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let K=e(u,p,(le=this.audioStreamsMap.get(y))!=null?le:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(oe=K==null?void 0:K.bitrate)!=null?oe:-1/0)}if(c){let K=e(c,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,($=K==null?void 0:K.bitrate)!=null?$:-1/0)}}let w=u;(n||!w)&&(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:x,forwardBufferHealth:S,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let M=y&&t(w,p,(k=this.audioStreamsMap.get(y))!=null?k:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),_=(R=this.videoTracksMap.get(w))==null?void 0:R.representation,F=M&&((Z=this.audioTracksMap.get(M))==null?void 0:Z.representation);if(_&&F)return[_,F];if(_&&!F&&this.audioTracksMap.size===0)return[_,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:W.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),Ze(this.video),this.tracer.end()}};var $s=class extends ur{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/es2018");var Ls=class extends ur{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 c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(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:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).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:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||(0,ge.isNullable)(d)||(t=u-d)})).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,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||(0,ge.isNullable)(u)||(0,ge.isNullable)(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=Ly(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,ge.filter)(u=>(0,ge.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Hy="X-Playback-Duration",ql=async s=>{var r;let e=await vt(s),t=await 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(Hy)?parseInt(e.headers.get(Hy),10):void 0};var ne=require("@vkontakte/videoplayer-shared/es2018");var Hl=G(oc(),1);var jo=require("@vkontakte/videoplayer-shared/es2018");var rL=s=>{let e=null;if(s.QUALITY&&(e=Si(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,jo.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},aL=(s,e)=>{var a,n;let t=s.split(`
|
|
179
179
|
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!d)){if(c){let l=(0,Hl.default)(c[1].split(",").map(y=>y.split("="))),p=(a=l.QUALITY)!=null?a:`stream-${l.BANDWIDTH}`,h=rL(l),m;l.BANDWIDTH&&(m=parseInt(l.BANDWIDTH,10)/1e3||void 0),!m&&l["AVERAGE-BANDWIDTH"]&&(m=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,S;if(l.RESOLUTION){let[y,x]=l.RESOLUTION.split("x").map(w=>parseInt(w,10));y&&x&&(S={width:y,height:x})}let v=new URL(t[++o],e).toString();h&&i.push({id:p,quality:h,url:v,bandwidth:m,size:S,fps:b})}if(d){let l=(0,Hl.default)(d[1].split(",").map(b=>{let S=b.indexOf("=");return[b.substring(0,S),b.substring(S+1)]}).map(([b,S])=>[b,S.replace(/^"|"$/g,"")])),p=(n=l.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=l.LANGUAGE,m=l.NAME;p&&h&&r.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},sL=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),jl=0,Wy=async(s,e=s,t,i)=>{let a=await(await vt(s,i)).text();jl+=1;try{let{qualityManifests:n,textTracks:o}=aL(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(jl<=t.manifestRetryMaxCount)return await sL((0,jo.getExponentialDelay)(jl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Wy(s,e,t)}return{qualityManifests:[],textTracks:[]}},Ho=Wy;var pt=require("@vkontakte/videoplayer-shared/es2018");var Wo=class{constructor(e,t,i,r,a){this.subscription=new pt.Subscription;this.abortControllers={destroy:new ye,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new pt.ValueSubject(null);this.getCurrentTime$=new pt.ValueSubject(null);this.error$=new pt.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe((0,pt.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()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await vt(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
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],c=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:c}),a=a+d,!i.segmentStartTime){let l=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-l}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let c=new Date(u);c.setMilliseconds(0),a=c.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,pt.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([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ye;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:pt.ErrorCategory.WTF,thrown:t,message:e})}};var Cs=class{constructor(e){this.subscription=new ne.Subscription;this.videoState=new ae("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ne.ValueSubject([]);this.liveOffset=new Xi;this.manifestStartTime$=new ne.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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,ne.assertNever)(t)}};var i;this.params=e,this.video=Je(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ne.VideoQuality.INVARIANT,url:this.params.source.url};let t=(r,a)=>Ho(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 Wo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new mt(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:ne.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:ne.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ne.ValueSubject((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:ne.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=tt(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.currentBuffer$,e.currentNativeBuffer$),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(et(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ft(this.video,t.playbackRate,r.playbackRateState$,i)),a(gt(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"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,ne.filterChanged)(),(0,ne.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,ne.isNonNullable)(c.to)){let l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(We(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,c,d;let o=(d=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,ne.combine)({startTime:this.manifestStartTime$.pipe((0,ne.filter)(ne.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,ne.map)(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,ne.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ne.observableFrom)(["init"])).pipe((0,ne.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),Ze(this.video)}prepare(){var o,u,c;let e=this.selectManifest();if((0,ne.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[p,h]of[[d,"mq"],[l,"lq"]]){let m=String(parseFloat(p||""));h&&p&&r.searchParams.set(h,m)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ae(r.toString(),this.liveOffset.getTotalOffset(),a);(c=this.liveTextManager)==null||c.prepare(n),this.video.setAttribute("src",n),this.video.load(),ql(n).then(d=>{var l;if(!(0,ne.isNullable)(d))this.maxSeekBackTime$.next(d);else{let p=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();((0,ne.isNullable)(p)||!isFinite(p))&&vt(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let S=new URL(m,n).toString();ql(S).then(v=>{(0,ne.isNullable)(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ne.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=Ae(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 de=require("@vkontakte/videoplayer-shared/es2018");var Ds=class{constructor(e){this.subscription=new de.Subscription;this.videoState=new ae("stopped");this.manifests$=new de.ValueSubject([]);this.unmuteAfterBrowserResetsHappened=new de.ValueSubject(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,de.assertNever)(t)}};this.textTracksManager=new mt(e.source.url),this.params=e,this.video=Je(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:de.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Ho(Ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:de.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:de.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=tt(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.currentBuffer$,e.currentNativeBuffer$),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,de.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Nt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ft(this.video,t.playbackRate,r.playbackRateState$,i)),Ii({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(et(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,de.isNonNullable)(c.to)){let m=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let b=this.manifests$.getValue().find(S=>S.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(We(b.url)))}let l=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(l!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(l),m.playbackRate=l)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe((0,de.map)(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!j.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,de.merge)((0,de.fromEvent)(o,"addtrack"),(0,de.fromEvent)(o,"removetrack"),(0,de.fromEvent)(o,"change"),(0,de.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,de.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,de.observableFrom)(["init"])).pipe((0,de.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ze(this.video)}prepare(){var a,n;let e=this.selectManifest();if((0,de.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[c,d]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(c||""));d&&c&&r.searchParams.set(d,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:de.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Qy=G(bi(),1),Wl=G(Hi(),1),zy=G(bt(),1);var Ee=require("@vkontakte/videoplayer-shared/es2018");var Bs=class{constructor(e){this.subscription=new Ee.Subscription;this.videoState=new ae("stopped");this.trackUrls={};this.textTracksManager=new mt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let 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"?B(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,Ee.assertNever)(e)}};this.params=e,this.video=Je(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Qy.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,Wl.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:Ee.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=tt(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.currentNativeBuffer$),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,Ee.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Nt(this.video,t.isLooped,i)),Ii({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(et(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ft(this.video,t.playbackRate,r.playbackRateState$,i)),a(gt(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,Ee.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),l=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(d!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=(0,Ee.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Ee.observableFrom)(["init"])).pipe((0,Ee.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),Ze(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,Ee.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,Ee.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ei(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(We(t))}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ee.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var c,d;this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=Ft(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=(c=this.params.output.currentVideoTrack$.getValue())==null?void 0:c.quality,a=!!(e.max||e.min),n=(0,Wl.default)(this.trackUrls).map(l=>l.track);if(!r||!a||Br(e,n[0].quality,(d=(0,zy.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?(0,Ee.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,Ee.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var we=require("@vkontakte/videoplayer-shared/es2018");var Yy=require("@vkontakte/videoplayer-shared/es2018"),Gy=["stun:videostun.mycdn.me:80"],nL=1e3,oL=3,Ql=()=>null,Qo=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Ql;this.externalStopCallback=Ql;this.externalErrorCallback=Ql;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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Gy}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Yy.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),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),nL)}normalizeOptions(e={}){let t={stunServerList:Gy,maxRetryNumber:oL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Vs=class{constructor(e){this.videoState=new ae("stopped");this.maxSeekBackTime$=new we.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let 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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,we.assertNever)(e)}};this.subscription=new we.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Je(e.container,e.tuning),this.liveStreamClient=new Qo(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ze(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:we.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,we.merge)(this.videoState.stateChangeStarted$.pipe((0,we.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,we.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=tt(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(r.currentBuffer$,e.currentNativeBuffer$),a(gt(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(et(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,we.assertNever)(n.to)}},i)).add((0,we.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,we.observableFrom)(["init"])).pipe((0,we.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:we.VideoQuality.INVARIANT}),this.video.srcObject=e,B(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:we.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:we.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Xr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};var E=require("@vkontakte/videoplayer-shared/es2018");var ri=require("@vkontakte/videoplayer-shared/es2018");var Ky=s=>new ri.Observable(e=>{let t=new ri.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe((0,ri.map)(({from:c,to:d})=>`${c}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe((0,ri.map)(({type:c})=>c!==void 0)),n=new ri.Subject,o=0,u="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),s.maxTransitionInterval),X({m:"hangup.set",l:c,id:o})})),t.add(r.subscribe(()=>{X({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(c=>{o&&(X({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval),X({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var St=require("@vkontakte/videoplayer-shared/es2018");function Xy(){return new(window.AudioContext||window.webkitAudioContext)}var _s=class _s{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ye;this.subscriptions=new St.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,St.filter)(a=>!!a.type),(0,St.once)()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){j.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,St.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,St.filter)(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),(0,St.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}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Xy();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await 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:_s.errorId,category:St.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${_s.errorId} exception`,thrown:e})}};_s.errorId="VolumeMultiplierManager";var Jr=_s;var uL={chunkDuration:5e3,maxParallelRequests:5},Os=class{constructor(e){this.current$=new E.ValueSubject({type:void 0});this.providerError$=new E.Subject;this.noAvailableProvidersError$=new E.Subject;this.volumeMultiplierError$=new E.Subject;this.providerOutput={position$:new E.ValueSubject(0),duration$:new E.ValueSubject(1/0),volume$:new E.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new E.ValueSubject([]),currentVideoStream$:new E.ValueSubject(void 0),availableVideoTracks$:new E.ValueSubject([]),currentVideoTrack$:new E.ValueSubject(void 0),availableVideoCodecs$:new E.ValueSubject([]),availableAudioStreams$:new E.ValueSubject([]),currentAudioStream$:new E.ValueSubject(void 0),availableAudioTracks$:new E.ValueSubject([]),availableAudioCodecs$:new E.ValueSubject([]),currentVideoSegmentLength$:new E.ValueSubject(0),currentAudioSegmentLength$:new E.ValueSubject(0),isAudioAvailable$:new E.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new E.ValueSubject(!1),autoVideoTrackLimits$:new E.ValueSubject(void 0),currentBuffer$:new E.ValueSubject(void 0),currentNativeBuffer$:new E.ValueSubject(void 0),isBuffering$:new E.ValueSubject(!0),error$:new E.Subject,fetcherError$:new E.Subject,fetcherRecoverableError$:new E.Subject,warning$:new E.Subject,willSeekEvent$:new E.Subject,soundProhibitedEvent$:new E.Subject,seekedEvent$:new E.Subject,loopedEvent$:new E.Subject,endedEvent$:new E.Subject,manifestRequested$:new E.Subject,firstBytesManifest$:new E.Subject,manifestReceived$:new E.Subject,firstBytesRequested$:new E.Subject,firstBytesReceived$:new E.Subject,firstBytesEvent$:new E.Subject,loadedMetadataEvent$:new E.Subject,firstFrameEvent$:new E.Subject,canplay$:new E.Subject,isLive$:new E.ValueSubject(void 0),isLiveEnded$:new E.ValueSubject(null),canPlayLiveTailBuffer$:new E.ValueSubject(!1),isLowLatency$:new E.ValueSubject(!1),canChangePlaybackSpeed$:new E.ValueSubject(!0),liveTime$:new E.ValueSubject(void 0),liveBufferTime$:new E.ValueSubject(void 0),liveLatency$:new E.ValueSubject(void 0),severeStallOccurred$:new E.Subject,availableTextTracks$:new E.ValueSubject([]),currentTextTrack$:new E.ValueSubject(void 0),hostname$:new E.ValueSubject(void 0),httpConnectionType$:new E.ValueSubject(void 0),httpConnectionReused$:new E.ValueSubject(void 0),httpConnectionMetrics$:new E.ValueSubject(void 0),httpDownloadMetrics$:new E.ValueSubject(void 0),inPiP$:new E.ValueSubject(!1),inFullscreen$:new E.ValueSubject(!1),element$:new E.ValueSubject(void 0),elementVisible$:new E.ValueSubject(!0),availableSources$:new E.ValueSubject(void 0),is3DVideo$:new E.ValueSubject(!1),playbackState$:new E.ValueSubject(""),getCurrentTime$:new E.ValueSubject(null)};this.subscription=new E.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Nu([...vy(this.params.tuning),...gy(this.params.tuning)]).filter(c=>(0,E.isNonNullable)(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(c=>!(0,zl.default)(r,c)),...t.filter(c=>(0,zl.default)(r,c))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",(0,E.flattenObject)(a)),this.screenFormatsIterator=new Xr(a);let n=[...$l(!0),...$l(!1)];this.chromecastFormatsIterator=new Xr(n.filter(c=>(0,E.isNonNullable)(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Jr.isSupported()&&(this.volumeMultiplierManager=new Jr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){X.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Xr(e))}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,E.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:E.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,E.assertNever)(e)}}createScreenProvider(e){var u,c;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 d=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);(0,E.assertNonNullable)(d);let{useDashProviderVirtual:p,useDashProviderVirtualMobile:h}=this.params.tuning,{isMobile:m}=j.device;return!m&&p||m&&h?new Ps({...o,source:d,sourceHls:l,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):new $s({...o,source:d,sourceHls:l,forceVideoCodec:(c=this.videoCodecsIterator)==null?void 0:c.getValue()})}case"DASH_LIVE_CMAF":{let d=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(d),this.params.tuning.useDashProviderVirtual&&!j.device.isMobile?new Kr({...o,source:d}):this.params.tuning.useDashProviderVirtualMobile&&j.device.isMobile?new Kr({...o,source:d}):new Ls({...o,source:d})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let d=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(d),new Ds({...o,source:d})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(d),new Cs({...o,source:d,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let d=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(d),new Bs({...o,source:d})}case"DASH_LIVE":{let d=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(d),new Pv({...o,source:d,config:{...uL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let d=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(d),new Vs({container:i,source:d,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,E.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o={meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof Gt){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return(0,E.assertNonNullable)(c),new ya({...o,chromecastConnector:c})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,E.assertNonNullable)(u),new Da({...o,connection:u})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,E.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,E.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,E.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{...e,url:i(e.url)}}return(0,Jy.default)((0,Gl.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new E.Subscription,t=!1,i=0;e.add((0,E.merge)(this.providerOutput.error$.pipe((0,E.filter)(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),Ky({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,E.map)(a=>({id:`ProviderHangup:${a}`,category:E.ErrorCategory.WTF,message:`A ${a} 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 a=this.params.desiredState.playbackState.transitionEnded$.pipe((0,E.filter)(({to:n})=>n==="playing"),(0,E.once)()).subscribe(()=>t=!0);e.add(a)}));let r=()=>{let a=X.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&(0,E.getWindow)().console.log(`===== DASH_LIVE DEBUG START ====
|
|
181
181
|
`,a.map(({time:u,data:c,stack:d})=>`${u}: ${JSON.stringify(c)}${d?`
|