@vkontakte/videoplayer-core 2.0.150-dev.31e6196f.0 → 2.0.150-dev.4e3741f9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.150-dev.31e6196f.0
3
- * Fri, 19 Dec 2025 10:49:43 GMT
2
+ * @vkontakte/videoplayer-core v2.0.150-dev.4e3741f9.0
3
+ * Mon, 12 Jan 2026 08:36:09 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-150/doc/
5
5
  */
6
6
  "use strict";var Wy=Object.create;var an=Object.defineProperty;var Qy=Object.getOwnPropertyDescriptor;var Gy=Object.getOwnPropertyNames;var Yy=Object.getPrototypeOf,Ky=Object.prototype.hasOwnProperty;var g=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Xy=(s,e)=>{for(var t in e)an(s,t,{get:e[t],enumerable:!0})},rd=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Gy(e))!Ky.call(s,r)&&r!==t&&an(s,r,{get:()=>e[r],enumerable:!(i=Qy(e,r))||i.enumerable});return s};var q=(s,e,t)=>(t=s!=null?Wy(Yy(s)):{},rd(e||!s||!s.__esModule?an(t,"default",{value:s,enumerable:!0}):t,s)),Jy=s=>rd(an({},"__esModule",{value:!0}),s);var ke=g((Zo,sd)=>{"use strict";var Ss=function(s){return s&&s.Math===Math&&s};sd.exports=Ss(typeof globalThis=="object"&&globalThis)||Ss(typeof window=="object"&&window)||Ss(typeof self=="object"&&self)||Ss(typeof global=="object"&&global)||Ss(typeof Zo=="object"&&Zo)||function(){return this}()||Function("return this")()});var _e=g((XM,ad)=>{"use strict";ad.exports=function(s){try{return!!s()}catch{return!0}}});var vs=g((JM,nd)=>{"use strict";var Zy=_e();nd.exports=!Zy(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var eu=g((ZM,cd)=>{"use strict";var eT=vs(),ld=Function.prototype,od=ld.apply,ud=ld.call;cd.exports=typeof Reflect=="object"&&Reflect.apply||(eT?ud.bind(od):function(){return ud.apply(od,arguments)})});var Oe=g((eL,hd)=>{"use strict";var dd=vs(),pd=Function.prototype,tu=pd.call,tT=dd&&pd.bind.bind(tu,tu);hd.exports=dd?tT:function(s){return function(){return tu.apply(s,arguments)}}});var Hi=g((tL,md)=>{"use strict";var fd=Oe(),iT=fd({}.toString),rT=fd("".slice);md.exports=function(s){return rT(iT(s),8,-1)}});var iu=g((iL,bd)=>{"use strict";var sT=Hi(),aT=Oe();bd.exports=function(s){if(sT(s)==="Function")return aT(s)}});var Pe=g((rL,gd)=>{"use strict";var ru=typeof document=="object"&&document.all;gd.exports=typeof ru>"u"&&ru!==void 0?function(s){return typeof s=="function"||s===ru}:function(s){return typeof s=="function"}});var St=g((sL,Sd)=>{"use strict";var nT=_e();Sd.exports=!nT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var vt=g((aL,vd)=>{"use strict";var oT=vs(),un=Function.prototype.call;vd.exports=oT?un.bind(un):function(){return un.apply(un,arguments)}});var su=g(Id=>{"use strict";var yd={}.propertyIsEnumerable,Td=Object.getOwnPropertyDescriptor,uT=Td&&!yd.call({1:2},1);Id.f=uT?function(e){var t=Td(this,e);return!!t&&t.enumerable}:yd});var ys=g((oL,Ed)=>{"use strict";Ed.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var xd=g((uL,wd)=>{"use strict";var lT=Oe(),cT=_e(),dT=Hi(),au=Object,pT=lT("".split);wd.exports=cT(function(){return!au("z").propertyIsEnumerable(0)})?function(s){return dT(s)==="String"?pT(s,""):au(s)}:au});var Ts=g((lL,kd)=>{"use strict";kd.exports=function(s){return s==null}});var yi=g((cL,Pd)=>{"use strict";var hT=Ts(),fT=TypeError;Pd.exports=function(s){if(hT(s))throw new fT("Can't call method on "+s);return s}});var zi=g((dL,Ad)=>{"use strict";var mT=xd(),bT=yi();Ad.exports=function(s){return mT(bT(s))}});var ut=g((pL,Rd)=>{"use strict";var gT=Pe();Rd.exports=function(s){return typeof s=="object"?s!==null:gT(s)}});var Wi=g((hL,$d)=>{"use strict";$d.exports={}});var ri=g((fL,Ld)=>{"use strict";var nu=Wi(),ou=ke(),ST=Pe(),Md=function(s){return ST(s)?s:void 0};Ld.exports=function(s,e){return arguments.length<2?Md(nu[s])||Md(ou[s]):nu[s]&&nu[s][e]||ou[s]&&ou[s][e]}});var Is=g((mL,Dd)=>{"use strict";var vT=Oe();Dd.exports=vT({}.isPrototypeOf)});var Qi=g((bL,Vd)=>{"use strict";var yT=ke(),Bd=yT.navigator,Cd=Bd&&Bd.userAgent;Vd.exports=Cd?String(Cd):""});var lu=g((gL,qd)=>{"use strict";var Ud=ke(),uu=Qi(),_d=Ud.process,Od=Ud.Deno,Nd=_d&&_d.versions||Od&&Od.version,Fd=Nd&&Nd.v8,_t,ln;Fd&&(_t=Fd.split("."),ln=_t[0]>0&&_t[0]<4?1:+(_t[0]+_t[1]));!ln&&uu&&(_t=uu.match(/Edge\/(\d+)/),(!_t||_t[1]>=74)&&(_t=uu.match(/Chrome\/(\d+)/),_t&&(ln=+_t[1])));qd.exports=ln});var cu=g((SL,Hd)=>{"use strict";var jd=lu(),TT=_e(),IT=ke(),ET=IT.String;Hd.exports=!!Object.getOwnPropertySymbols&&!TT(function(){var s=Symbol("symbol detection");return!ET(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&jd&&jd<41})});var du=g((vL,zd)=>{"use strict";var wT=cu();zd.exports=wT&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var pu=g((yL,Wd)=>{"use strict";var xT=ri(),kT=Pe(),PT=Is(),AT=du(),RT=Object;Wd.exports=AT?function(s){return typeof s=="symbol"}:function(s){var e=xT("Symbol");return kT(e)&&PT(e.prototype,RT(s))}});var Es=g((TL,Qd)=>{"use strict";var $T=String;Qd.exports=function(s){try{return $T(s)}catch{return"Object"}}});var Gt=g((IL,Gd)=>{"use strict";var MT=Pe(),LT=Es(),DT=TypeError;Gd.exports=function(s){if(MT(s))return s;throw new DT(LT(s)+" is not a function")}});var ws=g((EL,Yd)=>{"use strict";var BT=Gt(),CT=Ts();Yd.exports=function(s,e){var t=s[e];return CT(t)?void 0:BT(t)}});var Xd=g((wL,Kd)=>{"use strict";var hu=vt(),fu=Pe(),mu=ut(),VT=TypeError;Kd.exports=function(s,e){var t,i;if(e==="string"&&fu(t=s.toString)&&!mu(i=hu(t,s))||fu(t=s.valueOf)&&!mu(i=hu(t,s))||e!=="string"&&fu(t=s.toString)&&!mu(i=hu(t,s)))return i;throw new VT("Can't convert object to primitive value")}});var Ot=g((xL,Jd)=>{"use strict";Jd.exports=!0});var tp=g((kL,ep)=>{"use strict";var Zd=ke(),_T=Object.defineProperty;ep.exports=function(s,e){try{_T(Zd,s,{value:e,configurable:!0,writable:!0})}catch{Zd[s]=e}return e}});var xs=g((PL,sp)=>{"use strict";var OT=Ot(),NT=ke(),FT=tp(),ip="__core-js_shared__",rp=sp.exports=NT[ip]||FT(ip,{});(rp.versions||(rp.versions=[])).push({version:"3.43.0",mode:OT?"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 bu=g((AL,np)=>{"use strict";var ap=xs();np.exports=function(s,e){return ap[s]||(ap[s]=e||{})}});var Er=g((RL,op)=>{"use strict";var UT=yi(),qT=Object;op.exports=function(s){return qT(UT(s))}});var Nt=g(($L,up)=>{"use strict";var jT=Oe(),HT=Er(),zT=jT({}.hasOwnProperty);up.exports=Object.hasOwn||function(e,t){return zT(HT(e),t)}});var gu=g((ML,lp)=>{"use strict";var WT=Oe(),QT=0,GT=Math.random(),YT=WT(1.1.toString);lp.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+YT(++QT+GT,36)}});var ze=g((LL,dp)=>{"use strict";var KT=ke(),XT=bu(),cp=Nt(),JT=gu(),ZT=cu(),eI=du(),wr=KT.Symbol,Su=XT("wks"),tI=eI?wr.for||wr:wr&&wr.withoutSetter||JT;dp.exports=function(s){return cp(Su,s)||(Su[s]=ZT&&cp(wr,s)?wr[s]:tI("Symbol."+s)),Su[s]}});var mp=g((DL,fp)=>{"use strict";var iI=vt(),pp=ut(),hp=pu(),rI=ws(),sI=Xd(),aI=ze(),nI=TypeError,oI=aI("toPrimitive");fp.exports=function(s,e){if(!pp(s)||hp(s))return s;var t=rI(s,oI),i;if(t){if(e===void 0&&(e="default"),i=iI(t,s,e),!pp(i)||hp(i))return i;throw new nI("Can't convert object to primitive value")}return e===void 0&&(e="number"),sI(s,e)}});var vu=g((BL,bp)=>{"use strict";var uI=mp(),lI=pu();bp.exports=function(s){var e=uI(s,"string");return lI(e)?e:e+""}});var cn=g((CL,Sp)=>{"use strict";var cI=ke(),gp=ut(),yu=cI.document,dI=gp(yu)&&gp(yu.createElement);Sp.exports=function(s){return dI?yu.createElement(s):{}}});var Tu=g((VL,vp)=>{"use strict";var pI=St(),hI=_e(),fI=cn();vp.exports=!pI&&!hI(function(){return Object.defineProperty(fI("div"),"a",{get:function(){return 7}}).a!==7})});var Ip=g(Tp=>{"use strict";var mI=St(),bI=vt(),gI=su(),SI=ys(),vI=zi(),yI=vu(),TI=Nt(),II=Tu(),yp=Object.getOwnPropertyDescriptor;Tp.f=mI?yp:function(e,t){if(e=vI(e),t=yI(t),II)try{return yp(e,t)}catch{}if(TI(e,t))return SI(!bI(gI.f,e,t),e[t])}});var Iu=g((OL,Ep)=>{"use strict";var EI=_e(),wI=Pe(),xI=/#|\.prototype\./,ks=function(s,e){var t=PI[kI(s)];return t===RI?!0:t===AI?!1:wI(e)?EI(e):!!e},kI=ks.normalize=function(s){return String(s).replace(xI,".").toLowerCase()},PI=ks.data={},AI=ks.NATIVE="N",RI=ks.POLYFILL="P";Ep.exports=ks});var xr=g((NL,xp)=>{"use strict";var wp=iu(),$I=Gt(),MI=vs(),LI=wp(wp.bind);xp.exports=function(s,e){return $I(s),e===void 0?s:MI?LI(s,e):function(){return s.apply(e,arguments)}}});var Eu=g((FL,kp)=>{"use strict";var DI=St(),BI=_e();kp.exports=DI&&BI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Yt=g((UL,Pp)=>{"use strict";var CI=ut(),VI=String,_I=TypeError;Pp.exports=function(s){if(CI(s))return s;throw new _I(VI(s)+" is not an object")}});var Gi=g(Rp=>{"use strict";var OI=St(),NI=Tu(),FI=Eu(),dn=Yt(),Ap=vu(),UI=TypeError,wu=Object.defineProperty,qI=Object.getOwnPropertyDescriptor,xu="enumerable",ku="configurable",Pu="writable";Rp.f=OI?FI?function(e,t,i){if(dn(e),t=Ap(t),dn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Pu in i&&!i[Pu]){var r=qI(e,t);r&&r[Pu]&&(e[t]=i.value,i={configurable:ku in i?i[ku]:r[ku],enumerable:xu in i?i[xu]:r[xu],writable:!1})}return wu(e,t,i)}:wu:function(e,t,i){if(dn(e),t=Ap(t),dn(i),NI)try{return wu(e,t,i)}catch{}if("get"in i||"set"in i)throw new UI("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var kr=g((jL,$p)=>{"use strict";var jI=St(),HI=Gi(),zI=ys();$p.exports=jI?function(s,e,t){return HI.f(s,e,zI(1,t))}:function(s,e,t){return s[e]=t,s}});var Re=g((HL,Lp)=>{"use strict";var Ps=ke(),WI=eu(),QI=iu(),GI=Pe(),YI=Ip().f,KI=Iu(),Pr=Wi(),XI=xr(),Ar=kr(),Mp=Nt();xs();var JI=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 WI(s,this,arguments)};return e.prototype=s.prototype,e};Lp.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Ps:r?Ps[t]:Ps[t]&&Ps[t].prototype,o=i?Pr:Pr[t]||Ar(Pr,t,{})[t],u=o.prototype,l,p,c,d,h,m,b,v,S;for(d in e)l=KI(i?d:t+(r?".":"#")+d,s.forced),p=!l&&n&&Mp(n,d),m=o[d],p&&(s.dontCallGetSet?(S=YI(n,d),b=S&&S.value):b=n[d]),h=p&&b?b:e[d],!(!l&&!a&&typeof m==typeof h)&&(s.bind&&p?v=XI(h,Ps):s.wrap&&p?v=JI(h):a&&GI(h)?v=QI(h):v=h,(s.sham||h&&h.sham||m&&m.sham)&&Ar(v,"sham",!0),Ar(o,d,v),a&&(c=t+"Prototype",Mp(Pr,c)||Ar(Pr,c,{}),Ar(Pr[c],d,h),s.real&&u&&(l||!u[d])&&Ar(u,d,h)))}});var pn=g((zL,Bp)=>{"use strict";var ZI=bu(),eE=gu(),Dp=ZI("keys");Bp.exports=function(s){return Dp[s]||(Dp[s]=eE(s))}});var Vp=g((WL,Cp)=>{"use strict";var tE=_e();Cp.exports=!tE(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var hn=g((QL,Op)=>{"use strict";var iE=Nt(),rE=Pe(),sE=Er(),aE=pn(),nE=Vp(),_p=aE("IE_PROTO"),Au=Object,oE=Au.prototype;Op.exports=nE?Au.getPrototypeOf:function(s){var e=sE(s);if(iE(e,_p))return e[_p];var t=e.constructor;return rE(t)&&e instanceof t?t.prototype:e instanceof Au?oE:null}});var Fp=g((GL,Np)=>{"use strict";var uE=Math.ceil,lE=Math.floor;Np.exports=Math.trunc||function(e){var t=+e;return(t>0?lE:uE)(t)}});var As=g((YL,Up)=>{"use strict";var cE=Fp();Up.exports=function(s){var e=+s;return e!==e||e===0?0:cE(e)}});var jp=g((KL,qp)=>{"use strict";var dE=As(),pE=Math.max,hE=Math.min;qp.exports=function(s,e){var t=dE(s);return t<0?pE(t+e,0):hE(t,e)}});var Ru=g((XL,Hp)=>{"use strict";var fE=As(),mE=Math.min;Hp.exports=function(s){var e=fE(s);return e>0?mE(e,9007199254740991):0}});var Rr=g((JL,zp)=>{"use strict";var bE=Ru();zp.exports=function(s){return bE(s.length)}});var $u=g((ZL,Qp)=>{"use strict";var gE=zi(),SE=jp(),vE=Rr(),Wp=function(s){return function(e,t,i){var r=gE(e),a=vE(r);if(a===0)return!s&&-1;var n=SE(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}};Qp.exports={includes:Wp(!0),indexOf:Wp(!1)}});var fn=g((eD,Gp)=>{"use strict";Gp.exports={}});var Xp=g((tD,Kp)=>{"use strict";var yE=Oe(),Mu=Nt(),TE=zi(),IE=$u().indexOf,EE=fn(),Yp=yE([].push);Kp.exports=function(s,e){var t=TE(s),i=0,r=[],a;for(a in t)!Mu(EE,a)&&Mu(t,a)&&Yp(r,a);for(;e.length>i;)Mu(t,a=e[i++])&&(~IE(r,a)||Yp(r,a));return r}});var Lu=g((iD,Jp)=>{"use strict";Jp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Du=g((rD,Zp)=>{"use strict";var wE=Xp(),xE=Lu();Zp.exports=Object.keys||function(e){return wE(e,xE)}});var Bu=g((sD,sh)=>{"use strict";var th=St(),kE=_e(),ih=Oe(),PE=hn(),AE=Du(),RE=zi(),$E=su().f,rh=ih($E),ME=ih([].push),LE=th&&kE(function(){var s=Object.create(null);return s[2]=2,!rh(s,2)}),eh=function(s){return function(e){for(var t=RE(e),i=AE(t),r=LE&&PE(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!th||(r?u in t:rh(t,u)))&&ME(o,s?[u,t[u]]:t[u]);return o}};sh.exports={entries:eh(!0),values:eh(!1)}});var ah=g(()=>{"use strict";var DE=Re(),BE=Bu().values;DE({target:"Object",stat:!0},{values:function(e){return BE(e)}})});var oh=g((oD,nh)=>{"use strict";ah();var CE=Wi();nh.exports=CE.Object.values});var lh=g((uD,uh)=>{"use strict";var VE=oh();uh.exports=VE});var Yi=g((lD,ch)=>{"use strict";var _E=lh();ch.exports=_E});var Rs=g((cD,dh)=>{"use strict";dh.exports=function(){}});var ph=g(()=>{"use strict";var OE=Re(),NE=$u().includes,FE=_e(),UE=Rs(),qE=FE(function(){return!Array(1).includes()});OE({target:"Array",proto:!0,forced:qE},{includes:function(e){return NE(this,e,arguments.length>1?arguments[1]:void 0)}});UE("includes")});var Ti=g((hD,hh)=>{"use strict";var jE=ri();hh.exports=jE});var mh=g((fD,fh)=>{"use strict";ph();var HE=Ti();fh.exports=HE("Array","includes")});var gh=g((mD,bh)=>{"use strict";var zE=mh();bh.exports=zE});var We=g((bD,Sh)=>{"use strict";var WE=gh();Sh.exports=WE});var Lh=g(()=>{"use strict";var iw=Re(),rw=Bu().entries;iw({target:"Object",stat:!0},{entries:function(e){return rw(e)}})});var Bh=g((rC,Dh)=>{"use strict";Lh();var sw=Wi();Dh.exports=sw.Object.entries});var Vh=g((sC,Ch)=>{"use strict";var aw=Bh();Ch.exports=aw});var ki=g((aC,_h)=>{"use strict";var nw=Vh();_h.exports=nw});var Xi=g((nC,Oh)=>{"use strict";Oh.exports={}});var Uh=g((oC,Fh)=>{"use strict";var ow=ke(),uw=Pe(),Nh=ow.WeakMap;Fh.exports=uw(Nh)&&/native code/.test(String(Nh))});var qu=g((uC,Hh)=>{"use strict";var lw=Uh(),jh=ke(),cw=ut(),dw=kr(),Nu=Nt(),Fu=xs(),pw=pn(),hw=fn(),qh="Object already initialized",Uu=jh.TypeError,fw=jh.WeakMap,kn,Bs,Pn,mw=function(s){return Pn(s)?Bs(s):kn(s,{})},bw=function(s){return function(e){var t;if(!cw(e)||(t=Bs(e)).type!==s)throw new Uu("Incompatible receiver, "+s+" required");return t}};lw||Fu.state?(Ut=Fu.state||(Fu.state=new fw),Ut.get=Ut.get,Ut.has=Ut.has,Ut.set=Ut.set,kn=function(s,e){if(Ut.has(s))throw new Uu(qh);return e.facade=s,Ut.set(s,e),e},Bs=function(s){return Ut.get(s)||{}},Pn=function(s){return Ut.has(s)}):(Ji=pw("state"),hw[Ji]=!0,kn=function(s,e){if(Nu(s,Ji))throw new Uu(qh);return e.facade=s,dw(s,Ji,e),e},Bs=function(s){return Nu(s,Ji)?s[Ji]:{}},Pn=function(s){return Nu(s,Ji)});var Ut,Ji;Hh.exports={set:kn,get:Bs,has:Pn,enforce:mw,getterFor:bw}});var zu=g((lC,Wh)=>{"use strict";var ju=St(),gw=Nt(),zh=Function.prototype,Sw=ju&&Object.getOwnPropertyDescriptor,Hu=gw(zh,"name"),vw=Hu&&function(){}.name==="something",yw=Hu&&(!ju||ju&&Sw(zh,"name").configurable);Wh.exports={EXISTS:Hu,PROPER:vw,CONFIGURABLE:yw}});var Gh=g(Qh=>{"use strict";var Tw=St(),Iw=Eu(),Ew=Gi(),ww=Yt(),xw=zi(),kw=Du();Qh.f=Tw&&!Iw?Object.defineProperties:function(e,t){ww(e);for(var i=xw(t),r=kw(t),a=r.length,n=0,o;a>n;)Ew.f(e,o=r[n++],i[o]);return e}});var Wu=g((dC,Yh)=>{"use strict";var Pw=ri();Yh.exports=Pw("document","documentElement")});var Ku=g((pC,rf)=>{"use strict";var Aw=Yt(),Rw=Gh(),Kh=Lu(),$w=fn(),Mw=Wu(),Lw=cn(),Dw=pn(),Xh=">",Jh="<",Gu="prototype",Yu="script",ef=Dw("IE_PROTO"),Qu=function(){},tf=function(s){return Jh+Yu+Xh+s+Jh+"/"+Yu+Xh},Zh=function(s){s.write(tf("")),s.close();var e=s.parentWindow.Object;return s=null,e},Bw=function(){var s=Lw("iframe"),e="java"+Yu+":",t;return s.style.display="none",Mw.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(tf("document.F=Object")),t.close(),t.F},An,Rn=function(){try{An=new ActiveXObject("htmlfile")}catch{}Rn=typeof document<"u"?document.domain&&An?Zh(An):Bw():Zh(An);for(var s=Kh.length;s--;)delete Rn[Gu][Kh[s]];return Rn()};$w[ef]=!0;rf.exports=Object.create||function(e,t){var i;return e!==null?(Qu[Gu]=Aw(e),i=new Qu,Qu[Gu]=null,i[ef]=e):i=Rn(),t===void 0?i:Rw.f(i,t)}});var Mr=g((hC,sf)=>{"use strict";var Cw=kr();sf.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Cw(s,e,t),s}});var el=g((fC,of)=>{"use strict";var Vw=_e(),_w=Pe(),Ow=ut(),Nw=Ku(),af=hn(),Fw=Mr(),Uw=ze(),qw=Ot(),Zu=Uw("iterator"),nf=!1,ai,Xu,Ju;[].keys&&(Ju=[].keys(),"next"in Ju?(Xu=af(af(Ju)),Xu!==Object.prototype&&(ai=Xu)):nf=!0);var jw=!Ow(ai)||Vw(function(){var s={};return ai[Zu].call(s)!==s});jw?ai={}:qw&&(ai=Nw(ai));_w(ai[Zu])||Fw(ai,Zu,function(){return this});of.exports={IteratorPrototype:ai,BUGGY_SAFARI_ITERATORS:nf}});var $n=g((mC,lf)=>{"use strict";var Hw=ze(),zw=Hw("toStringTag"),uf={};uf[zw]="z";lf.exports=String(uf)==="[object z]"});var Cs=g((bC,cf)=>{"use strict";var Ww=$n(),Qw=Pe(),Mn=Hi(),Gw=ze(),Yw=Gw("toStringTag"),Kw=Object,Xw=Mn(function(){return arguments}())==="Arguments",Jw=function(s,e){try{return s[e]}catch{}};cf.exports=Ww?Mn:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Jw(e=Kw(s),Yw))=="string"?t:Xw?Mn(e):(i=Mn(e))==="Object"&&Qw(e.callee)?"Arguments":i}});var pf=g((gC,df)=>{"use strict";var Zw=$n(),ex=Cs();df.exports=Zw?{}.toString:function(){return"[object "+ex(this)+"]"}});var Vs=g((SC,ff)=>{"use strict";var tx=$n(),ix=Gi().f,rx=kr(),sx=Nt(),ax=pf(),nx=ze(),hf=nx("toStringTag");ff.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(sx(r,hf)||ix(r,hf,{configurable:!0,value:e}),i&&!tx&&rx(r,"toString",ax))}});var bf=g((vC,mf)=>{"use strict";var ox=el().IteratorPrototype,ux=Ku(),lx=ys(),cx=Vs(),dx=Xi(),px=function(){return this};mf.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=ux(ox,{next:lx(+!i,t)}),cx(s,r,!1,!0),dx[r]=px,s}});var Sf=g((yC,gf)=>{"use strict";var hx=Oe(),fx=Gt();gf.exports=function(s,e,t){try{return hx(fx(Object.getOwnPropertyDescriptor(s,e)[t]))}catch{}}});var yf=g((TC,vf)=>{"use strict";var mx=ut();vf.exports=function(s){return mx(s)||s===null}});var If=g((IC,Tf)=>{"use strict";var bx=yf(),gx=String,Sx=TypeError;Tf.exports=function(s){if(bx(s))return s;throw new Sx("Can't set "+gx(s)+" as a prototype")}});var tl=g((EC,Ef)=>{"use strict";var vx=Sf(),yx=ut(),Tx=yi(),Ix=If();Ef.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=vx(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch{}return function(r,a){return Tx(r),Ix(a),yx(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Bf=g((wC,Df)=>{"use strict";var Ex=Re(),wx=vt(),Ln=Ot(),Mf=zu(),xx=Pe(),kx=bf(),wf=hn(),xf=tl(),Px=Vs(),Ax=kr(),il=Mr(),Rx=ze(),kf=Xi(),Lf=el(),$x=Mf.PROPER,Mx=Mf.CONFIGURABLE,Pf=Lf.IteratorPrototype,Dn=Lf.BUGGY_SAFARI_ITERATORS,_s=Rx("iterator"),Af="keys",Os="values",Rf="entries",$f=function(){return this};Df.exports=function(s,e,t,i,r,a,n){kx(t,e,i);var o=function(S){if(S===r&&d)return d;if(!Dn&&S&&S in p)return p[S];switch(S){case Af:return function(){return new t(this,S)};case Os:return function(){return new t(this,S)};case Rf:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,p=s.prototype,c=p[_s]||p["@@iterator"]||r&&p[r],d=!Dn&&c||o(r),h=e==="Array"&&p.entries||c,m,b,v;if(h&&(m=wf(h.call(new s)),m!==Object.prototype&&m.next&&(!Ln&&wf(m)!==Pf&&(xf?xf(m,Pf):xx(m[_s])||il(m,_s,$f)),Px(m,u,!0,!0),Ln&&(kf[u]=$f))),$x&&r===Os&&c&&c.name!==Os&&(!Ln&&Mx?Ax(p,"name",Os):(l=!0,d=function(){return wx(c,this)})),r)if(b={values:o(Os),keys:a?d:o(Af),entries:o(Rf)},n)for(v in b)(Dn||l||!(v in p))&&il(p,v,b[v]);else Ex({target:e,proto:!0,forced:Dn||l},b);return(!Ln||n)&&p[_s]!==d&&il(p,_s,d,{name:r}),kf[e]=d,b}});var Vf=g((xC,Cf)=>{"use strict";Cf.exports=function(s,e){return{value:s,done:e}}});var sl=g((kC,Uf)=>{"use strict";var Lx=zi(),rl=Rs(),_f=Xi(),Nf=qu(),Dx=Gi().f,Bx=Bf(),Bn=Vf(),Cx=Ot(),Vx=St(),Ff="Array Iterator",_x=Nf.set,Ox=Nf.getterFor(Ff);Uf.exports=Bx(Array,"Array",function(s,e){_x(this,{type:Ff,target:Lx(s),index:0,kind:e})},function(){var s=Ox(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,Bn(void 0,!0);switch(s.kind){case"keys":return Bn(t,!1);case"values":return Bn(e[t],!1)}return Bn([t,e[t]],!1)},"values");var Of=_f.Arguments=_f.Array;rl("keys");rl("values");rl("entries");if(!Cx&&Vx&&Of.name!=="values")try{Dx(Of,"name",{value:"values"})}catch{}});var jf=g((PC,qf)=>{"use strict";var Nx=ze(),Fx=Xi(),Ux=Nx("iterator"),qx=Array.prototype;qf.exports=function(s){return s!==void 0&&(Fx.Array===s||qx[Ux]===s)}});var al=g((AC,zf)=>{"use strict";var jx=Cs(),Hf=ws(),Hx=Ts(),zx=Xi(),Wx=ze(),Qx=Wx("iterator");zf.exports=function(s){if(!Hx(s))return Hf(s,Qx)||Hf(s,"@@iterator")||zx[jx(s)]}});var Qf=g((RC,Wf)=>{"use strict";var Gx=vt(),Yx=Gt(),Kx=Yt(),Xx=Es(),Jx=al(),Zx=TypeError;Wf.exports=function(s,e){var t=arguments.length<2?Jx(s):e;if(Yx(t))return Kx(Gx(t,s));throw new Zx(Xx(s)+" is not iterable")}});var Kf=g(($C,Yf)=>{"use strict";var ek=vt(),Gf=Yt(),tk=ws();Yf.exports=function(s,e,t){var i,r;Gf(s);try{if(i=tk(s,"return"),!i){if(e==="throw")throw t;return t}i=ek(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Gf(i),t}});var Vn=g((MC,em)=>{"use strict";var ik=xr(),rk=vt(),sk=Yt(),ak=Es(),nk=jf(),ok=Rr(),Xf=Is(),uk=Qf(),lk=al(),Jf=Kf(),ck=TypeError,Cn=function(s,e){this.stopped=s,this.result=e},Zf=Cn.prototype;em.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=ik(e,i),l,p,c,d,h,m,b,v=function(y){return l&&Jf(l,"normal"),new Cn(!0,y)},S=function(y){return r?(sk(y),o?u(y[0],y[1],v):u(y[0],y[1])):o?u(y,v):u(y)};if(a)l=s.iterator;else if(n)l=s;else{if(p=lk(s),!p)throw new ck(ak(s)+" is not iterable");if(nk(p)){for(c=0,d=ok(s);d>c;c++)if(h=S(s[c]),h&&Xf(Zf,h))return h;return new Cn(!1)}l=uk(s,p)}for(m=a?s.next:l.next;!(b=rk(m,l)).done;){try{h=S(b.value)}catch(y){Jf(l,"throw",y)}if(typeof h=="object"&&h&&Xf(Zf,h))return h}return new Cn(!1)}});var im=g((LC,tm)=>{"use strict";var dk=St(),pk=Gi(),hk=ys();tm.exports=function(s,e,t){dk?pk.f(s,e,hk(0,t)):s[e]=t}});var rm=g(()=>{"use strict";var fk=Re(),mk=Vn(),bk=im();fk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return mk(e,function(i,r){bk(t,i,r)},{AS_ENTRIES:!0}),t}})});var am=g((CC,sm)=>{"use strict";sl();rm();var gk=Wi();sm.exports=gk.Object.fromEntries});var om=g((VC,nm)=>{"use strict";nm.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var lm=g(()=>{"use strict";sl();var Sk=om(),vk=ke(),yk=Vs(),um=Xi();for(_n in Sk)yk(vk[_n],_n),um[_n]=um.Array;var _n});var dm=g((NC,cm)=>{"use strict";var Tk=am();lm();cm.exports=Tk});var nl=g((FC,pm)=>{"use strict";var Ik=dm();pm.exports=Ik});var hm=g(()=>{"use strict"});var ol=g((jC,fm)=>{"use strict";var Ns=ke(),Ek=Qi(),wk=Hi(),On=function(s){return Ek.slice(0,s.length)===s};fm.exports=function(){return On("Bun/")?"BUN":On("Cloudflare-Workers")?"CLOUDFLARE":On("Deno/")?"DENO":On("Node.js/")?"NODE":Ns.Bun&&typeof Bun.version=="string"?"BUN":Ns.Deno&&typeof Deno.version=="object"?"DENO":wk(Ns.process)==="process"?"NODE":Ns.window&&Ns.document?"BROWSER":"REST"}()});var Nn=g((HC,mm)=>{"use strict";var xk=ol();mm.exports=xk==="NODE"});var gm=g((zC,bm)=>{"use strict";var kk=Gi();bm.exports=function(s,e,t){return kk.f(s,e,t)}});var ym=g((WC,vm)=>{"use strict";var Pk=ri(),Ak=gm(),Rk=ze(),$k=St(),Sm=Rk("species");vm.exports=function(s){var e=Pk(s);$k&&e&&!e[Sm]&&Ak(e,Sm,{configurable:!0,get:function(){return this}})}});var Im=g((QC,Tm)=>{"use strict";var Mk=Is(),Lk=TypeError;Tm.exports=function(s,e){if(Mk(e,s))return s;throw new Lk("Incorrect invocation")}});var ll=g((GC,Em)=>{"use strict";var Dk=Oe(),Bk=Pe(),ul=xs(),Ck=Dk(Function.toString);Bk(ul.inspectSource)||(ul.inspectSource=function(s){return Ck(s)});Em.exports=ul.inspectSource});var dl=g((YC,Am)=>{"use strict";var Vk=Oe(),_k=_e(),wm=Pe(),Ok=Cs(),Nk=ri(),Fk=ll(),xm=function(){},km=Nk("Reflect","construct"),cl=/^\s*(?:class|function)\b/,Uk=Vk(cl.exec),qk=!cl.test(xm),Fs=function(e){if(!wm(e))return!1;try{return km(xm,[],e),!0}catch{return!1}},Pm=function(e){if(!wm(e))return!1;switch(Ok(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return qk||!!Uk(cl,Fk(e))}catch{return!0}};Pm.sham=!0;Am.exports=!km||_k(function(){var s;return Fs(Fs.call)||!Fs(Object)||!Fs(function(){s=!0})||s})?Pm:Fs});var $m=g((KC,Rm)=>{"use strict";var jk=dl(),Hk=Es(),zk=TypeError;Rm.exports=function(s){if(jk(s))return s;throw new zk(Hk(s)+" is not a constructor")}});var pl=g((XC,Lm)=>{"use strict";var Mm=Yt(),Wk=$m(),Qk=Ts(),Gk=ze(),Yk=Gk("species");Lm.exports=function(s,e){var t=Mm(s).constructor,i;return t===void 0||Qk(i=Mm(t)[Yk])?e:Wk(i)}});var Bm=g((JC,Dm)=>{"use strict";var Kk=Oe();Dm.exports=Kk([].slice)});var Vm=g((ZC,Cm)=>{"use strict";var Xk=TypeError;Cm.exports=function(s,e){if(s<e)throw new Xk("Not enough arguments");return s}});var hl=g((eV,_m)=>{"use strict";var Jk=Qi();_m.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Jk)});var Il=g((tV,Wm)=>{"use strict";var yt=ke(),Zk=eu(),eP=xr(),Om=Pe(),tP=Nt(),zm=_e(),Nm=Wu(),iP=Bm(),Fm=cn(),rP=Vm(),sP=hl(),aP=Nn(),vl=yt.setImmediate,yl=yt.clearImmediate,nP=yt.process,fl=yt.Dispatch,oP=yt.Function,Um=yt.MessageChannel,uP=yt.String,ml=0,Us={},qm="onreadystatechange",qs,Zi,bl,gl;zm(function(){qs=yt.location});var Tl=function(s){if(tP(Us,s)){var e=Us[s];delete Us[s],e()}},Sl=function(s){return function(){Tl(s)}},jm=function(s){Tl(s.data)},Hm=function(s){yt.postMessage(uP(s),qs.protocol+"//"+qs.host)};(!vl||!yl)&&(vl=function(e){rP(arguments.length,1);var t=Om(e)?e:oP(e),i=iP(arguments,1);return Us[++ml]=function(){Zk(t,void 0,i)},Zi(ml),ml},yl=function(e){delete Us[e]},aP?Zi=function(s){nP.nextTick(Sl(s))}:fl&&fl.now?Zi=function(s){fl.now(Sl(s))}:Um&&!sP?(bl=new Um,gl=bl.port2,bl.port1.onmessage=jm,Zi=eP(gl.postMessage,gl)):yt.addEventListener&&Om(yt.postMessage)&&!yt.importScripts&&qs&&qs.protocol!=="file:"&&!zm(Hm)?(Zi=Hm,yt.addEventListener("message",jm,!1)):qm in Fm("script")?Zi=function(s){Nm.appendChild(Fm("script"))[qm]=function(){Nm.removeChild(this),Tl(s)}}:Zi=function(s){setTimeout(Sl(s),0)});Wm.exports={set:vl,clear:yl}});var Ym=g((iV,Gm)=>{"use strict";var Qm=ke(),lP=St(),cP=Object.getOwnPropertyDescriptor;Gm.exports=function(s){if(!lP)return Qm[s];var e=cP(Qm,s);return e&&e.value}});var El=g((rV,Xm)=>{"use strict";var Km=function(){this.head=null,this.tail=null};Km.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};Xm.exports=Km});var Zm=g((sV,Jm)=>{"use strict";var dP=Qi();Jm.exports=/ipad|iphone|ipod/i.test(dP)&&typeof Pebble<"u"});var tb=g((aV,eb)=>{"use strict";var pP=Qi();eb.exports=/web0s(?!.*chrome)/i.test(pP)});var ub=g((nV,ob)=>{"use strict";var Dr=ke(),hP=Ym(),ib=xr(),wl=Il().set,fP=El(),mP=hl(),bP=Zm(),gP=tb(),xl=Nn(),rb=Dr.MutationObserver||Dr.WebKitMutationObserver,sb=Dr.document,ab=Dr.process,Fn=Dr.Promise,Al=hP("queueMicrotask"),Lr,kl,Pl,Un,nb;Al||(js=new fP,Hs=function(){var s,e;for(xl&&(s=ab.domain)&&s.exit();e=js.get();)try{e()}catch(t){throw js.head&&Lr(),t}s&&s.enter()},!mP&&!xl&&!gP&&rb&&sb?(kl=!0,Pl=sb.createTextNode(""),new rb(Hs).observe(Pl,{characterData:!0}),Lr=function(){Pl.data=kl=!kl}):!bP&&Fn&&Fn.resolve?(Un=Fn.resolve(void 0),Un.constructor=Fn,nb=ib(Un.then,Un),Lr=function(){nb(Hs)}):xl?Lr=function(){ab.nextTick(Hs)}:(wl=ib(wl,Dr),Lr=function(){wl(Hs)}),Al=function(s){js.head||Lr(),js.add(s)});var js,Hs;ob.exports=Al});var cb=g((oV,lb)=>{"use strict";lb.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch{}}});var qn=g((uV,db)=>{"use strict";db.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var er=g((lV,pb)=>{"use strict";var SP=ke();pb.exports=SP.Promise});var Br=g((cV,bb)=>{"use strict";var vP=ke(),zs=er(),yP=Pe(),TP=Iu(),IP=ll(),EP=ze(),hb=ol(),wP=Ot(),Rl=lu(),fb=zs&&zs.prototype,xP=EP("species"),$l=!1,mb=yP(vP.PromiseRejectionEvent),kP=TP("Promise",function(){var s=IP(zs),e=s!==String(zs);if(!e&&Rl===66||wP&&!(fb.catch&&fb.finally))return!0;if(!Rl||Rl<51||!/native code/.test(s)){var t=new zs(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[xP]=i,$l=t.then(function(){})instanceof i,!$l)return!0}return!e&&(hb==="BROWSER"||hb==="DENO")&&!mb});bb.exports={CONSTRUCTOR:kP,REJECTION_EVENT:mb,SUBCLASSING:$l}});var Cr=g((dV,Sb)=>{"use strict";var gb=Gt(),PP=TypeError,AP=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new PP("Bad Promise constructor");e=i,t=r}),this.resolve=gb(e),this.reject=gb(t)};Sb.exports.f=function(s){return new AP(s)}});var Ob=g(()=>{"use strict";var RP=Re(),$P=Ot(),Wn=Nn(),Pi=ke(),MP=Wi(),Nr=vt(),vb=Mr(),yb=tl(),LP=Vs(),DP=ym(),BP=Gt(),zn=Pe(),CP=ut(),VP=Im(),_P=pl(),xb=Il().set,Cl=ub(),OP=cb(),NP=qn(),FP=El(),kb=qu(),Qn=er(),Vl=Br(),Pb=Cr(),Gn="Promise",Ab=Vl.CONSTRUCTOR,UP=Vl.REJECTION_EVENT,qP=Vl.SUBCLASSING,Ml=kb.getterFor(Gn),jP=kb.set,Vr=Qn&&Qn.prototype,tr=Qn,jn=Vr,Rb=Pi.TypeError,Ll=Pi.document,_l=Pi.process,Dl=Pb.f,HP=Dl,zP=!!(Ll&&Ll.createEvent&&Pi.dispatchEvent),$b="unhandledrejection",WP="rejectionhandled",Tb=0,Mb=1,QP=2,Ol=1,Lb=2,Hn,Ib,Db,Eb,Bb=function(s){var e;return CP(s)&&zn(e=s.then)?e:!1},Cb=function(s,e){var t=e.value,i=e.state===Mb,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,p;try{r?(i||(e.rejection===Lb&&YP(e),e.rejection=Ol),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),p=!0)),u===s.promise?n(new Rb("Promise-chain cycle")):(l=Bb(u))?Nr(l,u,a,n):a(u)):n(t)}catch(c){o&&!p&&o.exit(),n(c)}},Vb=function(s,e){s.notified||(s.notified=!0,Cl(function(){for(var t=s.reactions,i;i=t.get();)Cb(i,s);s.notified=!1,e&&!s.rejection&&GP(s)}))},_b=function(s,e,t){var i,r;zP?(i=Ll.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Pi.dispatchEvent(i)):i={promise:e,reason:t},!UP&&(r=Pi["on"+s])?r(i):s===$b&&OP("Unhandled promise rejection",t)},GP=function(s){Nr(xb,Pi,function(){var e=s.facade,t=s.value,i=wb(s),r;if(i&&(r=NP(function(){Wn?_l.emit("unhandledRejection",t,e):_b($b,e,t)}),s.rejection=Wn||wb(s)?Lb:Ol,r.error))throw r.value})},wb=function(s){return s.rejection!==Ol&&!s.parent},YP=function(s){Nr(xb,Pi,function(){var e=s.facade;Wn?_l.emit("rejectionHandled",e):_b(WP,e,s.value)})},_r=function(s,e,t){return function(i){s(e,i,t)}},Or=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=QP,Vb(s,!0))},Bl=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new Rb("Promise can't be resolved itself");var i=Bb(e);i?Cl(function(){var r={done:!1};try{Nr(i,e,_r(Bl,r,s),_r(Or,r,s))}catch(a){Or(r,a,s)}}):(s.value=e,s.state=Mb,Vb(s,!1))}catch(r){Or({done:!1},r,s)}}};if(Ab&&(tr=function(e){VP(this,jn),BP(e),Nr(Hn,this);var t=Ml(this);try{e(_r(Bl,t),_r(Or,t))}catch(i){Or(t,i)}},jn=tr.prototype,Hn=function(e){jP(this,{type:Gn,done:!1,notified:!1,parent:!1,reactions:new FP,rejection:!1,state:Tb,value:null})},Hn.prototype=vb(jn,"then",function(e,t){var i=Ml(this),r=Dl(_P(this,tr));return i.parent=!0,r.ok=zn(e)?e:!0,r.fail=zn(t)&&t,r.domain=Wn?_l.domain:void 0,i.state===Tb?i.reactions.add(r):Cl(function(){Cb(r,i)}),r.promise}),Ib=function(){var s=new Hn,e=Ml(s);this.promise=s,this.resolve=_r(Bl,e),this.reject=_r(Or,e)},Pb.f=Dl=function(s){return s===tr||s===Db?new Ib(s):HP(s)},!$P&&zn(Qn)&&Vr!==Object.prototype)){Eb=Vr.then,qP||vb(Vr,"then",function(e,t){var i=this;return new tr(function(r,a){Nr(Eb,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Vr.constructor}catch{}yb&&yb(Vr,jn)}RP({global:!0,constructor:!0,wrap:!0,forced:Ab},{Promise:tr});Db=MP.Promise;LP(tr,Gn,!1,!0);DP(Gn)});var jb=g((fV,qb)=>{"use strict";var KP=ze(),Fb=KP("iterator"),Ub=!1;try{Nb=0,Nl={next:function(){return{done:!!Nb++}},return:function(){Ub=!0}},Nl[Fb]=function(){return this},Array.from(Nl,function(){throw 2})}catch{}var Nb,Nl;qb.exports=function(s,e){try{if(!e&&!Ub)return!1}catch{return!1}var t=!1;try{var i={};i[Fb]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch{}return t}});var Fl=g((mV,Hb)=>{"use strict";var XP=er(),JP=jb(),ZP=Br().CONSTRUCTOR;Hb.exports=ZP||!JP(function(s){XP.all(s).then(void 0,function(){})})});var zb=g(()=>{"use strict";var eA=Re(),tA=vt(),iA=Gt(),rA=Cr(),sA=qn(),aA=Vn(),nA=Fl();eA({target:"Promise",stat:!0,forced:nA},{all:function(e){var t=this,i=rA.f(t),r=i.resolve,a=i.reject,n=sA(function(){var o=iA(t.resolve),u=[],l=0,p=1;aA(e,function(c){var d=l++,h=!1;p++,tA(o,t,c).then(function(m){h||(h=!0,u[d]=m,--p||r(u))},a)}),--p||r(u)});return n.error&&a(n.value),i.promise}})});var Qb=g(()=>{"use strict";var oA=Re(),uA=Ot(),lA=Br().CONSTRUCTOR,ql=er(),cA=ri(),dA=Pe(),pA=Mr(),Wb=ql&&ql.prototype;oA({target:"Promise",proto:!0,forced:lA,real:!0},{catch:function(s){return this.then(void 0,s)}});!uA&&dA(ql)&&(Ul=cA("Promise").prototype.catch,Wb.catch!==Ul&&pA(Wb,"catch",Ul,{unsafe:!0}));var Ul});var Gb=g(()=>{"use strict";var hA=Re(),fA=vt(),mA=Gt(),bA=Cr(),gA=qn(),SA=Vn(),vA=Fl();hA({target:"Promise",stat:!0,forced:vA},{race:function(e){var t=this,i=bA.f(t),r=i.reject,a=gA(function(){var n=mA(t.resolve);SA(e,function(o){fA(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Yb=g(()=>{"use strict";var yA=Re(),TA=Cr(),IA=Br().CONSTRUCTOR;yA({target:"Promise",stat:!0,forced:IA},{reject:function(e){var t=TA.f(this),i=t.reject;return i(e),t.promise}})});var jl=g((wV,Kb)=>{"use strict";var EA=Yt(),wA=ut(),xA=Cr();Kb.exports=function(s,e){if(EA(s),wA(e)&&e.constructor===s)return e;var t=xA.f(s),i=t.resolve;return i(e),t.promise}});var Zb=g(()=>{"use strict";var kA=Re(),PA=ri(),Xb=Ot(),AA=er(),Jb=Br().CONSTRUCTOR,RA=jl(),$A=PA("Promise"),MA=Xb&&!Jb;kA({target:"Promise",stat:!0,forced:Xb||Jb},{resolve:function(e){return RA(MA&&this===$A?AA:this,e)}})});var eg=g(()=>{"use strict";Ob();zb();Qb();Gb();Yb();Zb()});var sg=g(()=>{"use strict";var LA=Re(),DA=Ot(),Yn=er(),BA=_e(),ig=ri(),rg=Pe(),CA=pl(),tg=jl(),VA=Mr(),zl=Yn&&Yn.prototype,_A=!!Yn&&BA(function(){zl.finally.call({then:function(){}},function(){})});LA({target:"Promise",proto:!0,real:!0,forced:_A},{finally:function(s){var e=CA(this,ig("Promise")),t=rg(s);return this.then(t?function(i){return tg(e,s()).then(function(){return i})}:s,t?function(i){return tg(e,s()).then(function(){throw i})}:s)}});!DA&&rg(Yn)&&(Hl=ig("Promise").prototype.finally,zl.finally!==Hl&&VA(zl,"finally",Hl,{unsafe:!0}));var Hl});var ng=g((MV,ag)=>{"use strict";hm();eg();sg();var OA=Ti();ag.exports=OA("Promise","finally")});var ug=g((LV,og)=>{"use strict";var NA=ng();og.exports=NA});var Kn=g((DV,lg)=>{"use strict";var FA=ug();lg.exports=FA});var gg=g(()=>{"use strict";var GA=Re(),YA=Er(),KA=Rr(),XA=As(),JA=Rs();GA({target:"Array",proto:!0},{at:function(e){var t=YA(this),i=KA(t),r=XA(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});JA("at")});var vg=g((x0,Sg)=>{"use strict";gg();var ZA=Ti();Sg.exports=ZA("Array","at")});var Tg=g((k0,yg)=>{"use strict";var eR=vg();yg.exports=eR});var dt=g((P0,Ig)=>{"use strict";var tR=Tg();Ig.exports=tR});var pc=g((wN,eS)=>{"use strict";var bR=Hi();eS.exports=Array.isArray||function(e){return bR(e)==="Array"}});var iS=g((xN,tS)=>{"use strict";var gR=TypeError,SR=9007199254740991;tS.exports=function(s){if(s>SR)throw gR("Maximum allowed index exceeded");return s}});var aS=g((kN,sS)=>{"use strict";var vR=pc(),yR=Rr(),TR=iS(),IR=xr(),rS=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,p=n?IR(n,o):!1,c,d;l<i;)l in t&&(c=p?p(t[l],l,e):t[l],a>0&&vR(c)?(d=yR(c),u=rS(s,e,c,d,u,a-1)-1):(TR(u+1),s[u]=c),u++),l++;return u};sS.exports=rS});var lS=g((PN,uS)=>{"use strict";var nS=pc(),ER=dl(),wR=ut(),xR=ze(),kR=xR("species"),oS=Array;uS.exports=function(s){var e;return nS(s)&&(e=s.constructor,ER(e)&&(e===oS||nS(e.prototype))?e=void 0:wR(e)&&(e=e[kR],e===null&&(e=void 0))),e===void 0?oS:e}});var dS=g((AN,cS)=>{"use strict";var PR=lS();cS.exports=function(s,e){return new(PR(s))(e===0?0:e)}});var pS=g(()=>{"use strict";var AR=Re(),RR=aS(),$R=Gt(),MR=Er(),LR=Rr(),DR=dS();AR({target:"Array",proto:!0},{flatMap:function(e){var t=MR(this),i=LR(t),r;return $R(e),r=DR(t,0),r.length=RR(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var hS=g(()=>{"use strict";var BR=Rs();BR("flatMap")});var mS=g((DN,fS)=>{"use strict";pS();hS();var CR=Ti();fS.exports=CR("Array","flatMap")});var gS=g((BN,bS)=>{"use strict";var VR=mS();bS.exports=VR});var nr=g((CN,SS)=>{"use strict";var _R=gS();SS.exports=_R});var ra=g((JN,IS)=>{"use strict";var NR=Cs(),FR=String;IS.exports=function(s){if(NR(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return FR(s)}});var fc=g((ZN,ES)=>{"use strict";ES.exports=`
7
- \v\f\r                 \u2028\u2029\uFEFF`});var kS=g((eF,xS)=>{"use strict";var UR=Oe(),qR=yi(),jR=ra(),bc=fc(),wS=UR("".replace),HR=RegExp("^["+bc+"]+"),zR=RegExp("(^|[^"+bc+"])["+bc+"]+$"),mc=function(s){return function(e){var t=jR(qR(e));return s&1&&(t=wS(t,HR,"")),s&2&&(t=wS(t,zR,"$1")),t}};xS.exports={start:mc(1),end:mc(2),trim:mc(3)}});var $S=g((tF,RS)=>{"use strict";var WR=zu().PROPER,QR=_e(),PS=fc(),AS="​…᠎";RS.exports=function(s){return QR(function(){return!!PS[s]()||AS[s]()!==AS||WR&&PS[s].name!==s})}});var gc=g((iF,MS)=>{"use strict";var GR=kS().start,YR=$S();MS.exports=YR("trimStart")?function(){return GR(this)}:"".trimStart});var DS=g(()=>{"use strict";var KR=Re(),LS=gc();KR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==LS},{trimLeft:LS})});var CS=g(()=>{"use strict";DS();var XR=Re(),BS=gc();XR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==BS},{trimStart:BS})});var _S=g((oF,VS)=>{"use strict";CS();var JR=Ti();VS.exports=JR("String","trimLeft")});var NS=g((uF,OS)=>{"use strict";var ZR=_S();OS.exports=ZR});var US=g((lF,FS)=>{"use strict";var e$=NS();FS.exports=e$});var jS=g(()=>{"use strict"});var HS=g(()=>{"use strict"});var WS=g((HF,zS)=>{"use strict";var t$=ut(),i$=Hi(),r$=ze(),s$=r$("match");zS.exports=function(s){var e;return t$(s)&&((e=s[s$])!==void 0?!!e:i$(s)==="RegExp")}});var YS=g((zF,GS)=>{"use strict";var a$=ke(),n$=_e(),QS=a$.RegExp,o$=!n$(function(){var s=!0;try{QS(".","d")}catch{s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor(QS.prototype,"flags").get.call(e);return o!==i||t!==i});GS.exports={correct:o$}});var XS=g((WF,KS)=>{"use strict";var u$=Yt();KS.exports=function(){var s=u$(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 ev=g((QF,ZS)=>{"use strict";var l$=vt(),c$=Nt(),d$=Is(),JS=YS(),p$=XS(),h$=RegExp.prototype;ZS.exports=JS.correct?function(s){return s.flags}:function(s){return!JS.correct&&d$(h$,s)&&!c$(s,"flags")?l$(p$,s):s.flags}});var iv=g((GF,tv)=>{"use strict";var Tc=Oe(),f$=Er(),m$=Math.floor,vc=Tc("".charAt),b$=Tc("".replace),yc=Tc("".slice),g$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,S$=/\$([$&'`]|\d{1,2})/g;tv.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=S$;return r!==void 0&&(r=f$(r),u=g$),b$(a,u,function(l,p){var c;switch(vc(p,0)){case"$":return"$";case"&":return s;case"`":return yc(e,0,t);case"'":return yc(e,n);case"<":c=r[yc(p,1,-1)];break;default:var d=+p;if(d===0)return l;if(d>o){var h=m$(d/10);return h===0?l:h<=o?i[h-1]===void 0?vc(p,1):i[h-1]+vc(p,1):l}c=i[d-1]}return c===void 0?"":c})}});var av=g(()=>{"use strict";var v$=Re(),y$=vt(),Ec=Oe(),rv=yi(),T$=Pe(),I$=ut(),E$=WS(),Zr=ra(),w$=ws(),x$=ev(),k$=iv(),P$=ze(),A$=Ot(),R$=P$("replace"),$$=TypeError,Ic=Ec("".indexOf),M$=Ec("".replace),sv=Ec("".slice),L$=Math.max;v$({target:"String",proto:!0},{replaceAll:function(e,t){var i=rv(this),r,a,n,o,u,l,p,c,d,h,m=0,b="";if(I$(e)){if(r=E$(e),r&&(a=Zr(rv(x$(e))),!~Ic(a,"g")))throw new $$("`.replaceAll` does not allow non-global regexes");if(n=w$(e,R$),n)return y$(n,e,i,t);if(A$&&r)return M$(Zr(i),e,t)}for(o=Zr(i),u=Zr(e),l=T$(t),l||(t=Zr(t)),p=u.length,c=L$(1,p),d=Ic(o,u);d!==-1;)h=l?Zr(t(u,d,o)):k$(u,o,d,[],void 0,t),b+=sv(o,m,d)+h,m=d+p,d=d+c>o.length?-1:Ic(o,u,d+c);return m<o.length&&(b+=sv(o,m)),b}})});var ov=g((XF,nv)=>{"use strict";jS();HS();av();var D$=Ti();nv.exports=D$("String","replaceAll")});var lv=g((JF,uv)=>{"use strict";var B$=ov();uv.exports=B$});var dv=g((ZF,cv)=>{"use strict";var C$=lv();cv.exports=C$});var hv=g((eU,pv)=>{"use strict";var V$=As(),_$=ra(),O$=yi(),N$=RangeError;pv.exports=function(e){var t=_$(O$(this)),i="",r=V$(e);if(r<0||r===1/0)throw new N$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var Sv=g((tU,gv)=>{"use strict";var bv=Oe(),F$=Ru(),fv=ra(),U$=hv(),q$=yi(),j$=bv(U$),H$=bv("".slice),z$=Math.ceil,mv=function(s){return function(e,t,i){var r=fv(q$(e)),a=F$(t),n=r.length,o=i===void 0?" ":fv(i),u,l;return a<=n||o===""?r:(u=a-n,l=j$(o,z$(u/o.length)),l.length>u&&(l=H$(l,0,u)),s?r+l:l+r)}};gv.exports={start:mv(!1),end:mv(!0)}});var yv=g((iU,vv)=>{"use strict";var W$=Qi();vv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(W$)});var Tv=g(()=>{"use strict";var Q$=Re(),G$=Sv().start,Y$=yv();Q$({target:"String",proto:!0,forced:Y$},{padStart:function(e){return G$(this,e,arguments.length>1?arguments[1]:void 0)}})});var Ev=g((aU,Iv)=>{"use strict";Tv();var K$=Ti();Iv.exports=K$("String","padStart")});var xv=g((nU,wv)=>{"use strict";var X$=Ev();wv.exports=X$});var Pv=g((oU,kv)=>{"use strict";var J$=xv();kv.exports=J$});var QM={};Xy(QM,{ChromecastState:()=>Ir,HttpConnectionType:()=>nn,Observable:()=>ti.Observable,PlaybackState:()=>Ve,Player:()=>Ya,PredefinedQualityLimits:()=>gs,SDK_VERSION:()=>WM,Subject:()=>ti.Subject,Subscription:()=>ti.Subscription,Surface:()=>on,VERSION:()=>Jo,ValueSubject:()=>ti.ValueSubject,VideoFormat:()=>Qt,VideoQuality:()=>ti.VideoQuality,areValidLiveRecordSources:()=>Rh,clientChecker:()=>F,isMobile:()=>Ei});module.exports=Jy(QM);var Jo="2.0.150-dev.31e6196f.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ve||{}),Qt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_FMP4="HLS_FMP4",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(Qt||{});var Ir=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ir||{}),nn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(nn||{});var on=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(on||{}),gs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(gs||{});var td=q(Yi(),1),Uy=q(We(),1);var ae=require("@vkontakte/videoplayer-shared");var vh=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 mn=class{constructor(e){this.connection$=new ae.ValueSubject(void 0);this.castState$=new ae.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new ae.Subject;this.realCastState$=new ae.ValueSubject("NOT_AVAILABLE");this.subscription=new ae.Subscription;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,ae.isNonNullable)(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||vh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ae.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,ae.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,ae.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,ae.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,ae.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,ae.assertNever)(r.sessionState)}})).add((0,ae.merge)((0,ae.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,ae.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,ae.map)(r=>r.castState)),(0,ae.observableFrom)([i.getCastState()])).pipe((0,ae.filterChanged)(),(0,ae.map)(QE),(0,ae.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",n=(0,ae.isNonNullable)(this.connection$.getValue());if(a&&!n){let o=i.getCurrentSession();(0,ae.assertNonNullable)(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;((0,ae.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,ae.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:ae.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},QE=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,ae.assertNever)(s)}};var ne=require("@vkontakte/videoplayer-shared");var Ne=require("@vkontakte/videoplayer-shared");var Cu=require("@vkontakte/videoplayer-shared");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,Cu.assertNever)(t)}return s},Ii=(s,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(s);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(s);return Number(t.searchParams.get("offset_p")??0)}default:(0,Cu.assertNever)(e)}};var gn=s=>{let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let c=e[t];(0,Ne.assertNonNullable)(c);let d=(0,Ne.getHighestQuality)(Object.keys(c));(0,Ne.assertNonNullable)(d);let h=c[d];(0,Ne.assertNonNullable)(h),a=h,n="video/mp4",o=bn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=e[t];(0,Ne.assertNonNullable)(c),a=c.url,n="application/x-mpegurl",o=bn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=e[t];(0,Ne.assertNonNullable)(c),a=c.url,n="application/dash+xml",o=bn();break}case"DASH_LIVE_CMAF":{let c=e[t];(0,Ne.assertNonNullable)(c),a=c.url,n="application/dash+xml",o=yh();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=e[t];(0,Ne.assertNonNullable)(c),a=Ae(c.url),n="application/x-mpegurl",o=yh();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ne.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return(0,Ne.assertNever)(t)}let u=GE(i.videoId??a,n);u.contentUrl=a,u.streamType=o,u.metadata=YE();let{title:l,subtitle:p}=i;return(0,Ne.isNonNullable)(l)&&(u.metadata.title=l),(0,Ne.isNonNullable)(p)&&(u.metadata.subtitle=p),u};function bn(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function yh(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function GE(s,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:bn()}}function YE(){return chrome.cast?.media?.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 Sn=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 _u=require("@vkontakte/videoplayer-shared");var xn=require("@vkontakte/videoplayer-shared");var Th=q(We(),1),Ih=require("@vkontakte/videoplayer-shared");var vn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Th.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,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=(0,Ih.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 Eh=q(We(),1),wi=require("@vkontakte/videoplayer-shared");var Ei=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var yn=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,Eh.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,wi.getWindow)();if(!(0,wi.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=Ei()}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,wi.getWindow)();if(!(0,wi.isBrowserWindow)(e))return;let{userAgentData:t}=e.navigator;if(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",l="Unknown";if(n){let p=r[0];typeof p=="number"?p<a.length&&a[p]!==void 0&&(u=a[p]):u=p}if(o){let p=r[1];typeof p=="number"?p<a.length&&a[p]!==void 0&&(l=a[p]):p!==void 0&&(l=p)}else a[2]!==void 0?l=a[2]:a[1]!==void 0&&n&&typeof r[0]=="string"&&(l=a[1]);u=this.normalizeOSName(u),l=this.normalizeOSVersion(l,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:l||"Unknown",full:l&&l!=="Unknown"?`${u} ${l}`: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),l="Unknown";typeof o=="number"?l=a[o]!==void 0?a[o]:"Unknown":o!==void 0?l=o:a[1]!==void 0?l=a[1]:a[0]!==void 0&&(l=a[0]),l=this.normalizeModelName(l,u),this.details.vendor=u,this.details.model=l;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,wi.getWindow)();if(!(0,wi.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?.[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var $s=require("@vkontakte/videoplayer-shared"),Tn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,$s.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(){let e=(0,$s.getWindow)();if(!(0,$s.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=i.colorDepth}catch(a){console.error(a)}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(a){console.error(a)}}};var Ki=require("@vkontakte/videoplayer-shared");var rt=()=>window.ManagedMediaSource||window.MediaSource,xi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),wh=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),$r=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var KE=(0,Ki.getWindow)().document?.createElement("video"),XE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',JE='video/mp4; codecs="hev1.1.6.L93.B0"',xh='video/webm; codecs="vp09.00.10.08"',kh='video/webm; codecs="av01.0.00M.08"',ZE='audio/mp4; codecs="mp4a.40.2"',ew='audio/webm; codecs="opus"',Ph,tw=async()=>{let s=(0,Ki.getWindow)();if(!(0,Ki.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:kh}}),s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:xh}})]);Ph={DASH_WEBM_AV1:t,DASH_WEBM:i}};tw().catch(s=>{console.log(KE),console.error(s)});var In=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Ph}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=(0,Ki.getWindow)();if(!(0,Ki.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:xi(),mse:wh(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let i=!!rt()?.isTypeSupported?.(XE),r=!!rt()?.isTypeSupported?.(JE),a=!!rt()?.isTypeSupported?.(ZE);this._codecs={h264:i,h265:r,vp9:!!rt()?.isTypeSupported?.(xh),av1:!!rt()?.isTypeSupported?.(kh),aac:a,opus:!!rt()?.isTypeSupported?.(ew),mpeg:(i||r)&&a},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(i){console.error(i)}try{this.destroyVideoElement()}catch(i){console.error("Error destroying video element:",i)}}destroyVideoElement(){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);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var wn=require("@vkontakte/videoplayer-shared");var Ah="audio/mpeg",En=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=(0,wn.getWindow)();if(!(0,wn.isBrowserWindow)(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Ah)},this._codecs={mp3:!!rt()?.isTypeSupported?.(Ah)}}catch(i){console.error(i)}try{this.destroyAudioElement()}catch(i){console.error("Error destroying audio element:",i)}}destroyAudioElement(){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);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};var Vu=class{constructor(){this.isInited$=new xn.ValueSubject(!1);this._displayChecker=new Tn,this._deviceChecker=new yn(this._displayChecker),this._browserChecker=new vn,this._videoChecker=new In(this._deviceChecker,this._browserChecker),this._audioChecker=new En,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){(0,xn.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},F=new Vu;var Ou=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=F.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,_u.assertNever)(o)}})},Ms=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,_u.assertNever)(s)}},Rh=s=>{let t=Object.keys(s).filter(i=>!Ms(i));return Ou(t).length>0};var Ls=class{constructor(e){this.subscription=new ne.Subscription;this.sessionId$=new ne.ValueSubject(null);this.mediaSessionId$=new ne.ValueSubject(null);this.contentId$=new ne.ValueSubject(null);this.isMobile=Ei();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if((0,ne.isNullable)(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=e.media?.duration;(0,ne.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,ne.isNonNullable)(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let n=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!n?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new Sn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ms(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:ne.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,ne.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,ne.filter)(ne.isNonNullable),(0,ne.filterChanged)(),(0,ne.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,ne.filterChanged)(),(0,ne.map)(Boolean));this.subscription.add((0,ne.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,ne.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,ne.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,ne.filter)(({mediaLoaded:r})=>r),(0,ne.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,ne.filter)(({mediaLoaded:r,playbackState:{from:a,to:n}})=>!r&&a==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,ne.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,ne.debounce)(30)),mediaLoaded:t}).pipe((0,ne.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:n}=r.to;this.setVolume(n,a)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=gn(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=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,ne.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,ne.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,ne.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,ne.isNullable)(e))return;let{level:t,muted:i}=e,r={muted:i??!1,volume: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 me=require("@vkontakte/videoplayer-shared");var $h=s=>({castDevice:{friendlyName:s},remotePlayer:{},remotePlayerController:{},session:{}}),Mh=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Ds=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new me.ValueSubject(null);this.sessionId$=new me.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new me.Subscription;this.subscriptionEvents=new me.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new me.ValueSubject(!1);this.presentationConnection$=new me.ValueSubject(null);this.message$=new me.ValueSubject(null);this.friendlyName$=new me.ValueSubject(null);this.errorEvent$=new me.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,me.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(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();(0,me.assertNonNullable)(e,"connect with null presentationRequest");let t=await e.start();this.handleConnection(t)}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:me.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add((0,me.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,me.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,me.filter)(e=>!!e)).subscribe(e=>{let t=(0,me.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,me.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,me.fromEvent)(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:me.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?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:me.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){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":e.message?.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]||Mh()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new me.Subscription}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};var Qe=require("@vkontakte/videoplayer-shared");var si=class s{constructor(e){this.subscription=new Qe.Subscription;this.connection$=new Qe.ValueSubject(void 0);this.castState$=new Qe.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new Qe.Subject;let t=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 Ds({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,Qe.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,Qe.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,Qe.filterChanged)())});this.subscription.add(e.pipe((0,Qe.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,Qe.filterChanged)()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?$h(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(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};var Kc=q(We(),1),Xc=q(ki(),1),Py=q(nl(),1);var dg=q(Kn(),1);var Kt=require("@vkontakte/videoplayer-shared"),te=class{constructor(e){this.transitionStarted$=new Kt.Subject;this.transitionEnded$=new Kt.Subject;this.transitionUpdated$=new Kt.Subject;this.forceChanged$=new Kt.Subject;this.stateChangeStarted$=(0,Kt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Kt.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,Kt.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 de=require("@vkontakte/videoplayer-shared");var UA=5,qA=5,jA=500,cg=7e3,Ws=class{constructor(e){this.subscription=new de.Subscription;this.loadMediaTimeoutSubscription=new de.Subscription;this.videoState=new te("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?.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,de.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,de.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,de.assertNever)(e)}break}default:(0,de.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(Ms(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 de.Subscription;this.subscription.add(e),this.subscription.add((0,de.merge)(this.videoState.stateChangeStarted$.pipe((0,de.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,de.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 de.Subject;e.add(r.pipe((0,de.debounce)(jA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,de.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)>UA)&&r.next(o),a=o})),e.add((0,de.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,de.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,de.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,de.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<qA&&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,de.assertNever)(n)}}),t((0,de.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,de.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,de.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,de.observableFrom)(["init"])).pipe((0,de.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=gn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??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,de.timeout)(cg).subscribe(()=>a(`timeout(${cg})`)))});(0,dg.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:de.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var nc=q(We(),1);var Qs=require("@vkontakte/videoplayer-shared");var pg=require("@vkontakte/videoplayer-shared"),hg=s=>{try{s.pause(),s.playbackRate=0,(0,pg.clearVideoElement)(s),s.remove()}catch(e){console.error(e)}};var Jn=require("@vkontakte/videoplayer-shared"),Wl=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Xn=(0,Qs.getWindow)(),Ql=Xn.WeakMap?new Xn.WeakMap:new Wl,Gl=Xn.WeakMap?new Xn.WeakMap:new Map,HA=(s,e=20)=>{let t=0;return(0,Jn.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Ge=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?(0,Qs.clearVideoElement)(i):(i=document.createElement("video"),s.appendChild(i)),Ql.set(i,r);let a=new Jn.Subscription;return a.add(HA(i,e)),Gl.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ye=s=>{Gl.get(s)?.unsubscribe(),Gl.delete(s);let t=Ql.get(s);Ql.delete(s),t?(0,Qs.clearVideoElement)(s):hg(s)};var Yl=q(Yi(),1),W=require("@vkontakte/videoplayer-shared");var Ai=require("@vkontakte/videoplayer-shared"),Zn=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,Ai.isNullable)(r),l=new Ai.Subscription;return r&&l.add(r.subscribe(p=>{let c=s.getState();i(p,c)&&s.setState(p)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(p=>{t(p.to),u&&s.setState(p.to)},a)),l},At=(s,e,t)=>Zn(e,()=>s.loop,i=>{(0,Ai.isNonNullable)(i)&&(s.loop=i)},{onError:t}),Ke=(s,e,t,i)=>Zn(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,Ai.isNonNullable)(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),lt=(s,e,t,i)=>Zn(e,()=>s.playbackRate,r=>{(0,Ai.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Gs=Zn;var zA=s=>["__",s.language,s.label].join("|"),WA=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Kl=class s{constructor(e){this.available$=new W.Subject;this.current$=new W.ValueSubject(void 0);this.error$=new W.Subject;this.subscription=new W.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:W.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(Gs(t.internalTextTracks,()=>(0,Yl.default)(this.internalTracks),a=>{(0,W.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,n)=>(0,W.isNonNullable)(a)&&(0,W.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,W.map)(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Gs(t.externalTextTracks,()=>(0,Yl.default)(this.externalTracks),a=>{(0,W.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,n)=>(0,W.isNonNullable)(a)&&(0,W.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,W.map)(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Gs(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(Gs(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,W.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,W.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,W.merge)((0,W.fromEvent)(e,"addtrack"),(0,W.fromEvent)(e,"removetrack"),(0,W.observableFrom)(["init"])).pipe((0,W.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,W.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add((0,W.merge)((0,W.fromEvent)(e,"change"),(0,W.observableFrom)(["init"])).pipe((0,W.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,W.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,W.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,W.fromEvent)(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add((0,W.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.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,W.isNonNullable)(t.align)&&(r.align=t.align),(0,W.isNonNullable)(t.position)&&(r.position=t.position),(0,W.isNonNullable)(t.size)&&(r.size=t.size),(0,W.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,W.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:zA(e),a=this.externalTracks.has(r),n=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.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,W.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,W.isNullable)(e)||!WA(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,W.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,W.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)}},ct=Kl;var ir=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 fg=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Xl=s=>{let e=fg(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},mg=s=>{let e=fg(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var C=require("@vkontakte/videoplayer-shared");var QA=3,bg=(s,e,t=QA)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var Xe=s=>{let e=D=>(0,C.fromEvent)(s,D).pipe((0,C.mapTo)(void 0),(0,C.shareReplay)(1)),t=new C.Subscription,i=()=>t.unsubscribe(),r=(0,C.merge)((0,C.fromEvent)(s,"progress"),(0,C.fromEvent)(s,"timeupdate")).pipe((0,C.map)(()=>bg(s.buffered,s.currentTime)),(0,C.shareReplay)(1)),a=F.browser.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0),(0,C.shareReplay)(1)):e("playing"),n=(0,C.fromEvent)(s,"volumechange").pipe((0,C.map)(()=>({muted:s.muted,volume:s.volume})),(0,C.shareReplay)(1)),o=(0,C.fromEvent)(s,"ratechange").pipe((0,C.map)(()=>s.playbackRate),(0,C.shareReplay)(1)),u=(0,C.fromEvent)(s,"error").pipe((0,C.filter)(()=>!!(s.error||s.played.length)),(0,C.map)(()=>{let D=s.error;return{id:D?`MediaError#${D.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:D?D.message:"Error event from HTML video element",thrown:s.error??void 0}}),(0,C.shareReplay)(1)),l=(0,C.fromEvent)(s,"timeupdate").pipe((0,C.map)(()=>s.currentTime),(0,C.shareReplay)(1)),p=["waiting","seeking","seeked","timeupdate"],c=new C.Subject,d=.3,h;t.add((0,C.merge)(...p.map(D=>(0,C.fromEvent)(s,D))).subscribe(D=>{let se=s.currentTime;s.loop&&(0,C.isNonNullable)(h)&&(0,C.isNonNullable)(se)&&h>=s.duration-d&&se<=d&&c.next(h),h=se}));let m=e("pause").pipe((0,C.filter)(()=>!s.error&&h!==s.duration),(0,C.shareReplay)(1)),b=(0,C.fromEvent)(s,"enterpictureinpicture").pipe((0,C.shareReplay)(1)),v=(0,C.fromEvent)(s,"leavepictureinpicture").pipe((0,C.shareReplay)(1)),S=new C.ValueSubject(mg(s));t.add(b.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let y=new C.ValueSubject(Xl(s)),k=(0,C.fromEvent)(s,"fullscreenchange").pipe((0,C.shareReplay)(1));t.add(k.pipe((0,C.map)(()=>Xl(s))).subscribe(y));let x=.1,L=1e3,O=(0,C.fromEvent)(s,"timeupdate").pipe((0,C.map)(D=>s.duration-s.currentTime<x),(0,C.filterChanged)(),(0,C.shareReplay)(1)),N=(0,C.merge)(O.pipe((0,C.filter)(D=>!s.loop&&D)),(0,C.fromEvent)(s,"ended")).pipe((0,C.throttle)(L),(0,C.mapTo)(void 0),(0,C.shareReplay)(1)),j=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(D=>(0,C.fromEvent)(s,D)),O.pipe((0,C.map)(D=>({type:D?"ended":"unknown"})))).pipe((0,C.map)(D=>F.browser.isFirefox&&D.type==="ended"?s.readyState<2:s.readyState<3),(0,C.filterChanged)(),(0,C.shareReplay)(1));return{playing$:a,pause$:m,canplay$:e("canplay"),ended$:N,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,C.fromEvent)(s,"durationchange").pipe((0,C.map)(()=>s.duration),(0,C.shareReplay)(1)),isBuffering$:j,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:y,enterPip$:b,leavePip$:v,destroy:i}};var ni=require("@vkontakte/videoplayer-shared"),Xt=s=>{switch(s){case"mobile":return ni.VideoQuality.Q_144P;case"lowest":return ni.VideoQuality.Q_240P;case"low":return ni.VideoQuality.Q_360P;case"sd":case"medium":return ni.VideoQuality.Q_480P;case"hd":case"high":return ni.VideoQuality.Q_720P;case"fullhd":case"full":return ni.VideoQuality.Q_1080P;case"quadhd":case"quad":return ni.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ni.VideoQuality.Q_2160P}};var at=q(dt(),1),Zl=q(We(),1),rr=q(ki(),1),_=require("@vkontakte/videoplayer-shared");var Jl=!1,oi={},Eg=s=>{Jl=s},wg=()=>{oi={}},xg=s=>{s(oi)},Ys=(s,e)=>{Jl&&(oi.meta=oi.meta??{},oi.meta[s]=e)},st=class{constructor(e){this.name=e}next(e){if(!Jl)return;oi.series=oi.series??{};let t=oi.series[this.name]??[];t.push([Date.now(),e]),oi.series[this.name]=t}};var $e=require("@vkontakte/videoplayer-shared");function kg(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Fr(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 Pg({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Fr({max:s?.max?(0,$e.videoHeightToQuality)(s.max):void 0,min:s?.min?(0,$e.videoHeightToQuality)(s.min):void 0},e?(0,$e.videoHeightToQuality)(e):void 0,t?(0,$e.videoHeightToQuality)(t):void 0)}var Lg=new st("best_bitrate"),to=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Ur=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),qt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,_.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},io='Assertion "ABR Tracks is empty array" failed',eo=new WeakMap,Ag=new WeakMap,Rg=new WeakMap,sr=(s,e,t,i)=>{let r=[...e].sort(Ur(1)),a=[...t].sort(Ur(1)),n=a.filter(u=>(0,_.isNonNullable)(u.bitrate)&&(0,_.isNonNullable)(s.bitrate)?s.bitrate/u.bitrate>i:!0),o=(0,at.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,at.default)(a,-1);return o&&(0,Zl.default)(n,o)?o:n.length?(0,at.default)(n,-1):(0,at.default)(a,0)},ar=(s,e,t,i)=>{let r=eo.get(e);r||(r=[...e].sort(Ur(1)),eo.set(e,r));let a=eo.get(t);a||(a=[...t].sort(Ur(1)),eo.set(t,a));let n=Rg.get(s);n||(n=a.filter(u=>(0,_.isNonNullable)(u.bitrate)&&(0,_.isNonNullable)(s.bitrate)?s.bitrate/u.bitrate>i:!0),Rg.set(s,n));let o=(0,at.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,at.default)(a,-1);return o&&(0,Zl.default)(n,o)?o:n.length?(0,at.default)(n,-1):(0,at.default)(a,0)},$g=s=>"quality"in s,ro=(s,e,t,i)=>{let r=(0,_.isNonNullable)(i?.last?.bitrate)&&(0,_.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,_.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let n=i.last;i?.recordSwitch(n);let o=$g(n)?"video":"audio",u=$g(n)?n.quality:n.bitrate;return e({message:`
7
+ \v\f\r                 \u2028\u2029\uFEFF`});var kS=g((eF,xS)=>{"use strict";var UR=Oe(),qR=yi(),jR=ra(),bc=fc(),wS=UR("".replace),HR=RegExp("^["+bc+"]+"),zR=RegExp("(^|[^"+bc+"])["+bc+"]+$"),mc=function(s){return function(e){var t=jR(qR(e));return s&1&&(t=wS(t,HR,"")),s&2&&(t=wS(t,zR,"$1")),t}};xS.exports={start:mc(1),end:mc(2),trim:mc(3)}});var $S=g((tF,RS)=>{"use strict";var WR=zu().PROPER,QR=_e(),PS=fc(),AS="​…᠎";RS.exports=function(s){return QR(function(){return!!PS[s]()||AS[s]()!==AS||WR&&PS[s].name!==s})}});var gc=g((iF,MS)=>{"use strict";var GR=kS().start,YR=$S();MS.exports=YR("trimStart")?function(){return GR(this)}:"".trimStart});var DS=g(()=>{"use strict";var KR=Re(),LS=gc();KR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==LS},{trimLeft:LS})});var CS=g(()=>{"use strict";DS();var XR=Re(),BS=gc();XR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==BS},{trimStart:BS})});var _S=g((oF,VS)=>{"use strict";CS();var JR=Ti();VS.exports=JR("String","trimLeft")});var NS=g((uF,OS)=>{"use strict";var ZR=_S();OS.exports=ZR});var US=g((lF,FS)=>{"use strict";var e$=NS();FS.exports=e$});var jS=g(()=>{"use strict"});var HS=g(()=>{"use strict"});var WS=g((HF,zS)=>{"use strict";var t$=ut(),i$=Hi(),r$=ze(),s$=r$("match");zS.exports=function(s){var e;return t$(s)&&((e=s[s$])!==void 0?!!e:i$(s)==="RegExp")}});var YS=g((zF,GS)=>{"use strict";var a$=ke(),n$=_e(),QS=a$.RegExp,o$=!n$(function(){var s=!0;try{QS(".","d")}catch{s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor(QS.prototype,"flags").get.call(e);return o!==i||t!==i});GS.exports={correct:o$}});var XS=g((WF,KS)=>{"use strict";var u$=Yt();KS.exports=function(){var s=u$(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 ev=g((QF,ZS)=>{"use strict";var l$=vt(),c$=Nt(),d$=Is(),JS=YS(),p$=XS(),h$=RegExp.prototype;ZS.exports=JS.correct?function(s){return s.flags}:function(s){return!JS.correct&&d$(h$,s)&&!c$(s,"flags")?l$(p$,s):s.flags}});var iv=g((GF,tv)=>{"use strict";var Tc=Oe(),f$=Er(),m$=Math.floor,vc=Tc("".charAt),b$=Tc("".replace),yc=Tc("".slice),g$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,S$=/\$([$&'`]|\d{1,2})/g;tv.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=S$;return r!==void 0&&(r=f$(r),u=g$),b$(a,u,function(l,p){var c;switch(vc(p,0)){case"$":return"$";case"&":return s;case"`":return yc(e,0,t);case"'":return yc(e,n);case"<":c=r[yc(p,1,-1)];break;default:var d=+p;if(d===0)return l;if(d>o){var h=m$(d/10);return h===0?l:h<=o?i[h-1]===void 0?vc(p,1):i[h-1]+vc(p,1):l}c=i[d-1]}return c===void 0?"":c})}});var av=g(()=>{"use strict";var v$=Re(),y$=vt(),Ec=Oe(),rv=yi(),T$=Pe(),I$=ut(),E$=WS(),Zr=ra(),w$=ws(),x$=ev(),k$=iv(),P$=ze(),A$=Ot(),R$=P$("replace"),$$=TypeError,Ic=Ec("".indexOf),M$=Ec("".replace),sv=Ec("".slice),L$=Math.max;v$({target:"String",proto:!0},{replaceAll:function(e,t){var i=rv(this),r,a,n,o,u,l,p,c,d,h,m=0,b="";if(I$(e)){if(r=E$(e),r&&(a=Zr(rv(x$(e))),!~Ic(a,"g")))throw new $$("`.replaceAll` does not allow non-global regexes");if(n=w$(e,R$),n)return y$(n,e,i,t);if(A$&&r)return M$(Zr(i),e,t)}for(o=Zr(i),u=Zr(e),l=T$(t),l||(t=Zr(t)),p=u.length,c=L$(1,p),d=Ic(o,u);d!==-1;)h=l?Zr(t(u,d,o)):k$(u,o,d,[],void 0,t),b+=sv(o,m,d)+h,m=d+p,d=d+c>o.length?-1:Ic(o,u,d+c);return m<o.length&&(b+=sv(o,m)),b}})});var ov=g((XF,nv)=>{"use strict";jS();HS();av();var D$=Ti();nv.exports=D$("String","replaceAll")});var lv=g((JF,uv)=>{"use strict";var B$=ov();uv.exports=B$});var dv=g((ZF,cv)=>{"use strict";var C$=lv();cv.exports=C$});var hv=g((eU,pv)=>{"use strict";var V$=As(),_$=ra(),O$=yi(),N$=RangeError;pv.exports=function(e){var t=_$(O$(this)),i="",r=V$(e);if(r<0||r===1/0)throw new N$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var Sv=g((tU,gv)=>{"use strict";var bv=Oe(),F$=Ru(),fv=ra(),U$=hv(),q$=yi(),j$=bv(U$),H$=bv("".slice),z$=Math.ceil,mv=function(s){return function(e,t,i){var r=fv(q$(e)),a=F$(t),n=r.length,o=i===void 0?" ":fv(i),u,l;return a<=n||o===""?r:(u=a-n,l=j$(o,z$(u/o.length)),l.length>u&&(l=H$(l,0,u)),s?r+l:l+r)}};gv.exports={start:mv(!1),end:mv(!0)}});var yv=g((iU,vv)=>{"use strict";var W$=Qi();vv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(W$)});var Tv=g(()=>{"use strict";var Q$=Re(),G$=Sv().start,Y$=yv();Q$({target:"String",proto:!0,forced:Y$},{padStart:function(e){return G$(this,e,arguments.length>1?arguments[1]:void 0)}})});var Ev=g((aU,Iv)=>{"use strict";Tv();var K$=Ti();Iv.exports=K$("String","padStart")});var xv=g((nU,wv)=>{"use strict";var X$=Ev();wv.exports=X$});var Pv=g((oU,kv)=>{"use strict";var J$=xv();kv.exports=J$});var QM={};Xy(QM,{ChromecastState:()=>Ir,HttpConnectionType:()=>nn,Observable:()=>ti.Observable,PlaybackState:()=>Ve,Player:()=>Ya,PredefinedQualityLimits:()=>gs,SDK_VERSION:()=>WM,Subject:()=>ti.Subject,Subscription:()=>ti.Subscription,Surface:()=>on,VERSION:()=>Jo,ValueSubject:()=>ti.ValueSubject,VideoFormat:()=>Qt,VideoQuality:()=>ti.VideoQuality,areValidLiveRecordSources:()=>Rh,clientChecker:()=>F,isMobile:()=>Ei});module.exports=Jy(QM);var Jo="2.0.150-dev.4e3741f9.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ve||{}),Qt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_FMP4="HLS_FMP4",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(Qt||{});var Ir=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ir||{}),nn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(nn||{});var on=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(on||{}),gs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(gs||{});var td=q(Yi(),1),Uy=q(We(),1);var ae=require("@vkontakte/videoplayer-shared");var vh=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 mn=class{constructor(e){this.connection$=new ae.ValueSubject(void 0);this.castState$=new ae.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new ae.Subject;this.realCastState$=new ae.ValueSubject("NOT_AVAILABLE");this.subscription=new ae.Subscription;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,ae.isNonNullable)(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||vh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ae.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,ae.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,ae.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,ae.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,ae.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,ae.assertNever)(r.sessionState)}})).add((0,ae.merge)((0,ae.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,ae.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,ae.map)(r=>r.castState)),(0,ae.observableFrom)([i.getCastState()])).pipe((0,ae.filterChanged)(),(0,ae.map)(QE),(0,ae.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",n=(0,ae.isNonNullable)(this.connection$.getValue());if(a&&!n){let o=i.getCurrentSession();(0,ae.assertNonNullable)(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;((0,ae.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,ae.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:ae.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},QE=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,ae.assertNever)(s)}};var ne=require("@vkontakte/videoplayer-shared");var Ne=require("@vkontakte/videoplayer-shared");var Cu=require("@vkontakte/videoplayer-shared");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,Cu.assertNever)(t)}return s},Ii=(s,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(s);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(s);return Number(t.searchParams.get("offset_p")??0)}default:(0,Cu.assertNever)(e)}};var gn=s=>{let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let c=e[t];(0,Ne.assertNonNullable)(c);let d=(0,Ne.getHighestQuality)(Object.keys(c));(0,Ne.assertNonNullable)(d);let h=c[d];(0,Ne.assertNonNullable)(h),a=h,n="video/mp4",o=bn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=e[t];(0,Ne.assertNonNullable)(c),a=c.url,n="application/x-mpegurl",o=bn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=e[t];(0,Ne.assertNonNullable)(c),a=c.url,n="application/dash+xml",o=bn();break}case"DASH_LIVE_CMAF":{let c=e[t];(0,Ne.assertNonNullable)(c),a=c.url,n="application/dash+xml",o=yh();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=e[t];(0,Ne.assertNonNullable)(c),a=Ae(c.url),n="application/x-mpegurl",o=yh();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ne.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return(0,Ne.assertNever)(t)}let u=GE(i.videoId??a,n);u.contentUrl=a,u.streamType=o,u.metadata=YE();let{title:l,subtitle:p}=i;return(0,Ne.isNonNullable)(l)&&(u.metadata.title=l),(0,Ne.isNonNullable)(p)&&(u.metadata.subtitle=p),u};function bn(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function yh(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function GE(s,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:bn()}}function YE(){return chrome.cast?.media?.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 Sn=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 _u=require("@vkontakte/videoplayer-shared");var xn=require("@vkontakte/videoplayer-shared");var Th=q(We(),1),Ih=require("@vkontakte/videoplayer-shared");var vn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Th.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,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=(0,Ih.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 Eh=q(We(),1),wi=require("@vkontakte/videoplayer-shared");var Ei=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var yn=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,Eh.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,wi.getWindow)();if(!(0,wi.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=Ei()}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,wi.getWindow)();if(!(0,wi.isBrowserWindow)(e))return;let{userAgentData:t}=e.navigator;if(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",l="Unknown";if(n){let p=r[0];typeof p=="number"?p<a.length&&a[p]!==void 0&&(u=a[p]):u=p}if(o){let p=r[1];typeof p=="number"?p<a.length&&a[p]!==void 0&&(l=a[p]):p!==void 0&&(l=p)}else a[2]!==void 0?l=a[2]:a[1]!==void 0&&n&&typeof r[0]=="string"&&(l=a[1]);u=this.normalizeOSName(u),l=this.normalizeOSVersion(l,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:l||"Unknown",full:l&&l!=="Unknown"?`${u} ${l}`: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),l="Unknown";typeof o=="number"?l=a[o]!==void 0?a[o]:"Unknown":o!==void 0?l=o:a[1]!==void 0?l=a[1]:a[0]!==void 0&&(l=a[0]),l=this.normalizeModelName(l,u),this.details.vendor=u,this.details.model=l;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,wi.getWindow)();if(!(0,wi.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?.[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var $s=require("@vkontakte/videoplayer-shared"),Tn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,$s.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(){let e=(0,$s.getWindow)();if(!(0,$s.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=i.colorDepth}catch(a){console.error(a)}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(a){console.error(a)}}};var Ki=require("@vkontakte/videoplayer-shared");var rt=()=>window.ManagedMediaSource||window.MediaSource,xi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),wh=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),$r=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var KE=(0,Ki.getWindow)().document?.createElement("video"),XE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',JE='video/mp4; codecs="hev1.1.6.L93.B0"',xh='video/webm; codecs="vp09.00.10.08"',kh='video/webm; codecs="av01.0.00M.08"',ZE='audio/mp4; codecs="mp4a.40.2"',ew='audio/webm; codecs="opus"',Ph,tw=async()=>{let s=(0,Ki.getWindow)();if(!(0,Ki.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:kh}}),s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:xh}})]);Ph={DASH_WEBM_AV1:t,DASH_WEBM:i}};tw().catch(s=>{console.log(KE),console.error(s)});var In=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Ph}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=(0,Ki.getWindow)();if(!(0,Ki.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:xi(),mse:wh(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let i=!!rt()?.isTypeSupported?.(XE),r=!!rt()?.isTypeSupported?.(JE),a=!!rt()?.isTypeSupported?.(ZE);this._codecs={h264:i,h265:r,vp9:!!rt()?.isTypeSupported?.(xh),av1:!!rt()?.isTypeSupported?.(kh),aac:a,opus:!!rt()?.isTypeSupported?.(ew),mpeg:(i||r)&&a},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(i){console.error(i)}try{this.destroyVideoElement()}catch(i){console.error("Error destroying video element:",i)}}destroyVideoElement(){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);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var wn=require("@vkontakte/videoplayer-shared");var Ah="audio/mpeg",En=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=(0,wn.getWindow)();if(!(0,wn.isBrowserWindow)(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Ah)},this._codecs={mp3:!!rt()?.isTypeSupported?.(Ah)}}catch(i){console.error(i)}try{this.destroyAudioElement()}catch(i){console.error("Error destroying audio element:",i)}}destroyAudioElement(){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);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};var Vu=class{constructor(){this.isInited$=new xn.ValueSubject(!1);this._displayChecker=new Tn,this._deviceChecker=new yn(this._displayChecker),this._browserChecker=new vn,this._videoChecker=new In(this._deviceChecker,this._browserChecker),this._audioChecker=new En,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){(0,xn.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},F=new Vu;var Ou=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=F.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,_u.assertNever)(o)}})},Ms=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,_u.assertNever)(s)}},Rh=s=>{let t=Object.keys(s).filter(i=>!Ms(i));return Ou(t).length>0};var Ls=class{constructor(e){this.subscription=new ne.Subscription;this.sessionId$=new ne.ValueSubject(null);this.mediaSessionId$=new ne.ValueSubject(null);this.contentId$=new ne.ValueSubject(null);this.isMobile=Ei();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if((0,ne.isNullable)(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=e.media?.duration;(0,ne.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,ne.isNonNullable)(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let n=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!n?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new Sn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ms(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:ne.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,ne.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,ne.filter)(ne.isNonNullable),(0,ne.filterChanged)(),(0,ne.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,ne.filterChanged)(),(0,ne.map)(Boolean));this.subscription.add((0,ne.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,ne.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,ne.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,ne.filter)(({mediaLoaded:r})=>r),(0,ne.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,ne.filter)(({mediaLoaded:r,playbackState:{from:a,to:n}})=>!r&&a==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,ne.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,ne.debounce)(30)),mediaLoaded:t}).pipe((0,ne.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:n}=r.to;this.setVolume(n,a)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=gn(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=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,ne.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,ne.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,ne.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,ne.isNullable)(e))return;let{level:t,muted:i}=e,r={muted:i??!1,volume: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 me=require("@vkontakte/videoplayer-shared");var $h=s=>({castDevice:{friendlyName:s},remotePlayer:{},remotePlayerController:{},session:{}}),Mh=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Ds=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new me.ValueSubject(null);this.sessionId$=new me.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new me.Subscription;this.subscriptionEvents=new me.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new me.ValueSubject(!1);this.presentationConnection$=new me.ValueSubject(null);this.message$=new me.ValueSubject(null);this.friendlyName$=new me.ValueSubject(null);this.errorEvent$=new me.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,me.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(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();(0,me.assertNonNullable)(e,"connect with null presentationRequest");let t=await e.start();this.handleConnection(t)}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:me.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add((0,me.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,me.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,me.filter)(e=>!!e)).subscribe(e=>{let t=(0,me.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,me.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,me.fromEvent)(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:me.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?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:me.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){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":e.message?.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]||Mh()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new me.Subscription}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};var Qe=require("@vkontakte/videoplayer-shared");var si=class s{constructor(e){this.subscription=new Qe.Subscription;this.connection$=new Qe.ValueSubject(void 0);this.castState$=new Qe.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new Qe.Subject;let t=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 Ds({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,Qe.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,Qe.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,Qe.filterChanged)())});this.subscription.add(e.pipe((0,Qe.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,Qe.filterChanged)()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?$h(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(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};var Kc=q(We(),1),Xc=q(ki(),1),Py=q(nl(),1);var dg=q(Kn(),1);var Kt=require("@vkontakte/videoplayer-shared"),te=class{constructor(e){this.transitionStarted$=new Kt.Subject;this.transitionEnded$=new Kt.Subject;this.transitionUpdated$=new Kt.Subject;this.forceChanged$=new Kt.Subject;this.stateChangeStarted$=(0,Kt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Kt.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,Kt.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 de=require("@vkontakte/videoplayer-shared");var UA=5,qA=5,jA=500,cg=7e3,Ws=class{constructor(e){this.subscription=new de.Subscription;this.loadMediaTimeoutSubscription=new de.Subscription;this.videoState=new te("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?.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,de.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,de.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,de.assertNever)(e)}break}default:(0,de.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(Ms(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 de.Subscription;this.subscription.add(e),this.subscription.add((0,de.merge)(this.videoState.stateChangeStarted$.pipe((0,de.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,de.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 de.Subject;e.add(r.pipe((0,de.debounce)(jA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,de.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)>UA)&&r.next(o),a=o})),e.add((0,de.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,de.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,de.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,de.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<qA&&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,de.assertNever)(n)}}),t((0,de.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,de.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,de.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,de.observableFrom)(["init"])).pipe((0,de.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=gn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??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,de.timeout)(cg).subscribe(()=>a(`timeout(${cg})`)))});(0,dg.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:de.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var nc=q(We(),1);var Qs=require("@vkontakte/videoplayer-shared");var pg=require("@vkontakte/videoplayer-shared"),hg=s=>{try{s.pause(),s.playbackRate=0,(0,pg.clearVideoElement)(s),s.remove()}catch(e){console.error(e)}};var Jn=require("@vkontakte/videoplayer-shared"),Wl=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Xn=(0,Qs.getWindow)(),Ql=Xn.WeakMap?new Xn.WeakMap:new Wl,Gl=Xn.WeakMap?new Xn.WeakMap:new Map,HA=(s,e=20)=>{let t=0;return(0,Jn.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Ge=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?(0,Qs.clearVideoElement)(i):(i=document.createElement("video"),s.appendChild(i)),Ql.set(i,r);let a=new Jn.Subscription;return a.add(HA(i,e)),Gl.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ye=s=>{Gl.get(s)?.unsubscribe(),Gl.delete(s);let t=Ql.get(s);Ql.delete(s),t?(0,Qs.clearVideoElement)(s):hg(s)};var Yl=q(Yi(),1),W=require("@vkontakte/videoplayer-shared");var Ai=require("@vkontakte/videoplayer-shared"),Zn=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,Ai.isNullable)(r),l=new Ai.Subscription;return r&&l.add(r.subscribe(p=>{let c=s.getState();i(p,c)&&s.setState(p)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(p=>{t(p.to),u&&s.setState(p.to)},a)),l},At=(s,e,t)=>Zn(e,()=>s.loop,i=>{(0,Ai.isNonNullable)(i)&&(s.loop=i)},{onError:t}),Ke=(s,e,t,i)=>Zn(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,Ai.isNonNullable)(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),lt=(s,e,t,i)=>Zn(e,()=>s.playbackRate,r=>{(0,Ai.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Gs=Zn;var zA=s=>["__",s.language,s.label].join("|"),WA=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Kl=class s{constructor(e){this.available$=new W.Subject;this.current$=new W.ValueSubject(void 0);this.error$=new W.Subject;this.subscription=new W.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:W.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(Gs(t.internalTextTracks,()=>(0,Yl.default)(this.internalTracks),a=>{(0,W.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,n)=>(0,W.isNonNullable)(a)&&(0,W.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,W.map)(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Gs(t.externalTextTracks,()=>(0,Yl.default)(this.externalTracks),a=>{(0,W.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,n)=>(0,W.isNonNullable)(a)&&(0,W.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,W.map)(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Gs(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(Gs(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,W.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,W.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,W.merge)((0,W.fromEvent)(e,"addtrack"),(0,W.fromEvent)(e,"removetrack"),(0,W.observableFrom)(["init"])).pipe((0,W.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,W.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add((0,W.merge)((0,W.fromEvent)(e,"change"),(0,W.observableFrom)(["init"])).pipe((0,W.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,W.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,W.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,W.fromEvent)(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add((0,W.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.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,W.isNonNullable)(t.align)&&(r.align=t.align),(0,W.isNonNullable)(t.position)&&(r.position=t.position),(0,W.isNonNullable)(t.size)&&(r.size=t.size),(0,W.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,W.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:zA(e),a=this.externalTracks.has(r),n=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.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,W.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,W.isNullable)(e)||!WA(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,W.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,W.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)}},ct=Kl;var ir=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 fg=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Xl=s=>{let e=fg(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},mg=s=>{let e=fg(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var C=require("@vkontakte/videoplayer-shared");var QA=3,bg=(s,e,t=QA)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var Xe=s=>{let e=D=>(0,C.fromEvent)(s,D).pipe((0,C.mapTo)(void 0),(0,C.shareReplay)(1)),t=new C.Subscription,i=()=>t.unsubscribe(),r=(0,C.merge)((0,C.fromEvent)(s,"progress"),(0,C.fromEvent)(s,"timeupdate")).pipe((0,C.map)(()=>bg(s.buffered,s.currentTime)),(0,C.shareReplay)(1)),a=F.browser.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0),(0,C.shareReplay)(1)):e("playing"),n=(0,C.fromEvent)(s,"volumechange").pipe((0,C.map)(()=>({muted:s.muted,volume:s.volume})),(0,C.shareReplay)(1)),o=(0,C.fromEvent)(s,"ratechange").pipe((0,C.map)(()=>s.playbackRate),(0,C.shareReplay)(1)),u=(0,C.fromEvent)(s,"error").pipe((0,C.filter)(()=>!!(s.error||s.played.length)),(0,C.map)(()=>{let D=s.error;return{id:D?`MediaError#${D.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:D?D.message:"Error event from HTML video element",thrown:s.error??void 0}}),(0,C.shareReplay)(1)),l=(0,C.fromEvent)(s,"timeupdate").pipe((0,C.map)(()=>s.currentTime),(0,C.shareReplay)(1)),p=["waiting","seeking","seeked","timeupdate"],c=new C.Subject,d=.3,h;t.add((0,C.merge)(...p.map(D=>(0,C.fromEvent)(s,D))).subscribe(D=>{let se=s.currentTime;s.loop&&(0,C.isNonNullable)(h)&&(0,C.isNonNullable)(se)&&h>=s.duration-d&&se<=d&&c.next(h),h=se}));let m=e("pause").pipe((0,C.filter)(()=>!s.error&&h!==s.duration),(0,C.shareReplay)(1)),b=(0,C.fromEvent)(s,"enterpictureinpicture").pipe((0,C.shareReplay)(1)),v=(0,C.fromEvent)(s,"leavepictureinpicture").pipe((0,C.shareReplay)(1)),S=new C.ValueSubject(mg(s));t.add(b.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let y=new C.ValueSubject(Xl(s)),k=(0,C.fromEvent)(s,"fullscreenchange").pipe((0,C.shareReplay)(1));t.add(k.pipe((0,C.map)(()=>Xl(s))).subscribe(y));let x=.1,L=1e3,O=(0,C.fromEvent)(s,"timeupdate").pipe((0,C.map)(D=>s.duration-s.currentTime<x),(0,C.filterChanged)(),(0,C.shareReplay)(1)),N=(0,C.merge)(O.pipe((0,C.filter)(D=>!s.loop&&D)),(0,C.fromEvent)(s,"ended")).pipe((0,C.throttle)(L),(0,C.mapTo)(void 0),(0,C.shareReplay)(1)),j=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(D=>(0,C.fromEvent)(s,D)),O.pipe((0,C.map)(D=>({type:D?"ended":"unknown"})))).pipe((0,C.map)(D=>F.browser.isFirefox&&D.type==="ended"?s.readyState<2:s.readyState<3),(0,C.filterChanged)(),(0,C.shareReplay)(1));return{playing$:a,pause$:m,canplay$:e("canplay"),ended$:N,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,C.fromEvent)(s,"durationchange").pipe((0,C.map)(()=>s.duration),(0,C.shareReplay)(1)),isBuffering$:j,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:y,enterPip$:b,leavePip$:v,destroy:i}};var ni=require("@vkontakte/videoplayer-shared"),Xt=s=>{switch(s){case"mobile":return ni.VideoQuality.Q_144P;case"lowest":return ni.VideoQuality.Q_240P;case"low":return ni.VideoQuality.Q_360P;case"sd":case"medium":return ni.VideoQuality.Q_480P;case"hd":case"high":return ni.VideoQuality.Q_720P;case"fullhd":case"full":return ni.VideoQuality.Q_1080P;case"quadhd":case"quad":return ni.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ni.VideoQuality.Q_2160P}};var at=q(dt(),1),Zl=q(We(),1),rr=q(ki(),1),_=require("@vkontakte/videoplayer-shared");var Jl=!1,oi={},Eg=s=>{Jl=s},wg=()=>{oi={}},xg=s=>{s(oi)},Ys=(s,e)=>{Jl&&(oi.meta=oi.meta??{},oi.meta[s]=e)},st=class{constructor(e){this.name=e}next(e){if(!Jl)return;oi.series=oi.series??{};let t=oi.series[this.name]??[];t.push([Date.now(),e]),oi.series[this.name]=t}};var $e=require("@vkontakte/videoplayer-shared");function kg(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Fr(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 Pg({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Fr({max:s?.max?(0,$e.videoHeightToQuality)(s.max):void 0,min:s?.min?(0,$e.videoHeightToQuality)(s.min):void 0},e?(0,$e.videoHeightToQuality)(e):void 0,t?(0,$e.videoHeightToQuality)(t):void 0)}var Lg=new st("best_bitrate"),to=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Ur=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),qt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,_.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},io='Assertion "ABR Tracks is empty array" failed',eo=new WeakMap,Ag=new WeakMap,Rg=new WeakMap,sr=(s,e,t,i)=>{let r=[...e].sort(Ur(1)),a=[...t].sort(Ur(1)),n=a.filter(u=>(0,_.isNonNullable)(u.bitrate)&&(0,_.isNonNullable)(s.bitrate)?s.bitrate/u.bitrate>i:!0),o=(0,at.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,at.default)(a,-1);return o&&(0,Zl.default)(n,o)?o:n.length?(0,at.default)(n,-1):(0,at.default)(a,0)},ar=(s,e,t,i)=>{let r=eo.get(e);r||(r=[...e].sort(Ur(1)),eo.set(e,r));let a=eo.get(t);a||(a=[...t].sort(Ur(1)),eo.set(t,a));let n=Rg.get(s);n||(n=a.filter(u=>(0,_.isNonNullable)(u.bitrate)&&(0,_.isNonNullable)(s.bitrate)?s.bitrate/u.bitrate>i:!0),Rg.set(s,n));let o=(0,at.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,at.default)(a,-1);return o&&(0,Zl.default)(n,o)?o:n.length?(0,at.default)(n,-1):(0,at.default)(a,0)},$g=s=>"quality"in s,ro=(s,e,t,i)=>{let r=(0,_.isNonNullable)(i?.last?.bitrate)&&(0,_.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,_.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let n=i.last;i?.recordSwitch(n);let o=$g(n)?"video":"audio",u=$g(n)?n.quality:n.bitrate;return e({message:`
8
8
  [last ${o} selected] ${u}
9
9
  `}),n}return i?.recordSwitch(t),t},iR=(s,e)=>Math.log(e)/Math.log(s),Dg=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&F.display.pixelRatio){let a=F.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,p=iR(n,o*a+u)+l;Number.isFinite(p)&&(r*=p)}}return(0,_.isNonNullable)(t?.min)&&(0,_.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}},Mg=new WeakMap,Rt=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{(0,_.assertNotEmptyArray)(s,io);let{containerSizeFactor:v,containerSizeLimit:S}=Dg({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,_.isNonNullable)(o)?o:1,k=Mg.get(s);k||(k=s.filter(A=>!(0,_.isInvariantQuality)(A.quality)).sort((A,P)=>(0,_.isHigher)(A.quality,P.quality)?-1:1),Mg.set(s,k));let x=(0,at.default)(k,-1)?.quality,L=(0,at.default)(k,0)?.quality,O=Fr(r,L,x),N=y*to(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),M={},j=null;for(let A of k){let P=!0;if(S)if(A.size)P=A.size.width<=S.width&&A.size.height<=S.height;else{let pe=S&&(0,_.videoSizeToQuality)(S);P=pe?(0,_.isLowerOrEqual)(A.quality,pe):!0}if(!P){M[A.quality]="FitsContainer";continue}let re=h||t,U=(0,_.isNonNullable)(re)&&isFinite(re)&&(0,_.isNonNullable)(A.bitrate)?re-a>=A.bitrate*N:!0,ce=r?.min===A.quality;if(!U&&!ce){M[A.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,_.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,_.isInvariantQuality)(u.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,_.isHigher)(A.quality,u.quality)){M[A.quality]="Buffer";continue}if(!!c&&(0,_.isHigherOrEqual)(A.quality,c)&&!ce){M[A.quality]="DroppedFramesLimit";continue}if(!!d&&(0,_.isHigherOrEqual)(A.quality,d)&&!ce){M[A.quality]="StallsLimit";continue}let qe=O||((0,_.isNullable)(r?.max)||(0,_.isLowerOrEqual)(A.quality,r.max))&&((0,_.isNullable)(r?.min)||(0,_.isHigherOrEqual)(A.quality,r.min)),je=(0,_.isNonNullable)(p)&&!p?(0,_.isLowerOrEqual)(A.quality,i.backgroundVideoQualityLimit):!0;if(!qe||!je){M[A.quality]="FitsQualityLimits";continue}j||(j=A)}j&&j.bitrate&&Lg.next(j.bitrate);let D=j??(0,at.default)(k,-1)??s[0],se=l?.last,z=ro(i,m,D,l);return(0,_.isNonNullable)(l)&&z.quality!==se?.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(p,"i")}var Mv=s=>{if(!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?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},It=(s,e)=>{let t=s;t=(0,xc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Lv.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,xc.default)(t,n,(o,u)=>(0,sa.isNullable)(a)?o:(0,sa.isNullable)(u)?a:(0,Dv.default)(a,parseInt(u,10),"0"))}return t},es=(s,e)=>{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(j=>j.textContent?.trim()??""),o=(0,Bv.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),p=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let S,y=a.getAttribute("mediaPresentationDuration"),k=[...a.getElementsByTagName("Period")],x=k.reduce((j,D)=>({...j,[D.id]:D.children}),{}),L=k.reduce((j,D)=>({...j,[D.id]:D.getAttribute("duration")}),{});y?S=Mv(y):(0,kc.default)(L).filter(j=>j).length&&!u?S=(0,kc.default)(L).reduce((j,D)=>j+(Mv(D)??0),0):b&&(S=parseInt(b,10));let O=0,N=a.getAttribute("profiles")?.split(",")??[];for(let j of k.map(D=>D.id))for(let D of x[j]){let se=D.getAttribute("id")??"id"+(O++).toString(10),z=D.getAttribute("mimeType")??"",A=D.getAttribute("codecs")??"",P=D.getAttribute("contentType")??z?.split("/")[0],re=D.getAttribute("profiles")?.split(",")??[],U=$v(D.getAttribute("lang")??"")??{},ce=D.querySelector("Label")?.textContent?.trim()??void 0,ge=D.querySelectorAll("Representation"),xe=D.querySelector("SegmentTemplate"),Le=D.querySelector("Role")?.getAttribute("value")??void 0,qe=P,je={id:se,language:U.language,isDefault:Le==="main",label:ce,codecs:A,hdr:qe==="video"&&wc(A),mime:z,representations:[]};for(let pe of ge){let oe=pe.getAttribute("lang")??void 0,He=ce??D.getAttribute("label")??pe.getAttribute("label")??void 0,tt=pe.querySelector("BaseURL")?.textContent?.trim()??"",Ce=new URL(tt||o,e).toString(),kt=pe.getAttribute("mimeType")??z,bi=pe.getAttribute("codecs")??A??"",Dt;if(P==="text"){let gt=pe.getAttribute("id")||"",gi=U.privateuse?.includes("x-auto")||gt.includes("_auto"),Bt=pe.querySelector("SegmentTemplate");if(Bt){let hs={representationId:pe.getAttribute("id")??void 0,bandwidth:pe.getAttribute("bandwidth")??void 0},Ka=parseInt(pe.getAttribute("bandwidth")??"",10)/1e3,Xa=parseInt(Bt.getAttribute("startNumber")??"",10)??1,br=parseInt(Bt.getAttribute("timescale")??"",10),Ko=Bt.querySelectorAll("SegmentTimeline S")??[],gr=Bt.getAttribute("media");if(!gr)continue;let Ja=[],Za=0,en="",Sr=0,fs=Xa,it=0;for(let Ct of Ko){let Ui=parseInt(Ct.getAttribute("d")??"",10),Pt=parseInt(Ct.getAttribute("r")??"",10)||0,Si=parseInt(Ct.getAttribute("t")??"",10);it=Number.isFinite(Si)?Si:it;let qi=Ui/br*1e3,vr=it/br*1e3;for(let zt=0;zt<Pt+1;zt++){let vi=It(gr,{...hs,segmentNumber:fs.toString(10),segmentTime:(it+zt*Ui).toString(10)}),yr=(vr??0)+zt*qi,bs=yr+qi;fs++,Ja.push({time:{from:yr,to:bs},url:vi})}it+=(Pt+1)*Ui,Za+=(Pt+1)*qi}Sr=it/br*1e3,en=It(gr,{...hs,segmentNumber:fs.toString(10),segmentTime:it.toString(10)});let ms={time:{from:Sr,to:1/0},url:en},ii={type:"template",baseUrl:Ce,segmentTemplateUrl:gr,initUrl:"",totalSegmentsDurationMs:Za,segments:Ja,nextSegmentBeyondManifest:ms,timescale:br};Dt={id:gt,kind:"text",segmentReference:ii,profiles:[],duration:S,bitrate:Ka,mime:"",codecs:"",width:0,height:0,isAuto:gi}}else Dt={id:gt,isAuto:gi,kind:"text",url:Ce}}else{let gt=pe.getAttribute("contentType")??kt?.split("/")[0]??P,gi=D.getAttribute("profiles")?.split(",")??[],Bt=parseInt(pe.getAttribute("width")??"",10),hs=parseInt(pe.getAttribute("height")??"",10),Ka=parseInt(pe.getAttribute("bandwidth")??"",10)/1e3,Xa=pe.getAttribute("frameRate")??"",br=pe.getAttribute("quality")??void 0,Ko=Xa?Rv(Xa):void 0,gr=pe.getAttribute("id")??"id"+(O++).toString(10),Ja=gt==="video"?`${hs}p`:gt==="audio"?`${Ka}Kbps`:bi,Za=`${gr}@${Ja}`,en=[...N,...re,...gi],Sr,fs=pe.querySelector("SegmentBase"),it=pe.querySelector("SegmentTemplate")??xe;if(fs){let ii=pe.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ct,Ui]=ii.split("-").map(vi=>parseInt(vi,10)),Pt={from:Ct,to:Ui},Si=pe.querySelector("SegmentBase")?.getAttribute("indexRange"),[qi,vr]=Si?Si.split("-").map(vi=>parseInt(vi,10)):[],zt=Si?{from:qi,to:vr}:void 0;Sr={type:"byteRange",url:Ce,initRange:Pt,indexRange:zt}}else if(it){let ii={representationId:pe.getAttribute("id")??void 0,bandwidth:pe.getAttribute("bandwidth")??void 0},Ct=parseInt(it.getAttribute("timescale")??"",10),Ui=it.getAttribute("initialization")??"",Pt=it.getAttribute("media"),Si=parseInt(it.getAttribute("startNumber")??"",10)??1,qi=It(Ui,ii);if(!Pt)throw new ReferenceError("No media attribute in SegmentTemplate");let vr=it.querySelectorAll("SegmentTimeline S")??[],zt=[],vi=0,yr="",bs=0;if(vr.length){let tn=Si,Vt=0;for(let Tr of vr){let Wt=parseInt(Tr.getAttribute("d")??"",10),ji=parseInt(Tr.getAttribute("r")??"",10)||0,rn=parseInt(Tr.getAttribute("t")??"",10);Vt=Number.isFinite(rn)?rn:Vt;let Xo=Wt/Ct*1e3,jy=Vt/Ct*1e3;for(let sn=0;sn<ji+1;sn++){let Hy=It(Pt,{...ii,segmentNumber:tn.toString(10),segmentTime:(Vt+sn*Wt).toString(10)}),id=(jy??0)+sn*Xo,zy=id+Xo;tn++,zt.push({time:{from:id,to:zy},url:Hy})}Vt+=(ji+1)*Wt,vi+=(ji+1)*Xo}bs=Vt/Ct*1e3,yr=It(Pt,{...ii,segmentNumber:tn.toString(10),segmentTime:Vt.toString(10)})}else if((0,sa.isNonNullable)(S)){let Vt=parseInt(it.getAttribute("duration")??"",10)/Ct*1e3,Tr=Math.ceil(S/Vt),Wt=0;for(let ji=1;ji<Tr;ji++){let rn=It(Pt,{...ii,segmentNumber:ji.toString(10),segmentTime:Wt.toString(10)});zt.push({time:{from:Wt,to:Wt+Vt},url:rn}),Wt+=Vt}bs=Wt,yr=It(Pt,{...ii,segmentNumber:Tr.toString(10),segmentTime:Wt.toString(10)})}let qy={time:{from:bs,to:1/0},url:yr};Sr={type:"template",baseUrl:Ce,segmentTemplateUrl:Pt,initUrl:qi,totalSegmentsDurationMs:vi,segments:zt,nextSegmentBeyondManifest:qy,timescale:Ct}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!gt||!kt)continue;let ms={video:"video",audio:"audio",text:"text"}[gt];if(!ms)continue;qe||=ms,Dt={id:Za,kind:ms,segmentReference:Sr,profiles:en,duration:S,bitrate:Ka,mime:kt,codecs:bi,width:Bt,height:hs,fps:Ko,quality:br}}je.language||=oe,je.label||=He,je.mime||=kt,je.codecs||=bi,je.hdr||=qe==="video"&&wc(bi),je.representations.push(Dt)}if(qe){let pe=r[qe].find(oe=>oe.id===je.id);if(pe&&je.representations.every(oe=>oe.segmentReference.type==="template"))for(let oe of pe.representations){let He=je.representations.find(kt=>kt.id===oe.id);if(!He)continue;let tt=He.segmentReference,Ce=oe.segmentReference;Ce.segments.push(...tt.segments),Ce.nextSegmentBeyondManifest=tt.nextSegmentBeyondManifest}else r[qe].push(je)}}return{duration:S,streams:r,baseUrls:n,live:v}};var So=q(dt(),1),Pc=q(We(),1),aa=require("@vkontakte/videoplayer-shared");var go=s=>{let{webmDecodingInfo:e}=F.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,aa.assertNever)(s)}},Cv=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...go(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(F.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",...go(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...go(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...go(s),...a,"HLS","HLS_ONDEMAND"];default:(0,aa.assertNever)(e)}if(F.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,aa.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},Vv=({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=F.device.isMac&&F.browser.isSafari;if(F.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,aa.assertNever)(s)}else F.video.nativeHlsSupported&&!u&&!F.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"]},Ac=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ts=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,So.default)(t.value.split("."),0)}for(let t of s){let i=(0,So.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,So.default)(e.value.split("."),0)},is=s=>{let e=s.map(i=>Bi(i)),{codecs:t}=F.video;return rM().filter(i=>{if((0,Pc.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})},rs=s=>{let e=s.map(i=>Bi(i)),{codecs:t}=F.video;return sM().filter(i=>{if((0,Pc.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Bi=s=>s.split(".")[0].replace("0",""),rM=()=>["av1","vp9","hev1","avc1"],sM=()=>["opus","mp4a"];var Xv=q(dt(),1);var aM=(s,e={})=>{let i=e.timeout||1,r=performance.now();return Me.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},nM=s=>Me.clearTimeout(s),_v=s=>typeof s=="function"&&s?.toString().endsWith("{ [native code] }"),Ov=!_v(Me.requestIdleCallback)||!_v(Me.cancelIdleCallback),Zt=Ov?aM:Me.requestIdleCallback,$t=Ov?nM:Me.cancelIdleCallback;var V=require("@vkontakte/videoplayer-shared");var Fv=q(dt(),1);var vo=s=>s.valid,he=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 ss=class extends he{};var Nv=require("@vkontakte/videoplayer-shared");var na=class extends he{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,Nv.assertNever)(e)}}};var oa=class extends he{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 ua=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Te=class extends he{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 la=class extends Te{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 ca=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends he{constructor(e,t){super(e,t),this.data=this.content}};var ur=class extends Te{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var pa=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends Te{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 ma=class extends Te{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var ba=class extends Te{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 ga=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends Te{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 va=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends Te{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ia=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=class extends Te{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 wa=class extends Te{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 xa=class extends Te{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 ka=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends Te{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 Aa=class extends he{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 uM={ftyp:oa,moov:ua,mvhd:la,moof:ca,mdat:da,sidx:ur,trak:pa,mdia:ga,mfhd:Ta,tkhd:Sa,traf:Ia,tfhd:Ea,tfdt:wa,trun:xa,minf:va,sv3d:ha,st3d:fa,prhd:ma,proj:ya,equi:ba,uuid:na,stbl:ka,stsd:Pa,avc1:Aa,unknown:ss},ci=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||!vo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=uM[e];return i?new i(t,new s):new ss(t,new s)}};var Ci=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{vo(t)&&(this.index[t.type]??=[],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 cM=new TextDecoder("ascii"),dM=s=>cM.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",pM=s=>{let e=new ur(s,new ci),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})},hM=(s,e)=>{let i=new ci().parse(s),r=new Ci(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},fM=s=>{let t=new ci().parse(s),i=new Ci(t),r={},a=i.findAll("uuid"),n=(0,Fv.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},mM=s=>{let t=new ci().parse(s);return new Ci(t).find("sidx")?.timescale},bM=(s,e)=>{let i=new ci().parse(s),a=new Ci(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},gM=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 ci().parse(s),r=new Ci(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},Uv={validateData:dM,parseInit:gM,getIndexRange:()=>{},parseSegments:pM,parseFeedableSegmentChunk:hM,getChunkEndTime:bM,getServerLatencyTimestamps:fM,getTimescaleFromIndex:mM};var $a=q(We(),1),di=require("@vkontakte/videoplayer-shared");var jv=require("@vkontakte/videoplayer-shared");var qv={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"}},Hv=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=Ra(s,t),r=i in qv,a=r?qv[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,p=Ra(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+d):h=new DataView(s.buffer,s.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},Ra=(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},Ht=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Ra(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,jv.assertNever)(e)}},lr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Hv(i);if(!e(r))return;r.type==="master"&&lr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},zv=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Hv(s);return lr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Ht(o,n):a===17026?t=Ht(o,n):a===17029&&(i=Ht(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Wv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],SM=[231,22612,22743,167,171,163,160,175],vM=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,p=!1,c=0;return lr(s,({tag:d,type:h,value:m,valueSize:b})=>{if(d===21419){let v=Ht(m,h);l=Ra(v)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+b):d===357149030?a=!0:d===290298740?n=!0:d===2807729?i=Ht(m,h):d===17545?r=Ht(m,h):d===21420&&l===475249515?u=Ht(m,h):d===374648427?lr(m,({tag:v,type:S,value:y})=>v===30321?(p=Ht(y,S)===1,!1):!0):a&&n&&(0,$a.default)(Wv,d)&&(o=!0),!o}),(0,di.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,di.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,di.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=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:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},yM=s=>{if((0,di.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},TM=(s,e)=>{let t=!1,i=!1,r=o=>(0,di.isNonNullable)(o.time)&&(0,di.isNonNullable)(o.position),a=[],n;return lr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Ht(l,u));break;case 183:break;case 241:n&&(n.position=Ht(l,u));break;default:t&&(0,$a.default)(Wv,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:p}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},IM=s=>{let e=0,t=!1;try{lr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,$a.default)(SM,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,$a.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Qv={validateData:zv,parseInit:vM,getIndexRange:yM,parseSegments:TM,parseFeedableSegmentChunk:IM};var Mt=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Qv;case"mp4":return Uv}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Rc=q(dt(),1);var Gv=require("@vkontakte/videoplayer-shared"),Vi=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Xt(a):void 0)??(0,Gv.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ma=({id:s,bitrate:e})=>({id:s,bitrate:e}),Yv=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Kv=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),$c=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Rc.default)(i.split("."),0),isDefault:r}),Mc=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Rc.default)(r.split("."),0)}),Lc=s=>"url"in s,Et=s=>s.type==="template";var as=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,manifest:o}){this.error$=new V.Subject;this.playingRepresentation$=new V.ValueSubject(void 0);this.playingRepresentationInit$=new V.ValueSubject(void 0);this.currentSegmentLength$=new V.ValueSubject(0);this.onLastSegment$=new V.ValueSubject(!1);this.fullyBuffered$=new V.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 le;this.downloadAbortController=new le;this.subscription=new V.Subscription;this.startWith=(0,V.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,V.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=Mt(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,V.assertNonNullable)(i,"No init buffer for starting representation"),(0,V.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,V.abortable)(this.destroyAbortController.signal,async function*(e,t=!0){if((0,V.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,V.assertNonNullable)(r,`No such representation ${e}`),(0,V.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,V.assertNonNullable)(a,"No init buffer for switching representation"),(0,V.assertNonNullable)(n,"No segments for switching representation");let o=this.getCurrentPosition()??0,u=c=>c.segment.networkStatus!=="downloaded"||c.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,l=c=>{let d=this.representations.get(c.representationId);return(0,V.assertNonNullable)(d,"No itemRepresentation for previous track before switch"),c.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(d,r)},p=c=>t?u(c)&&l(c):u(c);this.bufferPlaybackQueue.filter(p).forEach(c=>c.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(c=>!p(c)),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,V.abortable)(this.downloadAbortController.signal,async function*(){let e=(0,V.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,V.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,V.fromEvent)(i,"online").pipe((0,V.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=n,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(u=>[u.id,u]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){(0,V.isNullable)(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return(0,V.isNonNullable)(t)&&(0,V.isNonNullable)(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from}getRepresentationInitialTime(){return(0,V.isNullable)(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if((0,V.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Xv.default)(e,-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,V.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_e2b3kd3ekf2)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_e2b3kd3ekf2(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=Vi(e),a=Vi(t);i=(0,V.isNonNullable)(r)&&(0,V.isNonNullable)(a)&&(0,V.isHigher)(a.quality,r.quality)}else if(this.kind==="audio"){let r=Ma(e),a=Ma(t);i=(0,V.isNonNullable)(r?.bitrate)&&(0,V.isNonNullable)(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 le,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,Zt(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,V.isNonNullable)(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,a);let{initMetadata:n,initDataView:o,segments:u}=await a??{};if(this.initDataPromises.delete(e.id),(0,V.isNullable)(o)||(0,V.isNullable)(u))return;n&&this.parsedInitData.set(e.id,n);let l=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,u),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:V.ErrorCategory.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if((0,V.isNullable)(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(o=>this.withinInterval(e,o.segment.time)),i=this.bufferPlaybackQueue.find(o=>o.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),a=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;(0,V.isNonNullable)(r)&&(0,V.isNonNullable)(i)&&(0,V.isNonNullable)(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,V.isNonNullable)(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),(0,V.isNonNullable)(a)&&this.withinRemoveInterval(e,a.segment.time)&&await this.removeSegment(a,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){(0,V.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,V.isNullable)(t)||(0,V.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,V.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(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){let t=this.segments.get(this.downloadingRepresentationId??"");if((0,V.isNullable)(t)||t.length===0)return;let i=t[t?.length-1];(0,V.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,V.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;(0,V.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,V.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,V.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,V.isNonNullable)(e)?e-i>t:!1}async appendSegmentFully(e,t){if((0,V.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,V.isNullable)(e.segment.data)||(0,V.isNullable)(e.segment.loadedBytes)||(0,V.isNullable)(e.segment.feedingBytes)||(0,V.isNullable)(e.segment.fedBytes)||(0,V.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?.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,V.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,V.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,V.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 ei=require("@vkontakte/videoplayer-shared");var yo=class extends as{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,ei.now)(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Ze(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(nt(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,ei.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ei.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},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,ei.isNullable)(o)||(0,ei.isNullable)(r)||n.aborted))for(let u of e){let{segment:l}=u,p=l.byte.from-r,c=l.byte.to-r,d=c-p+1,h=p<a,m=c<=a;l.size=d,h&&(l.networkStatus==="downloading"&&l.bufferStatus==="none"&&m?(l.data=new DataView(t.buffer,t.byteOffset+p,d),this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u),l.loadedBytes=Math.min(d,a-p),await this.onDownloadItem(u)):(0,ei.isNonNullable)(l.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&l.networkStatus==="downloading"&&(l.loadedBytes=Math.min(d,a-p),m&&(this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u)),l.loadedBytes>l.feedingBytes&&(l.data=new DataView(t.buffer,t.byteOffset+p,l.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(nt(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var pi=require("@vkontakte/videoplayer-shared");var ns=class extends as{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,pi.now)(),(0,pi.isNullable)(o))return;let u=e[0],l=new DataView(o);u.segment.size=l.byteLength,u.segment.loadedBytes=l.byteLength,u.segment.data=l,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Ze(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,pi.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:pi.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!nt(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,pi.isNullable)(u)||(0,pi.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(!nt(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var Dc=q(nr(),1),Jv=q(dt(),1);var Ue=require("@vkontakte/videoplayer-shared");var To=class extends ns{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new Ue.ValueSubject(0);this.currentLowLatencySegmentLength$=new Ue.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=(0,Dc.default)(t.streams[this.kind],r=>r.representations);for(let r of i){if((0,Ue.isNullable)(r)||!nt(r.segmentReference))return;let a=r.segmentReference.segments.map(p=>({...p,networkStatus:"none",bufferStatus:"none",size:void 0})),n=100,o=this.segments.get(r.id)??[],u=(0,Jv.default)(o,-1)?.time.to??0,l=a?.findIndex(p=>u>=p.time.from+n&&u<=p.time.to+n);if(l===-1){let p=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,p)}else{let p=a.slice(l+1);this.segments.set(r.id,[...o,...p])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Ue.assertNonNullable)(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t?.streams[this.kind],r=(0,Dc.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Ue.isNullable)(r))return;let a=this.segments.get(r.id);if(a?.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){if((0,Ue.isNullable)(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return(0,Ue.isNullable)(t)||!nt(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,Ue.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){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if((0,Ue.isNullable)(t.segment.data)||(0,Ue.isNullable)(r)||!nt(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:n}=r;t.segment.time.to=a.getChunkEndTime(i,n)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!nt(a))return;let n=this.segments.get(r.id)??[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.from));if(o?.isCurrentLowLatency&&(o.time.to=t.segment.time.to,i=o.time.to-o.time.from,o.isCurrentLowLatency=!1),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let l=Math.round(t.segment.time.to*a.timescale/1e3).toString(10),p=It(a.segmentTemplateUrl,{segmentTime:l});n.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:p,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){try{let a=this.tuning.dash.useFetchPriorityHints?i:"auto",n=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,a);this.initDataPromises.set(t.id,n);let{initMetadata:o,initDataView:u,segments:l}=await n??{};if(this.initDataPromises.delete(t.id),(0,Ue.isNullable)(u)||(0,Ue.isNullable)(l))return;o&&this.parsedInitData.set(t.id,o);let p=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,p);let c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(t.id,c),this.failedDownloads=0}catch(a){r&&this.error$.next({id:"LoadInits",category:Ue.ErrorCategory.WTF,message:"loadInit threw",thrown:a})}}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 La=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new To(e,t,i,r):nt(i[0].segmentReference)?new ns(e,t,i,r):new yo(e,t,i,r)}};var ot=require("@vkontakte/videoplayer-shared");var _i=require("@vkontakte/videoplayer-shared");var EM=18,Zv=!1;try{Zv=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=EM}catch(s){console.error(s)}var Bc=class{constructor(e,t=!1){this.bufferFull$=new _i.Subject;this.error$=new _i.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:_i.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};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)};Zv&&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(){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(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:_i.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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,_i.assertNever)(t)}}},ey=Bc;var Be=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var Da=class{constructor(e){this.error$=new ot.Subject;this.subscription=new ot.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new ey(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,ot.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ot.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,ot.isNullable)(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!(0,ot.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,ot.isNullable)(this.sourceBuffer)||!G(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,ot.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,ot.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}async abortBuffer(e){return(0,ot.isNullable)(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var wM=["timeupdate","progress","play","seeked","stalled","waiting"],ty=["timeupdate","progress","loadeddata","playing","seeked"],Io=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new E.Subscription;this.subscriptionRemovable=new E.SubscriptionRemovable;this.representationSubscription=new E.Subscription;this.forceEnded$=new E.Subject;this.destroyController=new le;this.state$=new te("none");this.currentVideoRepresentation$=new E.ValueSubject(void 0);this.currentVideoRepresentationInit$=new E.ValueSubject(void 0);this.currentAudioRepresentation$=new E.ValueSubject(void 0);this.currentVideoSegmentLength$=new E.ValueSubject(0);this.currentAudioSegmentLength$=new E.ValueSubject(0);this.error$=new E.Subject;this.manifestRequested=new E.Subject;this.manifestReceived=new E.Subject;this.firstBytesRequested=new E.Subject;this.firstBytesReceived=new E.Subject;this.lastConnectionType$=new E.ValueSubject(void 0);this.lastConnectionReused$=new E.ValueSubject(void 0);this.lastRequestFirstBytes$=new E.ValueSubject(void 0);this.currentLiveTextRepresentation$=new E.ValueSubject(null);this.isLive$=new E.ValueSubject(!1);this.isActiveLive$=new E.ValueSubject(!1);this.isLowLatency$=new E.ValueSubject(!1);this.liveDuration$=new E.ValueSubject(0);this.liveSeekableDuration$=new E.ValueSubject(0);this.liveAvailabilityStartTime$=new E.ValueSubject(0);this.liveStreamStatus$=new E.ValueSubject(void 0);this.currentBuffer$=new E.ValueSubject({from:0,to:0});this.bufferLength$=new E.ValueSubject(0);this.nativeBufferLength$=new E.ValueSubject(0);this.liveLatency$=new E.ValueSubject(void 0);this.liveLoadBufferLength$=new E.ValueSubject(0);this.livePositionFromPlayer$=new E.ValueSubject(0);this.currentStallDuration$=new E.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new E.ValueSubject(0);this.fetcherRecoverableError$=new E.Subject;this.fetcherError$=new E.Subject;this.initRepresentations=(0,E.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,E.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),(0,E.assertNonNullable)(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=(0,E.abortable)(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){(0,E.isNullable)(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:E.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new mo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:E.ErrorCategory.PARSER,message:"No playable video representations"})}initBuffer(){(0,E.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,E.merge)(...wM.map(t=>(0,E.fromEvent)(this.element,t)),(0,E.fromEvent)((0,E.getWindow)(),"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:E.ErrorCategory.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add((0,E.merge)(...e.map(t=>(0,E.fromEvent)(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add((0,E.fromEvent)(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,E.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:E.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){(0,E.assertNonNullable)(this.element),(0,E.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",(0,E.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,E.isNonNullable)(this.element)&&(0,E.isNonNullable)(this.source)&&(0,E.isNonNullable)(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&(0,E.getWindow)().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),(0,E.isNonNullable)(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if((0,E.isNullable)(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){(0,E.assertNonNullable)(this.element),(0,E.assertNonNullable)(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",(0,E.flattenObject)(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=(0,E.now)(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,l=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,p=(0,E.isNonNullable)(this.videoBufferManager)&&u<a&&r-n>i,c=(0,E.isNonNullable)(this.audioBufferManager)&&l<a&&r-o>i;return(p||c)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if((0,E.isNullable)(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",(0,E.flattenObject)(i)),i}parseManifest(e){try{return es(e??"",this.manifestUrlString)}catch(t){let i=Yr(e)??{id:"ManifestParsing",category:E.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,l)=>!!(this.element?.canPlayType?.(u)&&rt()?.isTypeSupported?.(`${u}; codecs="${l}"`)||o==="text"),r,a;for(let o of["video","audio"]){let l=e.streams[o].filter(({mime:c,codecs:d})=>i(o,c,d));t[o]=l;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:d})=>d);o==="audio"&&(a=rs(c),p=a[0]),o==="video"&&(r=is(c),this.forceVideoCodec&&(0,iy.default)(r,this.forceVideoCodec)?p=this.forceVideoCodec:p=r[0]),p&&(t[o]=l.filter(({codecs:d})=>Bi(d)===p))}else{let c=new Set(l.map(({codecs:d})=>d));p=ts(c),p&&(t[o]=l.filter(({codecs:d})=>d.startsWith(p)))}if(o==="video"){let c=this.tuning.preferHDR,d=t.video.some(m=>m.hdr),h=t.video.some(m=>!m.hdr);F.display.isHDR&&c&&d?t.video=t.video.filter(m=>m.hdr):h&&(t.video=t.video.filter(m=>!m.hdr))}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:a}),n}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){(0,E.assertNonNullable)(this.manifest),(0,E.assertNonNullable)(this.element);let a=l=>{this.representationSubscription.add((0,E.fromEvent)(l,"error").pipe((0,E.filter)(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=$r();let n=(0,E.getWindow)().document,o=n.createElement("source");if(a(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),xi())if(r){let l=n.createElement("source");a(l),l.type="application/x-mpegurl",l.src=r.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoNativeBufferManager=new Da(this.source),this.videoBufferManager=La.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,E.isNonNullable)(i)){this.audioNativeBufferManager=new Da(this.source);let l=this.manifest.streams.audio.reduce((p,c)=>[...p,...c.representations],[]);this.audioBufferManager=La.getBufferManager("audio",this.audioNativeBufferManager,l,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=>{e&&(this.timeoutSourceOpenId=(0,E.getWindow)().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&(0,E.getWindow)().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,E.merge)(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),(0,E.assertNonNullable)(this.videoBufferManager),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add((0,E.merge)(...ty.map(e=>(0,E.fromEvent)(this.element,e))).pipe((0,E.map)(e=>this.videoBufferManager?.getPlaybackBufferState()),(0,E.filter)(E.isNonNullable),(0,E.map)(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add((0,E.merge)(...ty.map(e=>(0,E.fromEvent)(this.element,e))).pipe((0,E.map)(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),(0,E.filterChanged)()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe((0,E.filter)(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=(0,E.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if((0,E.isNullable)(this.element)||(0,E.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};var be=require("@vkontakte/videoplayer-shared");var Eo=class extends Io{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){(0,be.assertNonNullable)(this.manifest),(0,be.assertNonNullable)(this.source);let e=[this.manifest.duration??0,...(0,Cc.default)((0,Cc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],t=>t.representations),t=>{let i=[];return t.duration&&i.push(t.duration),nt(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){(0,be.assertNonNullable)(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){(0,be.assertNonNullable)(this.element);let e=(0,be.merge)((0,be.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,be.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,be.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,be.merge)(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe((0,be.map)(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=(0,be.merge)(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe((0,be.map)(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=(0,be.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,be.filterChanged)(),(0,be.map)(({allBuffersFull:a,someBufferEnded:n})=>a&&n),(0,be.filter)(a=>a)),r=()=>{try{this.source?.endOfStream()}catch(a){this.error$.next({id:"EndOfStream",category:be.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:a})}};this.representationSubscription.add((0,be.merge)(this.forceEnded$,i).pipe((0,be.filter)(a=>(0,be.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var os=class extends ta{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,ry.filterChanged)()).subscribe(a=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:c}])=>c.id===a);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,l=this.params.desiredState.videoStream.getTransition();l&&l.to&&l.to.id===u.id&&this.params.desiredState.videoStream.setState(l.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(no(u));let p=this.player.calculateDurationFromSegments();p&&this.params.output.duration$.next(p/1e3)},r))}getPlayer(){return new Eo({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 H=require("@vkontakte/videoplayer-shared");var uy=q(We(),1),_c=q(nr(),1);var et=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};var I=require("@vkontakte/videoplayer-shared");var wo=q(We(),1),cr=q(dt(),1),xo=q(nr(),1);var ny=q(Kn(),1);var Oi=require("@vkontakte/videoplayer-shared");var xM=18,sy=!1;try{sy=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=xM}catch(s){console.error(s)}var Vc=class{constructor(e,t=!1){this.bufferFull$=new Oi.Subject;this.error$=new Oi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Oi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};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)};sy&&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(){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(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Oi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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,Oi.assertNever)(t)}}},ay=Vc;var us=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var R=require("@vkontakte/videoplayer-shared");var Ba=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new R.ValueSubject(0);this.currentLowLatencySegmentLength$=new R.ValueSubject(0);this.currentSegmentLength$=new R.ValueSubject(0);this.onLastSegment$=new R.ValueSubject(!1);this.fullyBuffered$=new R.ValueSubject(!1);this.playingRepresentation$=new R.ValueSubject(void 0);this.playingRepresentationInit$=new R.ValueSubject(void 0);this.error$=new R.Subject;this.gaps=[];this.subscription=new R.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;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,R.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,R.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 ay(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add((0,R.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,R.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!G(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,us(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"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,R.assertNonNullable)(i,"No init buffer for starting representation"),(0,R.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,R.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,R.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,R.isNullable)(a)||(0,R.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,R.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,R.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,R.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,R.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,R.isNullable)(a)||(0,R.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,R.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,R.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,R.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,xo.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!Et(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,R.assertNonNullable)(r,`Representation not found by id ${i}`);let a=this.segments.get(i);(0,R.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,R.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));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,(0,R.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,R.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,R.isNullable)(o)||(0,R.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,R.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,R.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,R.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 le,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,R.isNullable)(e)||(0,R.isNullable)(this.downloadingRepresentationId)||(0,R.isNullable)(this.playingRepresentationId)||(0,R.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,R.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,R.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,R.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,R.isNullable)(r)||(0,R.isNullable)(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);(0,R.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=Vi(i),m=Vi(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,R.isNonNullable)(h)&&(0,R.isNonNullable)(m)&&(0,R.isHigher)(h.quality,m.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||v?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let y=[...this.segments.entries()].map(([k,x])=>{let L=x.find(O=>e>=O.time.from&&e<O.time.to);return{representationId:k,status:L?.status}}).find(k=>k.status==="fed")?.representationId;y&&(this.playingRepresentationId=y,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&us(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let p=[];if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,wo.default)(p,n))d="high";else{let h=(0,cr.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,cr.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-c.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,R.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?.streams[this.kind];if(!t)return;let i=(0,xo.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,xo.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!Et(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,cr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,R.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,cr.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Et(r))return;let a=this.segments.get(i.id)??[],n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=It(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&$t&&$t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&$t&&$t(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}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:d,time:{from:h,to:m}},b)=>{let v=h<=i&&m>=i,S=h>i||v||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),k=this.preloadOnly&&h<=i+y||r<y&&m-h>=y||m<=i+y;return(d==="none"||d==="partially_ejected"&&S&&k&&this.sourceBuffer&&G(this.mediaSource,this.sourceBuffer)&&!(et(this.sourceBuffer.buffered,h)&&et(this.sourceBuffer.buffered,m)))&&S&&k});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){Et(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:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,R.abortable)(o,async function*(){let p=(0,R.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=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,R.now)(),!p)return;let c=new DataView(p),d=Mt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Ze(p)||(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())Et(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,R.abortable)(n,async function*(){let u=(0,R.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,R.fromEvent)(window,"online").pipe((0,R.once)()).subscribe(()=>{l(),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,R.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ze(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Et(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,cr.default)(e,0).byte.from,to:(0,cr.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,R.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Et(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,R.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,wo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!G(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 l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(!h)continue;let b=Mt(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===d?v:b.parseFeedableSegmentChunk(v);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!((0,R.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(et(this.sourceBuffer.buffered,e.segment.time.from,100)&&et(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:R.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",Lc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.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||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Zt(()=>(0,ny.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,R.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,R.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:l,dataView:p,segments:c}=u,d=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Et(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,u=>{a||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:R.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||!G(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,R.isNullable)(e))return!1;let r=[],a=0,n=u=>{u.sort((p,c)=>p.from-c.from);let l=[u[0]];for(let p=1;p<u.length;p++){let{from:c,to:d}=u[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(u[p])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=n(r);let l=Lc(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,p=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let d of this.segments.values())for(let h of d)(0,wo.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};o(d)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+u&&p.status==="fed"&&o(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!G(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||!G(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||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,R.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!G(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||!G(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=Zt(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:R.ErrorCategory.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,R.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,R.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(p=>p.from-t<=n&&p.to+t>=o),l=e.filter(p=>n>=p.from&&n<p.to-t||o>p.from+t&&o<=p.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:R.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var K=require("@vkontakte/videoplayer-shared");var Po=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new K.Subject;this.firstBytesManifest$=new K.Subject;this.firstBytesRequested$=new K.Subject;this.firstBytesReceived$=new K.Subject;this.lastConnectionType$=new K.ValueSubject(void 0);this.lastConnectionReused$=new K.ValueSubject(void 0);this.lastRequestFirstBytes$=new K.ValueSubject(void 0);this.recoverableError$=new K.Subject;this.error$=new K.Subject;this.abortAllController=new le;this.subscription=new K.SubscriptionRemovable;this.fetchManifest=(0,K.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=jt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Xr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ko);return r?(t.log("success",(0,K.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",(0,K.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,K.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:l=!1,ignoreNetworkErrors:p=!1}={}){let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let P=new URL(c,location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),c=P.toString();break}default:(0,K.assertNever)(t)}this.requestQuic&&(c=jt(c));let m=this.abortAllController.signal,b;if(n){let P=new le;if(b=(0,K.merge)((0,K.fromEvent)(this.abortAllController.signal,"abort"),(0,K.fromEvent)(n,"abort")).subscribe(()=>{try{P.abort()}catch(re){ko(re)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(re){ko(re)}m=P.signal}let v=0,S=(0,K.now)();h.log("startRequest",(0,K.flattenObject)({url:c,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested$.next();let y=yield this.doFetch(c,{priority:a,headers:d,signal:m},{ignoreNetworkErrors:p}),k=(0,K.now)();if(!y)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(b),null;if(this.throughputEstimator?.addRawRtt(k-S),!y.ok||!y.body){this.unsubscribeAbortSubscription(b);let P=`Fetch error ${y.status}: ${y.statusText}`;return h.error("error",{message:P}),h.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){this.unsubscribeAbortSubscription(b);let P=(0,K.now)(),re={requestStartedAt:S,requestEndedAt:P,duration:P-S};return h.log("endRequest",(0,K.flattenObject)(re)),h.end(),y.arrayBuffer()}let x=y.body;if(o){let P;[x,P]=y.body.tee(),this.throughputEstimator?.trackStream(P,u)}let L=x.getReader(),O,N=parseInt(y.headers.get("content-length")??"",10);Number.isFinite(N)&&(O=N),!O&&i&&(O=i.to-i.from+1);let M=O?new Uint8Array(O):new Uint8Array(0),j=!1,D=P=>{this.unsubscribeAbortSubscription(b),j=!0,ko(P)},se=(0,K.abortable)(m,async function*({done:P,value:re}){if(v===0&&(this.lastRequestFirstBytes$.next((0,K.now)()-S),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(b);return}if(!P&&re){if(l&&O)M.set(re,v),v+=re.byteLength;else{let U=new Uint8Array(M.length+re.length);U.set(M),U.set(re,M.length),M=U,v+=re.byteLength}r?.(new DataView(M.buffer),v),yield L?.read().then(se,D)}}.bind(this));yield L?.read().then(se,D),this.unsubscribeAbortSubscription(b);let z=(0,K.now)(),A={failed:j,requestStartedAt:S,requestEndedAt:z,duration:z-S};return j?(h.error("endRequest",(0,K.flattenObject)(A)),h.end(),null):(h.log("endRequest",(0,K.flattenObject)(A)),h.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,K.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let v=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,K.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}onHeadersReceived(e){let{type:t,reused:i}=Kr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,K.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await ft(e,t);if(r.ok)return r;if(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:K.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:K.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:K.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:K.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:K.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ko=s=>{if(!Ze(s))throw s};var Ca=require("@vkontakte/videoplayer-shared"),Ni=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ca.ValueSubject(e.initial),this.debounced$=new Ca.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new st(`raw_${t}`),this.smoothedSeries$=new st(`smoothed_${t}`),this.reportedSeries$=new st(`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,Ca.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 Ao=class extends Ni{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ui(this.slow,e,this.params.emaAlphaSlow),this.fast=ui(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ro=class extends Ni{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=lc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ui(this.emaSmoothed,e,this.params.emaAlpha);let i=Jg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var $o=class extends Ni{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?ui(this.smoothed,t,this.params.emaAlpha):t}};var hi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ao({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ro({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 $o({initial:e,label:"liveEdgeDelay",...t})}};var ls=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var Mo=require("@vkontakte/videoplayer-shared");var Va=class s{constructor(e,t){this.currentRepresentation$=new Mo.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?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,Mo.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of 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?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Et(t.segmentReference))}};var PM=["timeupdate","progress","play","seeked","stalled","waiting"],AM=["timeupdate","progress","loadeddata","playing","seeked"];var Lo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new I.Subscription;this.subscriptionRemovable=new I.SubscriptionRemovable;this.representationSubscription=new I.Subscription;this.state$=new te("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.firstBytesManifest$=new I.Subject;this.manifestReceived$=new I.Subject;this.firstBytesRequested$=new I.Subject;this.firstBytesReceived$=new I.Subject;this.lastConnectionType$=new I.ValueSubject(void 0);this.lastConnectionReused$=new I.ValueSubject(void 0);this.lastRequestFirstBytes$=new I.ValueSubject(void 0);this.currentLiveTextRepresentation$=new I.ValueSubject(null);this.isLive$=new I.ValueSubject(!1);this.isActiveLive$=new I.ValueSubject(!1);this.isLowLatency$=new I.ValueSubject(!1);this.liveDuration$=new I.ValueSubject(0);this.liveSeekableDuration$=new I.ValueSubject(0);this.liveAvailabilityStartTime$=new I.ValueSubject(0);this.liveStreamStatus$=new I.ValueSubject(void 0);this.bufferLength$=new I.ValueSubject(0);this.liveLatency$=new I.ValueSubject(void 0);this.liveLoadBufferLength$=new I.ValueSubject(0);this.livePositionFromPlayer$=new I.ValueSubject(0);this.currentStallDuration$=new I.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new I.ValueSubject(0);this.fetcherRecoverableError$=new I.Subject;this.fetcherError$=new I.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new I.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new le;this.initManifest=(0,I.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ae(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:I.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,I.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=es(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Yr(e)??{id:"ManifestParsing",category:I.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&rt()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";if(c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),c&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let m=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(m).catch(b=>{this.error$.next({id:"updateManifest",category:I.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:b})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=rs(d),c=n[0]),u==="video"&&(a=is(d),this.forceVideoCodec&&(0,uy.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>Bi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=ts(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);F.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",(0,I.flattenObject)(o)),o}.bind(this));this.initRepresentations=(0,I.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,I.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,I.assertNonNullable)(this.manifest),(0,I.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add((0,I.fromEvent)(c,"error").pipe((0,I.filter)(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=$r();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),xi())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}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((c,d)=>[...c,...d.representations],[]);if(this.videoBufferManager=new Ba("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,I.isNonNullable)(t)){let c=this.manifest.streams.audio.reduce((d,h)=>[...d,...h.representations],[]);this.audioBufferManager=new Ba("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(Va.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Va(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,I.merge)(...AM.map(c=>(0,I.fromEvent)(this.element,c))).pipe((0,I.map)(c=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),(0,I.filterChanged)(),(0,I.tap)(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,I.merge)((0,I.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,I.filterChanged)()).subscribe(d=>this.liveStreamEndTimestamp=(0,I.now)())),this.subscription.add((0,I.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:d}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,I.interval)(d).subscribe(h=>{let m=Ii(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,m+d,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,I.fromEvent)(this.element,"play").subscribe(d=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,I.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.map)(({isActiveLive:d,isLowLatency:h})=>d&&h),(0,I.filterChanged)()).subscribe(d=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add((0,I.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.filter)(({bufferLength:d,isActiveLive:h,isLowLatency:m})=>h&&m&&!!d)).subscribe(({bufferLength:d})=>this.liveBuffer.next(d))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(d=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!d)return;let h=this.liveSeekableDuration$.getValue()-d/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+d/1e3)})),this.representationSubscription.add((0,I.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,I.filter)(({isLive:d})=>d),(0,I.filterChanged)((d,h)=>h.bufferLength<d.bufferLength),(0,I.map)(({rtt:d,bufferLength:h,segmentServerLatency:m})=>{let b=Ii(this.manifestUrlString,2);return(d/2+h+m+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,I.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:d,isActiveLive:h,isLowLatency:m})=>{if(!m||!h)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=d-b;if(this.isManualDecreasePlaybackInLive())return;let k=1;Math.abs(y)>v&&(k=1+Math.sign(y)*S),ls(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{let h=0;if(d){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add((0,I.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,I.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:d,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,b=Ii(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,x=isFinite(d)?d:h,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let N="none";if(L?N="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(M=>M.proceedLowLatencyLive()),N="active_low_latency"):b!==0&&x<S?N="live_forward_buffering":x<S+k&&(N="live_with_target_offset"),isFinite(d)&&(c=d>c?d:c),N==="live_forward_buffering"||N==="live_with_target_offset"){let M=c-(S+y),j=this.normalizeLiveOffset(Math.trunc(b+M/m)),D=Math.abs(j-b),se=0;!d||D<=this.tuning.dashCmafLive.offsetCalculationError?se=b:j>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(se=j),this.manifestUrlString=Ae(this.manifestUrlString,se,2)}(N==="live_with_target_offset"||N==="live_forward_buffering")&&(c=0,await this.updateLive())},d=>{this.error$.next({id:"updateLive",category:I.ErrorCategory.VIDEO_PIPELINE,thrown:d,message:"Failed to update live with subscription"})}))}let u=(0,I.merge)(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe((0,I.map)(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=(0,I.merge)(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe((0,I.map)(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=(0,I.combine)({allBuffersFull:u,someBufferEnded:l}).pipe((0,I.filterChanged)(),(0,I.map)(({allBuffersFull:c,someBufferEnded:d})=>c&&d),(0,I.filter)(c=>c));if(this.representationSubscription.add((0,I.merge)(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add((0,I.merge)(...this.bufferManagers.map(c=>c.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 c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(d=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){d();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)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),d()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,_c.default)((0,_c.default)([...this.manifest.streams.audio,...this.manifest.streams.video],d=>d.representations),d=>{let h=[];return d.duration&&h.push(d.duration),Et(d.segmentReference)&&d.segmentReference.totalSegmentsDurationMs&&h.push(d.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&(0,I.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,I.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:I.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),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 Po({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.liveBuffer=hi.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,I.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,I.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ae(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,I.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,I.merge)(...PM.map(e=>(0,I.fromEvent)(this.element,e)),(0,I.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,I.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,I.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&et(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let p=this.currentStallDuration$.getValue();p+=n,this.currentStallDuration$.next(p);let c={timeInWaiting:p},d=(0,I.now)(),h=100,m=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(m);let b=this.audioBufferManager?.lastDataObtainedTimestamp??0,v=this.videoBufferManager?.getForwardBufferDuration()??0,S=this.audioBufferManager?.getForwardBufferDuration()??0,y=v<h&&d-m>r,k=this.audioBufferManager&&S<h&&d-b>r;if((!t||l)&&((y||k)&&p>r||p>=i))throw new Error(`Stall timeout exceeded: ${p} ms`);if(o&&p%a===0){let x=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(x),this.updateManifest()):this.seekLive(x).catch(L=>{this.error$.next({id:"stallIntervalCallback",category:I.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:L})}),c.liveLastOffset=x}else{let x=this.element.currentTime*1e3;this.videoBufferManager?.maintain(x),this.audioBufferManager?.maintain(x),c.position=x}this.tracer.log("stallIntervalCallback",(0,I.flattenObject)(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,I.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:I.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?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),et(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,I.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,I.isNonNullable)(this.element)&&(0,I.isNonNullable)(this.source)&&(0,I.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,I.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.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 l of u.gaps)(r&&l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.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,I.flattenObject)(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var mt=require("@vkontakte/videoplayer-shared"),Do=class{constructor(){this.subscription=new mt.Subscription;this.pipSize$=new mt.ValueSubject(void 0);this.videoSize$=new mt.ValueSubject(void 0);this.elementSize$=new mt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=mt.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,mt.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,mt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,mt.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 dr=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new te("stopped");this.observableVideo=null;this.droppedFramesManager=new Ri;this.stallsManager=new Wr;this.elementSizeManager=new Do;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new qt;this.audioTrackSwitchHistory=new qt;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?.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?.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?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,H.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Mi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 ct(e.source.url),this.params=e,this.video=Ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(De(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Lo({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,H.isNullable)(this.observableVideo)&&(this.observableVideo=Xe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:H.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,H.filter)(c=>!!c.length),(0,H.once)()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,H.map)(c=>c.to.state!=="none"),(0,H.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.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,H.filter)(H.isNonNullable),(0,H.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,H.map)(c=>c.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(At(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Di({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(lt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(pt(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:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if((0,H.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let v of d.audio){b.push($c(v));let S=[];for(let y of v.representations){let k=Ma(y);S.push(k),this.audioTracksMap.set(k,{stream:v,representation:y})}this.audioStreamsMap.set(v,S)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of d.video){m.push(Mc(b));let v=[];for(let S of b.representations){let y=Vi({...S,streamId:b.id});y&&(v.push(y),this.videoTracksMap.set(y,{stream:b,representation:S}))}this.videoStreamsMap.set(b,v)}this.params.output.availableVideoStreams$.next(m);for(let b of d.text)for(let v of b.representations){let S=Yv(b,v);this.textTracksMap.set(S,{stream:b,representation:v})}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?.video&&this.params.output.availableVideoCodecs$.next(h.video),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 c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,H.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,H.fromEvent)(this.video,"progress")).pipe((0,H.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,H.throttle)(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,v=[...this.videoTracksMap.keys()].find(y=>this.videoTracksMap.get(y)?.representation.id===m.id);(0,H.isNonNullable)(v)&&(this.stallsManager.lastVideoTrackSelected=v);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")await this.player.initRepresentations(m.id,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,H.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,H.merge)((0,H.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,H.map)(c=>c.to)))}).pipe((0,H.map)(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),(0,H.filterChanged)()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,H.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,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(Mc(m));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,H.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next($c(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,H.map)(({to:c})=>c==="ready"),(0,H.filterChanged)());this.subscription.add((0,H.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,H.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,H.merge)(l,this.player.state$.stateChangeEnded$,(0,H.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=(0,H.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ar:sr,t=this.params.tuning.useNewAutoSelectVideoTrack?Hr:jr,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:qr,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:M})=>M===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:M})=>M===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=Be(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,v=Math.min(h/Math.min(m,b||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),y=[...this.audioStreamsMap.keys()].find(({id:M})=>M===S?.id)??this.audioStreamsMap.keys().next().value,k=0;if(y){if(u&&!n){let M=e(u,d,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);k=Math.max(k,M?.bitrate??-1/0)}if(l){let M=e(l,d,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);k=Math.max(k,M?.bitrate??-1/0)}}let x=u;(n||!x)&&(x=i(d,{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:k,forwardBufferHealth:v,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let L=y&&t(x,d,this.audioStreamsMap.get(y)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),O=this.videoTracksMap.get(x)?.representation,N=L&&this.audioTracksMap.get(L)?.representation;if(O&&N)return[O,N];if(O&&!N&&this.audioTracksMap.size===0)return[O,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ye(this.video),this.tracer.end()}};var _a=class extends dr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Se=require("@vkontakte/videoplayer-shared");var Oa=class extends dr{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 Se.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,Se.filterChanged)()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!u&&!l&&c?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,Se.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,Se.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Se.map)(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u*1e3+l+t:void 0)).subscribe(i.liveTime$)).add((0,Se.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,Se.merge)(r.playbackRateState$,new Se.ValueSubject(1))}).pipe((0,Se.filter)(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||(0,Se.isNullable)(p)||(t=u-p)})).add((0,Se.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,Se.merge)(r.playbackRateState$,new Se.ValueSubject(1))}).pipe((0,Se.filterChanged)((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||(0,Se.isNullable)(u)||(0,Se.isNullable)(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=Kv(u);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,Se.filter)(u=>(0,Se.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Q=require("@vkontakte/videoplayer-shared");var Sy=q(We(),1),Hc=q(nr(),1);var T=require("@vkontakte/videoplayer-shared");var Oo=q(We(),1),hr=q(dt(),1),No=q(nr(),1);var by=q(Kn(),1);var Fi=require("@vkontakte/videoplayer-shared");var $M=18,ly=!1;try{ly=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=$M}catch(s){console.error(s)}var Oc=class{constructor(e,t=!1){this.bufferFull$=new Fi.Subject;this.error$=new Fi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Fi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};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)};ly&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){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(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Fi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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,Fi.assertNever)(t)}}},cy=Oc;var $=require("@vkontakte/videoplayer-shared");var Nc=q(dt(),1);var Bo=require("@vkontakte/videoplayer-shared"),Na=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Xt(a):void 0)??(0,Bo.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},dy=({id:s,bitrate:e})=>({id:s,bitrate:e}),py=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),hy=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Fc=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Nc.default)(i.split("."),0),isDefault:r}),Uc=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Nc.default)(r.split("."),0)}),qc=s=>"url"in s,wt=s=>s.type==="template";var fy=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},pr=(s,e)=>{for(let t of s)if(e(t))return t;return null},my=s=>{let e=!1,t=(0,Bo.throttleFn)(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var _o=require("@vkontakte/videoplayer-shared");var Co=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var Vo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new _o.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,_o.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!G(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Co(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Fa=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new $.ValueSubject(0);this.currentLowLatencySegmentLength$=new $.ValueSubject(0);this.currentSegmentLength$=new $.ValueSubject(0);this.onLastSegment$=new $.ValueSubject(!1);this.fullyBuffered$=new $.ValueSubject(!1);this.playingRepresentation$=new $.ValueSubject(void 0);this.playingRepresentationInit$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.gaps=[];this.subscription=new $.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;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.sourceBufferBufferedDiff=null;this.startWith=(0,$.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,$.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new cy(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.sourceBufferBufferedDiff=new Vo(this.mediaSource,this.sourceBuffer),this.subscription.add((0,$.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,$.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:$.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!G(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,us(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Be(this.sourceBuffer.buffered,o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"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,$.assertNonNullable)(i,"No init buffer for starting representation"),(0,$.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,$.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,$.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,$.isNullable)(a)||(0,$.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,$.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,$.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,$.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,$.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,$.isNullable)(a)||(0,$.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,$.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,$.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,$.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,No.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!wt(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,$.assertNonNullable)(r,`Representation not found by id ${i}`);let a=this.segments.get(i);(0,$.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,$.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));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,(0,$.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,$.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,$.isNullable)(o)||(0,$.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,$.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,$.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,$.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 le,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,$.isNullable)(e)||(0,$.isNullable)(this.downloadingRepresentationId)||(0,$.isNullable)(this.playingRepresentationId)||(0,$.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,$.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,$.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,$.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,$.isNullable)(r)||(0,$.isNullable)(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);(0,$.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=Na(i),m=Na(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,$.isNonNullable)(h)&&(0,$.isNonNullable)(m)&&(0,$.isHigher)(h.quality,m.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||v?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let y=[...this.segments.entries()].map(([k,x])=>{let L=x.find(O=>e>=O.time.from&&e<O.time.to);return{representationId:k,status:L?.status}}).find(k=>k.status==="fed")?.representationId;y&&(this.playingRepresentationId=y,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&us(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Be(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Oo.default)(p,n))d="high";else{let h=(0,hr.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&Be(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,hr.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-Be(this.sourceBuffer.buffered,e)<u),this.onLastSegment$.next(e-c.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,$.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?.streams[this.kind];if(!t)return;let i=(0,No.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,No.default)(e.streams[this.kind],i=>i.representations)??[];for(let i of t){if(!i||!wt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,hr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,$.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!wt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=It(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&$t&&$t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&$t&&$t(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:m}},b)=>{let v=h<=i&&m>=i,S=h>i||v||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),k=this.preloadOnly&&h<=i+y||r<y&&m-h>=y||m<=i+y;return(d==="none"||d==="partially_ejected"&&S&&k&&this.sourceBuffer&&G(this.mediaSource,this.sourceBuffer)&&!(et(this.sourceBuffer.buffered,h)&&et(this.sourceBuffer.buffered,m)))&&S&&k});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){wt(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:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,$.abortable)(o,async function*(){let p=(0,$.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=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,$.now)(),!p)return;let c=new DataView(p),d=Mt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Ze(p)||(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())wt(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,$.abortable)(n,async function*(){let u=(0,$.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,$.fromEvent)(window,"online").pipe((0,$.once)()).subscribe(()=>{l(),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,$.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ze(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(wt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,hr.default)(e,0).byte.from,to:(0,hr.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,$.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:$.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!wt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,$.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:$.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Oo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!G(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 l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===d?b:Mt(o.mime).parseFeedableSegmentChunk(b);v?.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,$.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(et(this.sourceBuffer.buffered,e.segment.time.from,100)&&et(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:$.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",qc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Zt(()=>(0,by.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,$.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,$.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&wt(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:$.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}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||!G(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,$.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{if(a>=t)return;r.push({...o.time});let u=qc(o)?o.size??0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let c of this.segments.values())for(let d of c)(0,Oo.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(u)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=fy(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!G(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||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,$.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let a=Math.round(r.from),n=Math.round(r.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Zt(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:$.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,$.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,$.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Co(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];u||(u=c-t<=n&&d+t>=o),(n>=c&&n<d-t||o>c+t&&o<=d)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:$.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,hr.default)(e,-1)?.time.to:0)||0}};var X=require("@vkontakte/videoplayer-shared");var Uo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new X.Subject;this.firstBytesManifest$=new X.Subject;this.firstBytesRequested$=new X.Subject;this.firstBytesReceived$=new X.Subject;this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.recoverableError$=new X.Subject;this.error$=new X.Subject;this.abortAllController=new le;this.subscription=new X.SubscriptionRemovable;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=jt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Xr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Fo);return r?(t.log("success",(0,X.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",(0,X.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,X.abortable)(this.abortAllController.signal,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:l=!1}={}){let p=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let A=new URL(p,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),p=A.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(p=jt(p));let h=this.abortAllController.signal,m;if(n){let A=new le;if(m=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{A.abort()}catch(P){Fo(P)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(P){Fo(P)}h=A.signal}let b=0,v=(0,X.now)();d.log("startRequest",(0,X.flattenObject)({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.firstBytesRequested$.next();let S=yield this.doFetch(p,{priority:a,headers:c,signal:h}),y=(0,X.now)();if(!S)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(y-v),!S.ok||!S.body){this.unsubscribeAbortSubscription(m);let A=`Fetch error ${S.status}: ${S.statusText}`;return d.error("error",{message:A}),d.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!o){this.unsubscribeAbortSubscription(m);let A=(0,X.now)(),P={requestStartedAt:v,requestEndedAt:A,duration:A-v};return d.log("endRequest",(0,X.flattenObject)(P)),d.end(),S.arrayBuffer()}let k=S.body;if(o){let A;[k,A]=S.body.tee(),this.throughputEstimator?.trackStream(A,u)}let x=k.getReader(),L,O=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(O)&&(L=O),!L&&i&&(L=i.to-i.from+1);let N=L?new Uint8Array(L):new Uint8Array(0),M=!1,j=A=>{this.unsubscribeAbortSubscription(m),M=!0,Fo(A)},D=(0,X.abortable)(h,async function*({done:A,value:P}){if(b===0&&(this.lastRequestFirstBytes$.next((0,X.now)()-v),this.firstBytesReceived$.next()),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!A&&P){if(l&&L)N.set(P,b),b+=P.byteLength;else{let re=new Uint8Array(N.length+P.length);re.set(N),re.set(P,N.length),N=re,b+=P.byteLength}r?.(new DataView(N.buffer),b),yield x?.read().then(D,j)}}.bind(this));yield x?.read().then(D,j),this.unsubscribeAbortSubscription(m);let se=(0,X.now)(),z={failed:M,requestStartedAt:v,requestEndedAt:se,duration:se-v};return M?(d.error("endRequest",(0,X.flattenObject)(z)),d.end(),null):(d.log("endRequest",(0,X.flattenObject)(z)),d.end(),N.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let v=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,X.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,{priority:t,measureThroughput:!1});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}onHeadersReceived(e){let{type:t,reused:i}=Kr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,X.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await ft(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:X.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:X.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:X.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:X.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:X.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Fo=s=>{if(!Ze(s))throw s};var qo=require("@vkontakte/videoplayer-shared");var Ua=class s{constructor(e,t){this.currentRepresentation$=new qo.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,qo.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of 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?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&wt(t.segmentReference))}};var DM=["progress","play","seeked","stalled","waiting"],BM=["timeupdate","progress","loadeddata","playing","seeked"];var jo=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 te("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.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ae(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.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*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=es(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Yr(e)??{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&rt()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=rs(d),c=n[0]),u==="video"&&(a=is(d),this.forceVideoCodec&&(0,Sy.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>Bi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=ts(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);F.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}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){this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new T.Subscription,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add((0,T.fromEvent)(d,"error").pipe((0,T.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=$r();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),xi())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}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((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new Fa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Fa("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}Ua.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ua(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,T.merge)(...BM.map(d=>(0,T.fromEvent)(this.element,d))).pipe((0,T.map)(d=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,T.interval)(1e3).subscribe(h=>{let m=Ii(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.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()||ls(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 v=Ii(this.manifestUrlString,2);return(h/2+m+b+v)/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 v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,k=h-v;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(k)>S&&(x=1+Math.sign(k)*y),ls(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let b=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,v=Ii(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),k=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,L=isFinite(h)?h:m,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),N=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(N);let M="none";if(O?M="active_low_latency":this.isLowLatency$.getValue()&&N?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),M="active_low_latency"):v!==0&&L<y?M="live_forward_buffering":L<y+x&&(M="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),M==="live_forward_buffering"||M==="live_with_target_offset"){let j=d-(y+k),D=this.normolizeLiveOffset(Math.trunc(v+j/b)),se=Math.abs(D-v),z=0;!h||se<=this.tuning.dashCmafLive.offsetCalculationError?z=v:D>0&&se>this.tuning.dashCmafLive.offsetCalculationError&&(z=D),this.manifestUrlString=Ae(this.manifestUrlString,z,2)}(M==="live_with_target_offset"||M==="live_forward_buffering")&&(d=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 l=(0,T.merge)(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=(0,T.merge)(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=(0,T.combine)({allBuffersFull:l,someBufferEnded:p}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:d,someBufferEnded:h})=>d&&h),(0,T.filter)(d=>d));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(d=>d.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 d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.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)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Hc.default)((0,Hc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),wt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),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 Uo({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.liveBuffer=hi.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);let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ae(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,T.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,T.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,T.merge)(...DM.map(t=>(0,T.fromEvent)(this.element,t)),(0,T.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&et(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=(0,T.now)(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),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?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),et(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",(0,T.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var bt=require("@vkontakte/videoplayer-shared"),Ho=class{constructor(){this.subscription=new bt.Subscription;this.pipSize$=new bt.ValueSubject(void 0);this.videoSize$=new bt.ValueSubject(void 0);this.elementSize$=new bt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=bt.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,bt.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,bt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,bt.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 fr=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new te("stopped");this.observableVideo=null;this.droppedFramesManager=new Ri;this.stallsManager=new Wr;this.elementSizeManager=new Ho;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new qt;this.audioTrackSwitchHistory=new qt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.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?.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?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,Q.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Mi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 ct(e.source.url),this.params=e,this.video=Ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(De(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new jo({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,Q.isNullable)(this.observableVideo)&&(this.observableVideo=Xe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Q.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,Q.filter)(c=>!!c.length),(0,Q.once)()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,Q.map)(c=>c.to.state!=="none"),(0,Q.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.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,Q.filter)(Q.isNonNullable),(0,Q.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,Q.map)(c=>c.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(At(this.video,t.isLooped,r)),this.subscription.add(Ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(lt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(pt(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:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if((0,Q.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let v of d.audio){b.push(Fc(v));let S=[];for(let y of v.representations){let k=dy(y);S.push(k),this.audioTracksMap.set(k,{stream:v,representation:y})}this.audioStreamsMap.set(v,S)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of d.video){m.push(Uc(b));let v=[];for(let S of b.representations){let y=Na({...S,streamId:b.id});y&&(v.push(y),this.videoTracksMap.set(y,{stream:b,representation:S}))}this.videoStreamsMap.set(b,v)}this.params.output.availableVideoStreams$.next(m);for(let b of d.text)for(let v of b.representations){let S=py(b,v);this.textTracksMap.set(S,{stream:b,representation:v})}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?.video&&this.params.output.availableVideoCodecs$.next(h.video),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 c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&my(o)||null;this.subscription.add((0,Q.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,Q.fromEvent)(this.video,"progress")).pipe((0,Q.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let b=pr(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===h.id);(0,Q.isNonNullable)(b)&&(this.stallsManager.lastVideoTrackSelected=b);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,S)}},r)),this.subscription.add((0,Q.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,Q.merge)((0,Q.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,Q.map)(c=>c.to)))}).pipe((0,Q.map)(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),(0,Q.filterChanged)()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,Q.filterChanged)()).subscribe(c=>{let d=pr(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,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(Uc(m));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,Q.filterChanged)()).subscribe(c=>{let d=pr(this.audioTracksMap.entries(),([,{representation:v}])=>v.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Fc(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,Q.map)(({to:c})=>c==="ready"),(0,Q.filterChanged)());this.subscription.add((0,Q.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,Q.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,Q.merge)(l,this.player.state$.stateChangeEnded$,(0,Q.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=(0,Q.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ar:sr,t=this.params.tuning.useNewAutoSelectVideoTrack?Hr:jr,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:qr,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=pr(this.videoTracksMap.keys(),M=>M.id===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=pr(this.videoStreamsMap.keys(),M=>M.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=Be(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,v=Math.min(h/Math.min(m,b||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),y=S?.id&&pr(this.audioStreamsMap.keys(),M=>M.id===S.id)||this.audioStreamsMap.keys().next().value,k=0;if(y){if(u&&!n){let M=e(u,d,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);k=Math.max(k,M?.bitrate??-1/0)}if(l){let M=e(l,d,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);k=Math.max(k,M?.bitrate??-1/0)}}let x=u;(n||!x)&&(x=i(d,{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:k,forwardBufferHealth:v,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let L=y&&t(x,d,this.audioStreamsMap.get(y)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),O=this.videoTracksMap.get(x)?.representation,N=L&&this.audioTracksMap.get(L)?.representation;O&&N?(this.selectedRepresentations.video=O,this.selectedRepresentations.audio=N):O&&!N&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=O,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Q.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ye(this.video),this.tracer.end()}};var qa=class extends fr{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 ve=require("@vkontakte/videoplayer-shared");var ja=class extends fr{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 ve.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,ve.filterChanged)()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!u&&!l&&c?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,ve.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,ve.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ve.map)(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,ve.filter)(u=>(0,ve.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add((0,ve.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ve.merge)(r.playbackRateState$,new ve.ValueSubject(1))}).pipe((0,ve.filter)(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||(0,ve.isNullable)(p)||(t=u-p)})).add((0,ve.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ve.merge)(r.playbackRateState$,new ve.ValueSubject(1))}).pipe((0,ve.filterChanged)((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||(0,ve.isNullable)(u)||(0,ve.isNullable)(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=hy(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var vy="X-Playback-Duration",zc=async s=>{let e=await ft(s),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(vy)?parseInt(e.headers.get(vy),10):void 0};var ue=require("@vkontakte/videoplayer-shared");var Qc=q(nl(),1);var zo=require("@vkontakte/videoplayer-shared");var VM=s=>{let e=null;if(s.QUALITY&&(e=Xt(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,zo.videoSizeToQuality)({width:t,height:i})}return e??null},_M=(s,e)=>{let t=s.split(`
178
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var Mv=s=>{if(!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?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},It=(s,e)=>{let t=s;t=(0,xc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Lv.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,xc.default)(t,n,(o,u)=>(0,sa.isNullable)(a)?o:(0,sa.isNullable)(u)?a:(0,Dv.default)(a,parseInt(u,10),"0"))}return t},es=(s,e)=>{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(j=>j.textContent?.trim()??""),o=(0,Bv.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),p=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let S,y=a.getAttribute("mediaPresentationDuration"),k=[...a.getElementsByTagName("Period")],x=k.reduce((j,D)=>({...j,[D.id]:D.children}),{}),L=k.reduce((j,D)=>({...j,[D.id]:D.getAttribute("duration")}),{});y?S=Mv(y):(0,kc.default)(L).filter(j=>j).length&&!u?S=(0,kc.default)(L).reduce((j,D)=>j+(Mv(D)??0),0):b&&(S=parseInt(b,10));let O=0,N=a.getAttribute("profiles")?.split(",")??[];for(let j of k.map(D=>D.id))for(let D of x[j]){let se=D.getAttribute("id")??"id"+(O++).toString(10),z=D.getAttribute("mimeType")??"",A=D.getAttribute("codecs")??"",P=D.getAttribute("contentType")??z?.split("/")[0],re=D.getAttribute("profiles")?.split(",")??[],U=$v(D.getAttribute("lang")??"")??{},ce=D.querySelector("Label")?.textContent?.trim()??void 0,ge=D.querySelectorAll("Representation"),xe=D.querySelector("SegmentTemplate"),Le=D.querySelector("Role")?.getAttribute("value")??void 0,qe=P,je={id:se,language:U.language,isDefault:Le==="main",label:ce,codecs:A,hdr:qe==="video"&&wc(A),mime:z,representations:[]};for(let pe of ge){let oe=pe.getAttribute("lang")??void 0,He=ce??D.getAttribute("label")??pe.getAttribute("label")??void 0,tt=pe.querySelector("BaseURL")?.textContent?.trim()??"",Ce=new URL(tt||o,e).toString(),kt=pe.getAttribute("mimeType")??z,bi=pe.getAttribute("codecs")??A??"",Dt;if(P==="text"){let gt=pe.getAttribute("id")||"",gi=U.privateuse?.includes("x-auto")||gt.includes("_auto"),Bt=pe.querySelector("SegmentTemplate");if(Bt){let hs={representationId:pe.getAttribute("id")??void 0,bandwidth:pe.getAttribute("bandwidth")??void 0},Ka=parseInt(pe.getAttribute("bandwidth")??"",10)/1e3,Xa=parseInt(Bt.getAttribute("startNumber")??"",10)??1,br=parseInt(Bt.getAttribute("timescale")??"",10),Ko=Bt.querySelectorAll("SegmentTimeline S")??[],gr=Bt.getAttribute("media");if(!gr)continue;let Ja=[],Za=0,en="",Sr=0,fs=Xa,it=0;for(let Ct of Ko){let Ui=parseInt(Ct.getAttribute("d")??"",10),Pt=parseInt(Ct.getAttribute("r")??"",10)||0,Si=parseInt(Ct.getAttribute("t")??"",10);it=Number.isFinite(Si)?Si:it;let qi=Ui/br*1e3,vr=it/br*1e3;for(let zt=0;zt<Pt+1;zt++){let vi=It(gr,{...hs,segmentNumber:fs.toString(10),segmentTime:(it+zt*Ui).toString(10)}),yr=(vr??0)+zt*qi,bs=yr+qi;fs++,Ja.push({time:{from:yr,to:bs},url:vi})}it+=(Pt+1)*Ui,Za+=(Pt+1)*qi}Sr=it/br*1e3,en=It(gr,{...hs,segmentNumber:fs.toString(10),segmentTime:it.toString(10)});let ms={time:{from:Sr,to:1/0},url:en},ii={type:"template",baseUrl:Ce,segmentTemplateUrl:gr,initUrl:"",totalSegmentsDurationMs:Za,segments:Ja,nextSegmentBeyondManifest:ms,timescale:br};Dt={id:gt,kind:"text",segmentReference:ii,profiles:[],duration:S,bitrate:Ka,mime:"",codecs:"",width:0,height:0,isAuto:gi}}else Dt={id:gt,isAuto:gi,kind:"text",url:Ce}}else{let gt=pe.getAttribute("contentType")??kt?.split("/")[0]??P,gi=D.getAttribute("profiles")?.split(",")??[],Bt=parseInt(pe.getAttribute("width")??"",10),hs=parseInt(pe.getAttribute("height")??"",10),Ka=parseInt(pe.getAttribute("bandwidth")??"",10)/1e3,Xa=pe.getAttribute("frameRate")??"",br=pe.getAttribute("quality")??void 0,Ko=Xa?Rv(Xa):void 0,gr=pe.getAttribute("id")??"id"+(O++).toString(10),Ja=gt==="video"?`${hs}p`:gt==="audio"?`${Ka}Kbps`:bi,Za=`${gr}@${Ja}`,en=[...N,...re,...gi],Sr,fs=pe.querySelector("SegmentBase"),it=pe.querySelector("SegmentTemplate")??xe;if(fs){let ii=pe.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ct,Ui]=ii.split("-").map(vi=>parseInt(vi,10)),Pt={from:Ct,to:Ui},Si=pe.querySelector("SegmentBase")?.getAttribute("indexRange"),[qi,vr]=Si?Si.split("-").map(vi=>parseInt(vi,10)):[],zt=Si?{from:qi,to:vr}:void 0;Sr={type:"byteRange",url:Ce,initRange:Pt,indexRange:zt}}else if(it){let ii={representationId:pe.getAttribute("id")??void 0,bandwidth:pe.getAttribute("bandwidth")??void 0},Ct=parseInt(it.getAttribute("timescale")??"",10),Ui=it.getAttribute("initialization")??"",Pt=it.getAttribute("media"),Si=parseInt(it.getAttribute("startNumber")??"",10)??1,qi=It(Ui,ii);if(!Pt)throw new ReferenceError("No media attribute in SegmentTemplate");let vr=it.querySelectorAll("SegmentTimeline S")??[],zt=[],vi=0,yr="",bs=0;if(vr.length){let tn=Si,Vt=0;for(let Tr of vr){let Wt=parseInt(Tr.getAttribute("d")??"",10),ji=parseInt(Tr.getAttribute("r")??"",10)||0,rn=parseInt(Tr.getAttribute("t")??"",10);Vt=Number.isFinite(rn)?rn:Vt;let Xo=Wt/Ct*1e3,jy=Vt/Ct*1e3;for(let sn=0;sn<ji+1;sn++){let Hy=It(Pt,{...ii,segmentNumber:tn.toString(10),segmentTime:(Vt+sn*Wt).toString(10)}),id=(jy??0)+sn*Xo,zy=id+Xo;tn++,zt.push({time:{from:id,to:zy},url:Hy})}Vt+=(ji+1)*Wt,vi+=(ji+1)*Xo}bs=Vt/Ct*1e3,yr=It(Pt,{...ii,segmentNumber:tn.toString(10),segmentTime:Vt.toString(10)})}else if((0,sa.isNonNullable)(S)){let Vt=parseInt(it.getAttribute("duration")??"",10)/Ct*1e3,Tr=Math.ceil(S/Vt),Wt=0;for(let ji=1;ji<Tr;ji++){let rn=It(Pt,{...ii,segmentNumber:ji.toString(10),segmentTime:Wt.toString(10)});zt.push({time:{from:Wt,to:Wt+Vt},url:rn}),Wt+=Vt}bs=Wt,yr=It(Pt,{...ii,segmentNumber:Tr.toString(10),segmentTime:Wt.toString(10)})}let qy={time:{from:bs,to:1/0},url:yr};Sr={type:"template",baseUrl:Ce,segmentTemplateUrl:Pt,initUrl:qi,totalSegmentsDurationMs:vi,segments:zt,nextSegmentBeyondManifest:qy,timescale:Ct}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!gt||!kt)continue;let ms={video:"video",audio:"audio",text:"text"}[gt];if(!ms)continue;qe||=ms,Dt={id:Za,kind:ms,segmentReference:Sr,profiles:en,duration:S,bitrate:Ka,mime:kt,codecs:bi,width:Bt,height:hs,fps:Ko,quality:br}}je.language||=oe,je.label||=He,je.mime||=kt,je.codecs||=bi,je.hdr||=qe==="video"&&wc(bi),je.representations.push(Dt)}if(qe){let pe=r[qe].find(oe=>oe.id===je.id);if(pe&&je.representations.every(oe=>oe.segmentReference.type==="template"))for(let oe of pe.representations){let He=je.representations.find(kt=>kt.id===oe.id);if(!He)continue;let tt=He.segmentReference,Ce=oe.segmentReference;Ce.segments.push(...tt.segments),Ce.nextSegmentBeyondManifest=tt.nextSegmentBeyondManifest}else r[qe].push(je)}}return{duration:S,streams:r,baseUrls:n,live:v}};var So=q(dt(),1),Pc=q(We(),1),aa=require("@vkontakte/videoplayer-shared");var go=s=>{let{webmDecodingInfo:e}=F.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,aa.assertNever)(s)}},Cv=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...go(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(F.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",...go(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...go(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...go(s),...a,"HLS","HLS_ONDEMAND"];default:(0,aa.assertNever)(e)}if(F.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,aa.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},Vv=({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=F.device.isMac&&F.browser.isSafari;if(F.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,aa.assertNever)(s)}else F.video.nativeHlsSupported&&!u&&!F.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"]},Ac=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ts=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,So.default)(t.value.split("."),0)}for(let t of s){let i=(0,So.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,So.default)(e.value.split("."),0)},is=s=>{let e=s.map(i=>Bi(i)),{codecs:t}=F.video;return rM().filter(i=>{if((0,Pc.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})},rs=s=>{let e=s.map(i=>Bi(i)),{codecs:t}=F.video;return sM().filter(i=>{if((0,Pc.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Bi=s=>s.split(".")[0].replace("0",""),rM=()=>["av1","vp9","hev1","avc1"],sM=()=>["opus","mp4a"];var Xv=q(dt(),1);var aM=(s,e={})=>{let i=e.timeout||1,r=performance.now();return Me.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},nM=s=>Me.clearTimeout(s),_v=s=>typeof s=="function"&&s?.toString().endsWith("{ [native code] }"),Ov=!_v(Me.requestIdleCallback)||!_v(Me.cancelIdleCallback),Zt=Ov?aM:Me.requestIdleCallback,$t=Ov?nM:Me.cancelIdleCallback;var V=require("@vkontakte/videoplayer-shared");var Fv=q(dt(),1);var vo=s=>s.valid,he=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 ss=class extends he{};var Nv=require("@vkontakte/videoplayer-shared");var na=class extends he{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,Nv.assertNever)(e)}}};var oa=class extends he{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 ua=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Te=class extends he{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 la=class extends Te{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 ca=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends he{constructor(e,t){super(e,t),this.data=this.content}};var ur=class extends Te{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var pa=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends Te{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 ma=class extends Te{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var ba=class extends Te{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 ga=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends Te{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 va=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends Te{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ia=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=class extends Te{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 wa=class extends Te{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 xa=class extends Te{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 ka=class extends he{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends Te{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 Aa=class extends he{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 uM={ftyp:oa,moov:ua,mvhd:la,moof:ca,mdat:da,sidx:ur,trak:pa,mdia:ga,mfhd:Ta,tkhd:Sa,traf:Ia,tfhd:Ea,tfdt:wa,trun:xa,minf:va,sv3d:ha,st3d:fa,prhd:ma,proj:ya,equi:ba,uuid:na,stbl:ka,stsd:Pa,avc1:Aa,unknown:ss},ci=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||!vo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=uM[e];return i?new i(t,new s):new ss(t,new s)}};var Ci=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{vo(t)&&(this.index[t.type]??=[],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 cM=new TextDecoder("ascii"),dM=s=>cM.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",pM=s=>{let e=new ur(s,new ci),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})},hM=(s,e)=>{let i=new ci().parse(s),r=new Ci(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},fM=s=>{let t=new ci().parse(s),i=new Ci(t),r={},a=i.findAll("uuid"),n=(0,Fv.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},mM=s=>{let t=new ci().parse(s);return new Ci(t).find("sidx")?.timescale},bM=(s,e)=>{let i=new ci().parse(s),a=new Ci(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},gM=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 ci().parse(s),r=new Ci(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},Uv={validateData:dM,parseInit:gM,getIndexRange:()=>{},parseSegments:pM,parseFeedableSegmentChunk:hM,getChunkEndTime:bM,getServerLatencyTimestamps:fM,getTimescaleFromIndex:mM};var $a=q(We(),1),di=require("@vkontakte/videoplayer-shared");var jv=require("@vkontakte/videoplayer-shared");var qv={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"}},Hv=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=Ra(s,t),r=i in qv,a=r?qv[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,p=Ra(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+d):h=new DataView(s.buffer,s.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},Ra=(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},Ht=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Ra(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,jv.assertNever)(e)}},lr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Hv(i);if(!e(r))return;r.type==="master"&&lr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},zv=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Hv(s);return lr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Ht(o,n):a===17026?t=Ht(o,n):a===17029&&(i=Ht(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Wv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],SM=[231,22612,22743,167,171,163,160,175],vM=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,p=!1,c=0;return lr(s,({tag:d,type:h,value:m,valueSize:b})=>{if(d===21419){let v=Ht(m,h);l=Ra(v)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+b):d===357149030?a=!0:d===290298740?n=!0:d===2807729?i=Ht(m,h):d===17545?r=Ht(m,h):d===21420&&l===475249515?u=Ht(m,h):d===374648427?lr(m,({tag:v,type:S,value:y})=>v===30321?(p=Ht(y,S)===1,!1):!0):a&&n&&(0,$a.default)(Wv,d)&&(o=!0),!o}),(0,di.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,di.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,di.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=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:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},yM=s=>{if((0,di.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},TM=(s,e)=>{let t=!1,i=!1,r=o=>(0,di.isNonNullable)(o.time)&&(0,di.isNonNullable)(o.position),a=[],n;return lr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Ht(l,u));break;case 183:break;case 241:n&&(n.position=Ht(l,u));break;default:t&&(0,$a.default)(Wv,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:p}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},IM=s=>{let e=0,t=!1;try{lr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,$a.default)(SM,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,$a.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Qv={validateData:zv,parseInit:vM,getIndexRange:yM,parseSegments:TM,parseFeedableSegmentChunk:IM};var Mt=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Qv;case"mp4":return Uv}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Rc=q(dt(),1);var Gv=require("@vkontakte/videoplayer-shared"),Vi=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Xt(a):void 0)??(0,Gv.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ma=({id:s,bitrate:e})=>({id:s,bitrate:e}),Yv=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Kv=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),$c=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Rc.default)(i.split("."),0),isDefault:r}),Mc=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Rc.default)(r.split("."),0)}),Lc=s=>"url"in s,Et=s=>s.type==="template";var as=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,manifest:o}){this.error$=new V.Subject;this.playingRepresentation$=new V.ValueSubject(void 0);this.playingRepresentationInit$=new V.ValueSubject(void 0);this.currentSegmentLength$=new V.ValueSubject(0);this.onLastSegment$=new V.ValueSubject(!1);this.fullyBuffered$=new V.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 le;this.downloadAbortController=new le;this.subscription=new V.Subscription;this.startWith=(0,V.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,V.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=Mt(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,V.assertNonNullable)(i,"No init buffer for starting representation"),(0,V.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,V.abortable)(this.destroyAbortController.signal,async function*(e,t=!0){if((0,V.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,V.assertNonNullable)(r,`No such representation ${e}`),(0,V.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,V.assertNonNullable)(a,"No init buffer for switching representation"),(0,V.assertNonNullable)(n,"No segments for switching representation");let o=this.getCurrentPosition()??0,u=c=>c.segment.networkStatus!=="downloaded"||c.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,l=c=>{let d=this.representations.get(c.representationId);return(0,V.assertNonNullable)(d,"No itemRepresentation for previous track before switch"),c.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(d,r)},p=c=>t?u(c)&&l(c):u(c);this.bufferPlaybackQueue.filter(p).forEach(c=>c.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(c=>!p(c)),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,V.abortable)(this.downloadAbortController.signal,async function*(){let e=(0,V.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,V.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,V.fromEvent)(i,"online").pipe((0,V.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=n,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(u=>[u.id,u]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){(0,V.isNullable)(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return(0,V.isNonNullable)(t)&&(0,V.isNonNullable)(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from}getRepresentationInitialTime(){return(0,V.isNullable)(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if((0,V.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Xv.default)(e,-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,V.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_n85ich4920f)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_n85ich4920f(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=Vi(e),a=Vi(t);i=(0,V.isNonNullable)(r)&&(0,V.isNonNullable)(a)&&(0,V.isHigher)(a.quality,r.quality)}else if(this.kind==="audio"){let r=Ma(e),a=Ma(t);i=(0,V.isNonNullable)(r?.bitrate)&&(0,V.isNonNullable)(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 le,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,Zt(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,V.isNonNullable)(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,a);let{initMetadata:n,initDataView:o,segments:u}=await a??{};if(this.initDataPromises.delete(e.id),(0,V.isNullable)(o)||(0,V.isNullable)(u))return;n&&this.parsedInitData.set(e.id,n);let l=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,u),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:V.ErrorCategory.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if((0,V.isNullable)(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(o=>this.withinInterval(e,o.segment.time)),i=this.bufferPlaybackQueue.find(o=>o.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),a=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;(0,V.isNonNullable)(r)&&(0,V.isNonNullable)(i)&&(0,V.isNonNullable)(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,V.isNonNullable)(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),(0,V.isNonNullable)(a)&&this.withinRemoveInterval(e,a.segment.time)&&await this.removeSegment(a,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){(0,V.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,V.isNullable)(t)||(0,V.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,V.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(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){let t=this.segments.get(this.downloadingRepresentationId??"");if((0,V.isNullable)(t)||t.length===0)return;let i=t[t?.length-1];(0,V.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,V.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;(0,V.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,V.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,V.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,V.isNonNullable)(e)?e-i>t:!1}async appendSegmentFully(e,t){if((0,V.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,V.isNullable)(e.segment.data)||(0,V.isNullable)(e.segment.loadedBytes)||(0,V.isNullable)(e.segment.feedingBytes)||(0,V.isNullable)(e.segment.fedBytes)||(0,V.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?.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,V.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,V.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,V.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 ei=require("@vkontakte/videoplayer-shared");var yo=class extends as{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,ei.now)(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Ze(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(nt(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,ei.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ei.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},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,ei.isNullable)(o)||(0,ei.isNullable)(r)||n.aborted))for(let u of e){let{segment:l}=u,p=l.byte.from-r,c=l.byte.to-r,d=c-p+1,h=p<a,m=c<=a;l.size=d,h&&(l.networkStatus==="downloading"&&l.bufferStatus==="none"&&m?(l.data=new DataView(t.buffer,t.byteOffset+p,d),this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u),l.loadedBytes=Math.min(d,a-p),await this.onDownloadItem(u)):(0,ei.isNonNullable)(l.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&l.networkStatus==="downloading"&&(l.loadedBytes=Math.min(d,a-p),m&&(this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u)),l.loadedBytes>l.feedingBytes&&(l.data=new DataView(t.buffer,t.byteOffset+p,l.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(nt(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var pi=require("@vkontakte/videoplayer-shared");var ns=class extends as{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,pi.now)(),(0,pi.isNullable)(o))return;let u=e[0],l=new DataView(o);u.segment.size=l.byteLength,u.segment.loadedBytes=l.byteLength,u.segment.data=l,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Ze(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,pi.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:pi.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!nt(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,pi.isNullable)(u)||(0,pi.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(!nt(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var Dc=q(nr(),1),Jv=q(dt(),1);var Ue=require("@vkontakte/videoplayer-shared");var To=class extends ns{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new Ue.ValueSubject(0);this.currentLowLatencySegmentLength$=new Ue.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=(0,Dc.default)(t.streams[this.kind],r=>r.representations);for(let r of i){if((0,Ue.isNullable)(r)||!nt(r.segmentReference))return;let a=r.segmentReference.segments.map(p=>({...p,networkStatus:"none",bufferStatus:"none",size:void 0})),n=100,o=this.segments.get(r.id)??[],u=(0,Jv.default)(o,-1)?.time.to??0,l=a?.findIndex(p=>u>=p.time.from+n&&u<=p.time.to+n);if(l===-1){let p=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,p)}else{let p=a.slice(l+1);this.segments.set(r.id,[...o,...p])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Ue.assertNonNullable)(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t?.streams[this.kind],r=(0,Dc.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Ue.isNullable)(r))return;let a=this.segments.get(r.id);if(a?.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){if((0,Ue.isNullable)(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return(0,Ue.isNullable)(t)||!nt(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,Ue.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){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if((0,Ue.isNullable)(t.segment.data)||(0,Ue.isNullable)(r)||!nt(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:n}=r;t.segment.time.to=a.getChunkEndTime(i,n)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!nt(a))return;let n=this.segments.get(r.id)??[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.from));if(o?.isCurrentLowLatency&&(o.time.to=t.segment.time.to,i=o.time.to-o.time.from,o.isCurrentLowLatency=!1),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let l=Math.round(t.segment.time.to*a.timescale/1e3).toString(10),p=It(a.segmentTemplateUrl,{segmentTime:l});n.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:p,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){try{let a=this.tuning.dash.useFetchPriorityHints?i:"auto",n=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,a);this.initDataPromises.set(t.id,n);let{initMetadata:o,initDataView:u,segments:l}=await n??{};if(this.initDataPromises.delete(t.id),(0,Ue.isNullable)(u)||(0,Ue.isNullable)(l))return;o&&this.parsedInitData.set(t.id,o);let p=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,p);let c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(t.id,c),this.failedDownloads=0}catch(a){r&&this.error$.next({id:"LoadInits",category:Ue.ErrorCategory.WTF,message:"loadInit threw",thrown:a})}}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 La=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new To(e,t,i,r):nt(i[0].segmentReference)?new ns(e,t,i,r):new yo(e,t,i,r)}};var ot=require("@vkontakte/videoplayer-shared");var _i=require("@vkontakte/videoplayer-shared");var EM=18,Zv=!1;try{Zv=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=EM}catch(s){console.error(s)}var Bc=class{constructor(e,t=!1){this.bufferFull$=new _i.Subject;this.error$=new _i.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:_i.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};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)};Zv&&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(){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(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:_i.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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,_i.assertNever)(t)}}},ey=Bc;var Be=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var Da=class{constructor(e){this.error$=new ot.Subject;this.subscription=new ot.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new ey(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,ot.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ot.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,ot.isNullable)(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!(0,ot.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,ot.isNullable)(this.sourceBuffer)||!G(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,ot.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,ot.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}async abortBuffer(e){return(0,ot.isNullable)(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var wM=["timeupdate","progress","play","seeked","stalled","waiting"],ty=["timeupdate","progress","loadeddata","playing","seeked"],Io=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new E.Subscription;this.subscriptionRemovable=new E.SubscriptionRemovable;this.representationSubscription=new E.Subscription;this.forceEnded$=new E.Subject;this.destroyController=new le;this.state$=new te("none");this.currentVideoRepresentation$=new E.ValueSubject(void 0);this.currentVideoRepresentationInit$=new E.ValueSubject(void 0);this.currentAudioRepresentation$=new E.ValueSubject(void 0);this.currentVideoSegmentLength$=new E.ValueSubject(0);this.currentAudioSegmentLength$=new E.ValueSubject(0);this.error$=new E.Subject;this.manifestRequested=new E.Subject;this.manifestReceived=new E.Subject;this.firstBytesRequested=new E.Subject;this.firstBytesReceived=new E.Subject;this.lastConnectionType$=new E.ValueSubject(void 0);this.lastConnectionReused$=new E.ValueSubject(void 0);this.lastRequestFirstBytes$=new E.ValueSubject(void 0);this.currentLiveTextRepresentation$=new E.ValueSubject(null);this.isLive$=new E.ValueSubject(!1);this.isActiveLive$=new E.ValueSubject(!1);this.isLowLatency$=new E.ValueSubject(!1);this.liveDuration$=new E.ValueSubject(0);this.liveSeekableDuration$=new E.ValueSubject(0);this.liveAvailabilityStartTime$=new E.ValueSubject(0);this.liveStreamStatus$=new E.ValueSubject(void 0);this.currentBuffer$=new E.ValueSubject({from:0,to:0});this.bufferLength$=new E.ValueSubject(0);this.nativeBufferLength$=new E.ValueSubject(0);this.liveLatency$=new E.ValueSubject(void 0);this.liveLoadBufferLength$=new E.ValueSubject(0);this.livePositionFromPlayer$=new E.ValueSubject(0);this.currentStallDuration$=new E.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new E.ValueSubject(0);this.fetcherRecoverableError$=new E.Subject;this.fetcherError$=new E.Subject;this.initRepresentations=(0,E.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,E.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),(0,E.assertNonNullable)(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=(0,E.abortable)(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){(0,E.isNullable)(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:E.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new mo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:E.ErrorCategory.PARSER,message:"No playable video representations"})}initBuffer(){(0,E.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,E.merge)(...wM.map(t=>(0,E.fromEvent)(this.element,t)),(0,E.fromEvent)((0,E.getWindow)(),"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:E.ErrorCategory.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add((0,E.merge)(...e.map(t=>(0,E.fromEvent)(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add((0,E.fromEvent)(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,E.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:E.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){(0,E.assertNonNullable)(this.element),(0,E.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",(0,E.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,E.isNonNullable)(this.element)&&(0,E.isNonNullable)(this.source)&&(0,E.isNonNullable)(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&(0,E.getWindow)().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),(0,E.isNonNullable)(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if((0,E.isNullable)(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){(0,E.assertNonNullable)(this.element),(0,E.assertNonNullable)(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",(0,E.flattenObject)(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=(0,E.now)(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,l=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,p=(0,E.isNonNullable)(this.videoBufferManager)&&u<a&&r-n>i,c=(0,E.isNonNullable)(this.audioBufferManager)&&l<a&&r-o>i;return(p||c)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if((0,E.isNullable)(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",(0,E.flattenObject)(i)),i}parseManifest(e){try{return es(e??"",this.manifestUrlString)}catch(t){let i=Yr(e)??{id:"ManifestParsing",category:E.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,l)=>!!(this.element?.canPlayType?.(u)&&rt()?.isTypeSupported?.(`${u}; codecs="${l}"`)||o==="text"),r,a;for(let o of["video","audio"]){let l=e.streams[o].filter(({mime:c,codecs:d})=>i(o,c,d));t[o]=l;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:d})=>d);o==="audio"&&(a=rs(c),p=a[0]),o==="video"&&(r=is(c),this.forceVideoCodec&&(0,iy.default)(r,this.forceVideoCodec)?p=this.forceVideoCodec:p=r[0]),p&&(t[o]=l.filter(({codecs:d})=>Bi(d)===p))}else{let c=new Set(l.map(({codecs:d})=>d));p=ts(c),p&&(t[o]=l.filter(({codecs:d})=>d.startsWith(p)))}if(o==="video"){let c=this.tuning.preferHDR,d=t.video.some(m=>m.hdr),h=t.video.some(m=>!m.hdr);F.display.isHDR&&c&&d?t.video=t.video.filter(m=>m.hdr):h&&(t.video=t.video.filter(m=>!m.hdr))}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:a}),n}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){(0,E.assertNonNullable)(this.manifest),(0,E.assertNonNullable)(this.element);let a=l=>{this.representationSubscription.add((0,E.fromEvent)(l,"error").pipe((0,E.filter)(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=$r();let n=(0,E.getWindow)().document,o=n.createElement("source");if(a(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),xi())if(r){let l=n.createElement("source");a(l),l.type="application/x-mpegurl",l.src=r.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoNativeBufferManager=new Da(this.source),this.videoBufferManager=La.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,E.isNonNullable)(i)){this.audioNativeBufferManager=new Da(this.source);let l=this.manifest.streams.audio.reduce((p,c)=>[...p,...c.representations],[]);this.audioBufferManager=La.getBufferManager("audio",this.audioNativeBufferManager,l,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=>{e&&(this.timeoutSourceOpenId=(0,E.getWindow)().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&(0,E.getWindow)().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,E.merge)(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),(0,E.assertNonNullable)(this.videoBufferManager),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add((0,E.merge)(...ty.map(e=>(0,E.fromEvent)(this.element,e))).pipe((0,E.map)(e=>this.videoBufferManager?.getPlaybackBufferState()),(0,E.filter)(E.isNonNullable),(0,E.map)(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add((0,E.merge)(...ty.map(e=>(0,E.fromEvent)(this.element,e))).pipe((0,E.map)(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),(0,E.filterChanged)()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe((0,E.filter)(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=(0,E.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if((0,E.isNullable)(this.element)||(0,E.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};var be=require("@vkontakte/videoplayer-shared");var Eo=class extends Io{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){(0,be.assertNonNullable)(this.manifest),(0,be.assertNonNullable)(this.source);let e=[this.manifest.duration??0,...(0,Cc.default)((0,Cc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],t=>t.representations),t=>{let i=[];return t.duration&&i.push(t.duration),nt(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){(0,be.assertNonNullable)(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){(0,be.assertNonNullable)(this.element);let e=(0,be.merge)((0,be.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,be.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,be.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,be.merge)(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe((0,be.map)(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=(0,be.merge)(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe((0,be.map)(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=(0,be.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,be.filterChanged)(),(0,be.map)(({allBuffersFull:a,someBufferEnded:n})=>a&&n),(0,be.filter)(a=>a)),r=()=>{try{this.source?.endOfStream()}catch(a){this.error$.next({id:"EndOfStream",category:be.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:a})}};this.representationSubscription.add((0,be.merge)(this.forceEnded$,i).pipe((0,be.filter)(a=>(0,be.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var os=class extends ta{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,ry.filterChanged)()).subscribe(a=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:c}])=>c.id===a);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,l=this.params.desiredState.videoStream.getTransition();l&&l.to&&l.to.id===u.id&&this.params.desiredState.videoStream.setState(l.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(no(u));let p=this.player.calculateDurationFromSegments();p&&this.params.output.duration$.next(p/1e3)},r))}getPlayer(){return new Eo({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 H=require("@vkontakte/videoplayer-shared");var uy=q(We(),1),_c=q(nr(),1);var et=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};var I=require("@vkontakte/videoplayer-shared");var wo=q(We(),1),cr=q(dt(),1),xo=q(nr(),1);var ny=q(Kn(),1);var Oi=require("@vkontakte/videoplayer-shared");var xM=18,sy=!1;try{sy=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=xM}catch(s){console.error(s)}var Vc=class{constructor(e,t=!1){this.bufferFull$=new Oi.Subject;this.error$=new Oi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Oi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};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)};sy&&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(){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(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Oi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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,Oi.assertNever)(t)}}},ay=Vc;var us=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var R=require("@vkontakte/videoplayer-shared");var Ba=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new R.ValueSubject(0);this.currentLowLatencySegmentLength$=new R.ValueSubject(0);this.currentSegmentLength$=new R.ValueSubject(0);this.onLastSegment$=new R.ValueSubject(!1);this.fullyBuffered$=new R.ValueSubject(!1);this.playingRepresentation$=new R.ValueSubject(void 0);this.playingRepresentationInit$=new R.ValueSubject(void 0);this.error$=new R.Subject;this.gaps=[];this.subscription=new R.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;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,R.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,R.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 ay(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add((0,R.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,R.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!G(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,us(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"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,R.assertNonNullable)(i,"No init buffer for starting representation"),(0,R.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,R.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,R.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,R.isNullable)(a)||(0,R.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,R.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,R.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,R.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,R.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,R.isNullable)(a)||(0,R.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,R.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,R.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,R.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,xo.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!Et(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,R.assertNonNullable)(r,`Representation not found by id ${i}`);let a=this.segments.get(i);(0,R.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,R.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));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,(0,R.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,R.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,R.isNullable)(o)||(0,R.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,R.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,R.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,R.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 le,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,R.isNullable)(e)||(0,R.isNullable)(this.downloadingRepresentationId)||(0,R.isNullable)(this.playingRepresentationId)||(0,R.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,R.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,R.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,R.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,R.isNullable)(r)||(0,R.isNullable)(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);(0,R.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=Vi(i),m=Vi(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,R.isNonNullable)(h)&&(0,R.isNonNullable)(m)&&(0,R.isHigher)(h.quality,m.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||v?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let y=[...this.segments.entries()].map(([k,x])=>{let L=x.find(O=>e>=O.time.from&&e<O.time.to);return{representationId:k,status:L?.status}}).find(k=>k.status==="fed")?.representationId;y&&(this.playingRepresentationId=y,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&us(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let p=[];if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,wo.default)(p,n))d="high";else{let h=(0,cr.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,cr.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-c.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,R.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?.streams[this.kind];if(!t)return;let i=(0,xo.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,xo.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!Et(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,cr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,R.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,cr.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Et(r))return;let a=this.segments.get(i.id)??[],n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=It(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&$t&&$t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&$t&&$t(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}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:d,time:{from:h,to:m}},b)=>{let v=h<=i&&m>=i,S=h>i||v||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),k=this.preloadOnly&&h<=i+y||r<y&&m-h>=y||m<=i+y;return(d==="none"||d==="partially_ejected"&&S&&k&&this.sourceBuffer&&G(this.mediaSource,this.sourceBuffer)&&!(et(this.sourceBuffer.buffered,h)&&et(this.sourceBuffer.buffered,m)))&&S&&k});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){Et(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:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,R.abortable)(o,async function*(){let p=(0,R.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=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,R.now)(),!p)return;let c=new DataView(p),d=Mt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Ze(p)||(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())Et(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,R.abortable)(n,async function*(){let u=(0,R.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,R.fromEvent)(window,"online").pipe((0,R.once)()).subscribe(()=>{l(),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,R.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ze(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Et(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,cr.default)(e,0).byte.from,to:(0,cr.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,R.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Et(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,R.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:R.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,wo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!G(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 l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(!h)continue;let b=Mt(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===d?v:b.parseFeedableSegmentChunk(v);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!((0,R.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(et(this.sourceBuffer.buffered,e.segment.time.from,100)&&et(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:R.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",Lc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.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||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Zt(()=>(0,ny.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,R.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,R.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:l,dataView:p,segments:c}=u,d=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Et(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,u=>{a||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:R.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||!G(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,R.isNullable)(e))return!1;let r=[],a=0,n=u=>{u.sort((p,c)=>p.from-c.from);let l=[u[0]];for(let p=1;p<u.length;p++){let{from:c,to:d}=u[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(u[p])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=n(r);let l=Lc(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,p=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let d of this.segments.values())for(let h of d)(0,wo.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};o(d)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+u&&p.status==="fed"&&o(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!G(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||!G(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||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,R.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!G(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||!G(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=Zt(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:R.ErrorCategory.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,R.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,R.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(p=>p.from-t<=n&&p.to+t>=o),l=e.filter(p=>n>=p.from&&n<p.to-t||o>p.from+t&&o<=p.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:R.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var K=require("@vkontakte/videoplayer-shared");var Po=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new K.Subject;this.firstBytesManifest$=new K.Subject;this.firstBytesRequested$=new K.Subject;this.firstBytesReceived$=new K.Subject;this.lastConnectionType$=new K.ValueSubject(void 0);this.lastConnectionReused$=new K.ValueSubject(void 0);this.lastRequestFirstBytes$=new K.ValueSubject(void 0);this.recoverableError$=new K.Subject;this.error$=new K.Subject;this.abortAllController=new le;this.subscription=new K.SubscriptionRemovable;this.fetchManifest=(0,K.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=jt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Xr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ko);return r?(t.log("success",(0,K.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",(0,K.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,K.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:l=!1,ignoreNetworkErrors:p=!1}={}){let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let P=new URL(c,location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),c=P.toString();break}default:(0,K.assertNever)(t)}this.requestQuic&&(c=jt(c));let m=this.abortAllController.signal,b;if(n){let P=new le;if(b=(0,K.merge)((0,K.fromEvent)(this.abortAllController.signal,"abort"),(0,K.fromEvent)(n,"abort")).subscribe(()=>{try{P.abort()}catch(re){ko(re)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(re){ko(re)}m=P.signal}let v=0,S=(0,K.now)();h.log("startRequest",(0,K.flattenObject)({url:c,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested$.next();let y=yield this.doFetch(c,{priority:a,headers:d,signal:m},{ignoreNetworkErrors:p}),k=(0,K.now)();if(!y)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(b),null;if(this.throughputEstimator?.addRawRtt(k-S),!y.ok||!y.body){this.unsubscribeAbortSubscription(b);let P=`Fetch error ${y.status}: ${y.statusText}`;return h.error("error",{message:P}),h.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){this.unsubscribeAbortSubscription(b);let P=(0,K.now)(),re={requestStartedAt:S,requestEndedAt:P,duration:P-S};return h.log("endRequest",(0,K.flattenObject)(re)),h.end(),y.arrayBuffer()}let x=y.body;if(o){let P;[x,P]=y.body.tee(),this.throughputEstimator?.trackStream(P,u)}let L=x.getReader(),O,N=parseInt(y.headers.get("content-length")??"",10);Number.isFinite(N)&&(O=N),!O&&i&&(O=i.to-i.from+1);let M=O?new Uint8Array(O):new Uint8Array(0),j=!1,D=P=>{this.unsubscribeAbortSubscription(b),j=!0,ko(P)},se=(0,K.abortable)(m,async function*({done:P,value:re}){if(v===0&&(this.lastRequestFirstBytes$.next((0,K.now)()-S),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(b);return}if(!P&&re){if(l&&O)M.set(re,v),v+=re.byteLength;else{let U=new Uint8Array(M.length+re.length);U.set(M),U.set(re,M.length),M=U,v+=re.byteLength}r?.(new DataView(M.buffer),v),yield L?.read().then(se,D)}}.bind(this));yield L?.read().then(se,D),this.unsubscribeAbortSubscription(b);let z=(0,K.now)(),A={failed:j,requestStartedAt:S,requestEndedAt:z,duration:z-S};return j?(h.error("endRequest",(0,K.flattenObject)(A)),h.end(),null):(h.log("endRequest",(0,K.flattenObject)(A)),h.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,K.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let v=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,K.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}onHeadersReceived(e){let{type:t,reused:i}=Kr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,K.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await ft(e,t);if(r.ok)return r;if(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:K.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:K.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:K.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:K.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:K.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ko=s=>{if(!Ze(s))throw s};var Ca=require("@vkontakte/videoplayer-shared"),Ni=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ca.ValueSubject(e.initial),this.debounced$=new Ca.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new st(`raw_${t}`),this.smoothedSeries$=new st(`smoothed_${t}`),this.reportedSeries$=new st(`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,Ca.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 Ao=class extends Ni{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ui(this.slow,e,this.params.emaAlphaSlow),this.fast=ui(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ro=class extends Ni{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=lc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ui(this.emaSmoothed,e,this.params.emaAlpha);let i=Jg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var $o=class extends Ni{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?ui(this.smoothed,t,this.params.emaAlpha):t}};var hi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ao({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ro({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 $o({initial:e,label:"liveEdgeDelay",...t})}};var ls=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var Mo=require("@vkontakte/videoplayer-shared");var Va=class s{constructor(e,t){this.currentRepresentation$=new Mo.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?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,Mo.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of 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?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Et(t.segmentReference))}};var PM=["timeupdate","progress","play","seeked","stalled","waiting"],AM=["timeupdate","progress","loadeddata","playing","seeked"];var Lo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new I.Subscription;this.subscriptionRemovable=new I.SubscriptionRemovable;this.representationSubscription=new I.Subscription;this.state$=new te("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.firstBytesManifest$=new I.Subject;this.manifestReceived$=new I.Subject;this.firstBytesRequested$=new I.Subject;this.firstBytesReceived$=new I.Subject;this.lastConnectionType$=new I.ValueSubject(void 0);this.lastConnectionReused$=new I.ValueSubject(void 0);this.lastRequestFirstBytes$=new I.ValueSubject(void 0);this.currentLiveTextRepresentation$=new I.ValueSubject(null);this.isLive$=new I.ValueSubject(!1);this.isActiveLive$=new I.ValueSubject(!1);this.isLowLatency$=new I.ValueSubject(!1);this.liveDuration$=new I.ValueSubject(0);this.liveSeekableDuration$=new I.ValueSubject(0);this.liveAvailabilityStartTime$=new I.ValueSubject(0);this.liveStreamStatus$=new I.ValueSubject(void 0);this.bufferLength$=new I.ValueSubject(0);this.liveLatency$=new I.ValueSubject(void 0);this.liveLoadBufferLength$=new I.ValueSubject(0);this.livePositionFromPlayer$=new I.ValueSubject(0);this.currentStallDuration$=new I.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new I.ValueSubject(0);this.fetcherRecoverableError$=new I.Subject;this.fetcherError$=new I.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new I.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new le;this.initManifest=(0,I.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ae(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:I.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,I.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=es(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Yr(e)??{id:"ManifestParsing",category:I.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&rt()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";if(c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),c&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let m=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(m).catch(b=>{this.error$.next({id:"updateManifest",category:I.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:b})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=rs(d),c=n[0]),u==="video"&&(a=is(d),this.forceVideoCodec&&(0,uy.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>Bi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=ts(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);F.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",(0,I.flattenObject)(o)),o}.bind(this));this.initRepresentations=(0,I.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,I.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,I.assertNonNullable)(this.manifest),(0,I.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add((0,I.fromEvent)(c,"error").pipe((0,I.filter)(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=$r();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),xi())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}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((c,d)=>[...c,...d.representations],[]);if(this.videoBufferManager=new Ba("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,I.isNonNullable)(t)){let c=this.manifest.streams.audio.reduce((d,h)=>[...d,...h.representations],[]);this.audioBufferManager=new Ba("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(Va.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Va(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,I.merge)(...AM.map(c=>(0,I.fromEvent)(this.element,c))).pipe((0,I.map)(c=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),(0,I.filterChanged)(),(0,I.tap)(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,I.merge)((0,I.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,I.filterChanged)()).subscribe(d=>this.liveStreamEndTimestamp=(0,I.now)())),this.subscription.add((0,I.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:d}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,I.interval)(d).subscribe(h=>{let m=Ii(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,m+d,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,I.fromEvent)(this.element,"play").subscribe(d=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,I.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.map)(({isActiveLive:d,isLowLatency:h})=>d&&h),(0,I.filterChanged)()).subscribe(d=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add((0,I.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,I.filter)(({bufferLength:d,isActiveLive:h,isLowLatency:m})=>h&&m&&!!d)).subscribe(({bufferLength:d})=>this.liveBuffer.next(d))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(d=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!d)return;let h=this.liveSeekableDuration$.getValue()-d/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+d/1e3)})),this.representationSubscription.add((0,I.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,I.filter)(({isLive:d})=>d),(0,I.filterChanged)((d,h)=>h.bufferLength<d.bufferLength),(0,I.map)(({rtt:d,bufferLength:h,segmentServerLatency:m})=>{let b=Ii(this.manifestUrlString,2);return(d/2+h+m+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,I.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:d,isActiveLive:h,isLowLatency:m})=>{if(!m||!h)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=d-b;if(this.isManualDecreasePlaybackInLive())return;let k=1;Math.abs(y)>v&&(k=1+Math.sign(y)*S),ls(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{let h=0;if(d){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add((0,I.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,I.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:d,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,b=Ii(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,x=isFinite(d)?d:h,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let N="none";if(L?N="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(M=>M.proceedLowLatencyLive()),N="active_low_latency"):b!==0&&x<S?N="live_forward_buffering":x<S+k&&(N="live_with_target_offset"),isFinite(d)&&(c=d>c?d:c),N==="live_forward_buffering"||N==="live_with_target_offset"){let M=c-(S+y),j=this.normalizeLiveOffset(Math.trunc(b+M/m)),D=Math.abs(j-b),se=0;!d||D<=this.tuning.dashCmafLive.offsetCalculationError?se=b:j>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(se=j),this.manifestUrlString=Ae(this.manifestUrlString,se,2)}(N==="live_with_target_offset"||N==="live_forward_buffering")&&(c=0,await this.updateLive())},d=>{this.error$.next({id:"updateLive",category:I.ErrorCategory.VIDEO_PIPELINE,thrown:d,message:"Failed to update live with subscription"})}))}let u=(0,I.merge)(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe((0,I.map)(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=(0,I.merge)(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe((0,I.map)(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=(0,I.combine)({allBuffersFull:u,someBufferEnded:l}).pipe((0,I.filterChanged)(),(0,I.map)(({allBuffersFull:c,someBufferEnded:d})=>c&&d),(0,I.filter)(c=>c));if(this.representationSubscription.add((0,I.merge)(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add((0,I.merge)(...this.bufferManagers.map(c=>c.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 c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(d=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){d();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)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),d()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,_c.default)((0,_c.default)([...this.manifest.streams.audio,...this.manifest.streams.video],d=>d.representations),d=>{let h=[];return d.duration&&h.push(d.duration),Et(d.segmentReference)&&d.segmentReference.totalSegmentsDurationMs&&h.push(d.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&(0,I.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,I.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:I.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),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 Po({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.liveBuffer=hi.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,I.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,I.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ae(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,I.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,I.merge)(...PM.map(e=>(0,I.fromEvent)(this.element,e)),(0,I.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,I.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,I.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&et(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let p=this.currentStallDuration$.getValue();p+=n,this.currentStallDuration$.next(p);let c={timeInWaiting:p},d=(0,I.now)(),h=100,m=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(m);let b=this.audioBufferManager?.lastDataObtainedTimestamp??0,v=this.videoBufferManager?.getForwardBufferDuration()??0,S=this.audioBufferManager?.getForwardBufferDuration()??0,y=v<h&&d-m>r,k=this.audioBufferManager&&S<h&&d-b>r;if((!t||l)&&((y||k)&&p>r||p>=i))throw new Error(`Stall timeout exceeded: ${p} ms`);if(o&&p%a===0){let x=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(x),this.updateManifest()):this.seekLive(x).catch(L=>{this.error$.next({id:"stallIntervalCallback",category:I.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:L})}),c.liveLastOffset=x}else{let x=this.element.currentTime*1e3;this.videoBufferManager?.maintain(x),this.audioBufferManager?.maintain(x),c.position=x}this.tracer.log("stallIntervalCallback",(0,I.flattenObject)(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,I.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:I.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?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),et(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,I.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,I.isNonNullable)(this.element)&&(0,I.isNonNullable)(this.source)&&(0,I.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,I.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.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 l of u.gaps)(r&&l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.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,I.flattenObject)(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var mt=require("@vkontakte/videoplayer-shared"),Do=class{constructor(){this.subscription=new mt.Subscription;this.pipSize$=new mt.ValueSubject(void 0);this.videoSize$=new mt.ValueSubject(void 0);this.elementSize$=new mt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=mt.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,mt.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,mt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,mt.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 dr=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new te("stopped");this.observableVideo=null;this.droppedFramesManager=new Ri;this.stallsManager=new Wr;this.elementSizeManager=new Do;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new qt;this.audioTrackSwitchHistory=new qt;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?.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?.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?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,H.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Mi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 ct(e.source.url),this.params=e,this.video=Ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(De(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Lo({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,H.isNullable)(this.observableVideo)&&(this.observableVideo=Xe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:H.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,H.filter)(c=>!!c.length),(0,H.once)()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,H.map)(c=>c.to.state!=="none"),(0,H.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.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,H.filter)(H.isNonNullable),(0,H.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,H.map)(c=>c.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(At(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Di({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(lt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(pt(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:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if((0,H.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let v of d.audio){b.push($c(v));let S=[];for(let y of v.representations){let k=Ma(y);S.push(k),this.audioTracksMap.set(k,{stream:v,representation:y})}this.audioStreamsMap.set(v,S)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of d.video){m.push(Mc(b));let v=[];for(let S of b.representations){let y=Vi({...S,streamId:b.id});y&&(v.push(y),this.videoTracksMap.set(y,{stream:b,representation:S}))}this.videoStreamsMap.set(b,v)}this.params.output.availableVideoStreams$.next(m);for(let b of d.text)for(let v of b.representations){let S=Yv(b,v);this.textTracksMap.set(S,{stream:b,representation:v})}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?.video&&this.params.output.availableVideoCodecs$.next(h.video),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 c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,H.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,H.fromEvent)(this.video,"progress")).pipe((0,H.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,H.throttle)(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,v=[...this.videoTracksMap.keys()].find(y=>this.videoTracksMap.get(y)?.representation.id===m.id);(0,H.isNonNullable)(v)&&(this.stallsManager.lastVideoTrackSelected=v);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")await this.player.initRepresentations(m.id,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,H.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,H.merge)((0,H.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,H.map)(c=>c.to)))}).pipe((0,H.map)(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),(0,H.filterChanged)()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,H.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,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(Mc(m));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,H.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next($c(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,H.map)(({to:c})=>c==="ready"),(0,H.filterChanged)());this.subscription.add((0,H.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,H.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,H.merge)(l,this.player.state$.stateChangeEnded$,(0,H.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=(0,H.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ar:sr,t=this.params.tuning.useNewAutoSelectVideoTrack?Hr:jr,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:qr,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:M})=>M===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:M})=>M===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=Be(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,v=Math.min(h/Math.min(m,b||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),y=[...this.audioStreamsMap.keys()].find(({id:M})=>M===S?.id)??this.audioStreamsMap.keys().next().value,k=0;if(y){if(u&&!n){let M=e(u,d,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);k=Math.max(k,M?.bitrate??-1/0)}if(l){let M=e(l,d,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);k=Math.max(k,M?.bitrate??-1/0)}}let x=u;(n||!x)&&(x=i(d,{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:k,forwardBufferHealth:v,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let L=y&&t(x,d,this.audioStreamsMap.get(y)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),O=this.videoTracksMap.get(x)?.representation,N=L&&this.audioTracksMap.get(L)?.representation;if(O&&N)return[O,N];if(O&&!N&&this.audioTracksMap.size===0)return[O,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ye(this.video),this.tracer.end()}};var _a=class extends dr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Se=require("@vkontakte/videoplayer-shared");var Oa=class extends dr{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 Se.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,Se.filterChanged)()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!u&&!l&&c?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,Se.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,Se.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Se.map)(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u*1e3+l+t:void 0)).subscribe(i.liveTime$)).add((0,Se.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,Se.merge)(r.playbackRateState$,new Se.ValueSubject(1))}).pipe((0,Se.filter)(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||(0,Se.isNullable)(p)||(t=u-p)})).add((0,Se.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,Se.merge)(r.playbackRateState$,new Se.ValueSubject(1))}).pipe((0,Se.filterChanged)((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||(0,Se.isNullable)(u)||(0,Se.isNullable)(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=Kv(u);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,Se.filter)(u=>(0,Se.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Q=require("@vkontakte/videoplayer-shared");var Sy=q(We(),1),Hc=q(nr(),1);var T=require("@vkontakte/videoplayer-shared");var Oo=q(We(),1),hr=q(dt(),1),No=q(nr(),1);var by=q(Kn(),1);var Fi=require("@vkontakte/videoplayer-shared");var $M=18,ly=!1;try{ly=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=$M}catch(s){console.error(s)}var Oc=class{constructor(e,t=!1){this.bufferFull$=new Fi.Subject;this.error$=new Fi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Fi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};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)};ly&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){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(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Fi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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,Fi.assertNever)(t)}}},cy=Oc;var $=require("@vkontakte/videoplayer-shared");var Nc=q(dt(),1);var Bo=require("@vkontakte/videoplayer-shared"),Na=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Xt(a):void 0)??(0,Bo.videoSizeToQuality)({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},dy=({id:s,bitrate:e})=>({id:s,bitrate:e}),py=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),hy=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Fc=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Nc.default)(i.split("."),0),isDefault:r}),Uc=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Nc.default)(r.split("."),0)}),qc=s=>"url"in s,wt=s=>s.type==="template";var fy=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},pr=(s,e)=>{for(let t of s)if(e(t))return t;return null},my=s=>{let e=!1,t=(0,Bo.throttleFn)(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var _o=require("@vkontakte/videoplayer-shared");var Co=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var Vo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new _o.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,_o.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!G(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Co(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Fa=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new $.ValueSubject(0);this.currentLowLatencySegmentLength$=new $.ValueSubject(0);this.currentSegmentLength$=new $.ValueSubject(0);this.onLastSegment$=new $.ValueSubject(!1);this.fullyBuffered$=new $.ValueSubject(!1);this.playingRepresentation$=new $.ValueSubject(void 0);this.playingRepresentationInit$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.gaps=[];this.subscription=new $.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;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.sourceBufferBufferedDiff=null;this.startWith=(0,$.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,$.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new cy(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.sourceBufferBufferedDiff=new Vo(this.mediaSource,this.sourceBuffer),this.subscription.add((0,$.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,$.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:$.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!G(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,us(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Be(this.sourceBuffer.buffered,o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"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,$.assertNonNullable)(i,"No init buffer for starting representation"),(0,$.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,$.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,$.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,$.isNullable)(a)||(0,$.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,$.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,$.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,$.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,$.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,$.isNullable)(a)||(0,$.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,$.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,$.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,$.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,No.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!wt(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,$.assertNonNullable)(r,`Representation not found by id ${i}`);let a=this.segments.get(i);(0,$.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,$.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));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,(0,$.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,$.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,$.isNullable)(o)||(0,$.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,$.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!G(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,$.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,$.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 le,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,$.isNullable)(e)||(0,$.isNullable)(this.downloadingRepresentationId)||(0,$.isNullable)(this.playingRepresentationId)||(0,$.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,$.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,$.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,$.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,$.isNullable)(r)||(0,$.isNullable)(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);(0,$.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=Na(i),m=Na(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,$.isNonNullable)(h)&&(0,$.isNonNullable)(m)&&(0,$.isHigher)(h.quality,m.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||v?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let y=[...this.segments.entries()].map(([k,x])=>{let L=x.find(O=>e>=O.time.from&&e<O.time.to);return{representationId:k,status:L?.status}}).find(k=>k.status==="fed")?.representationId;y&&(this.playingRepresentationId=y,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&us(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Be(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Oo.default)(p,n))d="high";else{let h=(0,hr.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&Be(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,hr.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-Be(this.sourceBuffer.buffered,e)<u),this.onLastSegment$.next(e-c.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,$.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?.streams[this.kind];if(!t)return;let i=(0,No.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,No.default)(e.streams[this.kind],i=>i.representations)??[];for(let i of t){if(!i||!wt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,hr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,$.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!wt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=It(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&$t&&$t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&$t&&$t(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:m}},b)=>{let v=h<=i&&m>=i,S=h>i||v||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),k=this.preloadOnly&&h<=i+y||r<y&&m-h>=y||m<=i+y;return(d==="none"||d==="partially_ejected"&&S&&k&&this.sourceBuffer&&G(this.mediaSource,this.sourceBuffer)&&!(et(this.sourceBuffer.buffered,h)&&et(this.sourceBuffer.buffered,m)))&&S&&k});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){wt(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:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,$.abortable)(o,async function*(){let p=(0,$.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=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,$.now)(),!p)return;let c=new DataView(p),d=Mt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Ze(p)||(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())wt(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,$.abortable)(n,async function*(){let u=(0,$.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,$.fromEvent)(window,"online").pipe((0,$.once)()).subscribe(()=>{l(),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,$.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ze(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(wt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,hr.default)(e,0).byte.from,to:(0,hr.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,$.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:$.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!wt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,$.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:$.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Oo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!G(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 l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===d?b:Mt(o.mime).parseFeedableSegmentChunk(b);v?.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,$.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(et(this.sourceBuffer.buffered,e.segment.time.from,100)&&et(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:$.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",qc(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Zt(()=>(0,by.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,$.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,$.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&wt(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:$.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}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||!G(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,$.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{if(a>=t)return;r.push({...o.time});let u=qc(o)?o.size??0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let c of this.segments.values())for(let d of c)(0,Oo.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(u)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=fy(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!G(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||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,$.isNullable)(e)?0:Be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let a=Math.round(r.from),n=Math.round(r.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Zt(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:$.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,$.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,$.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Co(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];u||(u=c-t<=n&&d+t>=o),(n>=c&&n<d-t||o>c+t&&o<=d)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:$.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,hr.default)(e,-1)?.time.to:0)||0}};var X=require("@vkontakte/videoplayer-shared");var Uo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new X.Subject;this.firstBytesManifest$=new X.Subject;this.firstBytesRequested$=new X.Subject;this.firstBytesReceived$=new X.Subject;this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.recoverableError$=new X.Subject;this.error$=new X.Subject;this.abortAllController=new le;this.subscription=new X.SubscriptionRemovable;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=jt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Xr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Fo);return r?(t.log("success",(0,X.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",(0,X.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,X.abortable)(this.abortAllController.signal,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:l=!1}={}){let p=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let A=new URL(p,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),p=A.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(p=jt(p));let h=this.abortAllController.signal,m;if(n){let A=new le;if(m=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{A.abort()}catch(P){Fo(P)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(P){Fo(P)}h=A.signal}let b=0,v=(0,X.now)();d.log("startRequest",(0,X.flattenObject)({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.firstBytesRequested$.next();let S=yield this.doFetch(p,{priority:a,headers:c,signal:h}),y=(0,X.now)();if(!S)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(y-v),!S.ok||!S.body){this.unsubscribeAbortSubscription(m);let A=`Fetch error ${S.status}: ${S.statusText}`;return d.error("error",{message:A}),d.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!o){this.unsubscribeAbortSubscription(m);let A=(0,X.now)(),P={requestStartedAt:v,requestEndedAt:A,duration:A-v};return d.log("endRequest",(0,X.flattenObject)(P)),d.end(),S.arrayBuffer()}let k=S.body;if(o){let A;[k,A]=S.body.tee(),this.throughputEstimator?.trackStream(A,u)}let x=k.getReader(),L,O=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(O)&&(L=O),!L&&i&&(L=i.to-i.from+1);let N=L?new Uint8Array(L):new Uint8Array(0),M=!1,j=A=>{this.unsubscribeAbortSubscription(m),M=!0,Fo(A)},D=(0,X.abortable)(h,async function*({done:A,value:P}){if(b===0&&(this.lastRequestFirstBytes$.next((0,X.now)()-v),this.firstBytesReceived$.next()),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!A&&P){if(l&&L)N.set(P,b),b+=P.byteLength;else{let re=new Uint8Array(N.length+P.length);re.set(N),re.set(P,N.length),N=re,b+=P.byteLength}r?.(new DataView(N.buffer),b),yield x?.read().then(D,j)}}.bind(this));yield x?.read().then(D,j),this.unsubscribeAbortSubscription(m);let se=(0,X.now)(),z={failed:M,requestStartedAt:v,requestEndedAt:se,duration:se-v};return M?(d.error("endRequest",(0,X.flattenObject)(z)),d.end(),null):(d.log("endRequest",(0,X.flattenObject)(z)),d.end(),N.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let v=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,X.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,{priority:t,measureThroughput:!1});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}onHeadersReceived(e){let{type:t,reused:i}=Kr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,X.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await ft(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:X.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:X.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:X.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:X.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:X.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Fo=s=>{if(!Ze(s))throw s};var qo=require("@vkontakte/videoplayer-shared");var Ua=class s{constructor(e,t){this.currentRepresentation$=new qo.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,qo.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of 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?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&wt(t.segmentReference))}};var DM=["progress","play","seeked","stalled","waiting"],BM=["timeupdate","progress","loadeddata","playing","seeked"];var jo=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 te("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.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ae(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.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*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=es(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Yr(e)??{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&rt()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=rs(d),c=n[0]),u==="video"&&(a=is(d),this.forceVideoCodec&&(0,Sy.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>Bi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=ts(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);F.display.isHDR&&d&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}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){this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new T.Subscription,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add((0,T.fromEvent)(d,"error").pipe((0,T.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=$r();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),xi())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}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((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new Fa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Fa("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}Ua.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ua(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,T.merge)(...BM.map(d=>(0,T.fromEvent)(this.element,d))).pipe((0,T.map)(d=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,T.interval)(1e3).subscribe(h=>{let m=Ii(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.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()||ls(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 v=Ii(this.manifestUrlString,2);return(h/2+m+b+v)/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 v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,k=h-v;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(k)>S&&(x=1+Math.sign(k)*y),ls(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let b=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,v=Ii(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),k=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,L=isFinite(h)?h:m,O=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),N=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(N);let M="none";if(O?M="active_low_latency":this.isLowLatency$.getValue()&&N?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),M="active_low_latency"):v!==0&&L<y?M="live_forward_buffering":L<y+x&&(M="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),M==="live_forward_buffering"||M==="live_with_target_offset"){let j=d-(y+k),D=this.normolizeLiveOffset(Math.trunc(v+j/b)),se=Math.abs(D-v),z=0;!h||se<=this.tuning.dashCmafLive.offsetCalculationError?z=v:D>0&&se>this.tuning.dashCmafLive.offsetCalculationError&&(z=D),this.manifestUrlString=Ae(this.manifestUrlString,z,2)}(M==="live_with_target_offset"||M==="live_forward_buffering")&&(d=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 l=(0,T.merge)(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=(0,T.merge)(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=(0,T.combine)({allBuffersFull:l,someBufferEnded:p}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:d,someBufferEnded:h})=>d&&h),(0,T.filter)(d=>d));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(d=>d.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 d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.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)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Hc.default)((0,Hc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),wt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),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 Uo({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.liveBuffer=hi.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);let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ae(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,T.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,T.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,T.merge)(...DM.map(t=>(0,T.fromEvent)(this.element,t)),(0,T.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&et(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=(0,T.now)(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),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?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),et(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",(0,T.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var bt=require("@vkontakte/videoplayer-shared"),Ho=class{constructor(){this.subscription=new bt.Subscription;this.pipSize$=new bt.ValueSubject(void 0);this.videoSize$=new bt.ValueSubject(void 0);this.elementSize$=new bt.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=bt.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,bt.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,bt.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,bt.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 fr=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new te("stopped");this.observableVideo=null;this.droppedFramesManager=new Ri;this.stallsManager=new Wr;this.elementSizeManager=new Ho;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new qt;this.audioTrackSwitchHistory=new qt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.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?.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?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,Q.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Mi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 ct(e.source.url),this.params=e,this.video=Ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(De(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new jo({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,Q.isNullable)(this.observableVideo)&&(this.observableVideo=Xe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Q.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,Q.filter)(c=>!!c.length),(0,Q.once)()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,Q.map)(c=>c.to.state!=="none"),(0,Q.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.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,Q.filter)(Q.isNonNullable),(0,Q.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,Q.map)(c=>c.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(At(this.video,t.isLooped,r)),this.subscription.add(Ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(lt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(pt(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:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if((0,Q.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let v of d.audio){b.push(Fc(v));let S=[];for(let y of v.representations){let k=dy(y);S.push(k),this.audioTracksMap.set(k,{stream:v,representation:y})}this.audioStreamsMap.set(v,S)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of d.video){m.push(Uc(b));let v=[];for(let S of b.representations){let y=Na({...S,streamId:b.id});y&&(v.push(y),this.videoTracksMap.set(y,{stream:b,representation:S}))}this.videoStreamsMap.set(b,v)}this.params.output.availableVideoStreams$.next(m);for(let b of d.text)for(let v of b.representations){let S=py(b,v);this.textTracksMap.set(S,{stream:b,representation:v})}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?.video&&this.params.output.availableVideoCodecs$.next(h.video),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 c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&my(o)||null;this.subscription.add((0,Q.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,Q.fromEvent)(this.video,"progress")).pipe((0,Q.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let b=pr(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===h.id);(0,Q.isNonNullable)(b)&&(this.stallsManager.lastVideoTrackSelected=b);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,S)}},r)),this.subscription.add((0,Q.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,Q.merge)((0,Q.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,Q.map)(c=>c.to)))}).pipe((0,Q.map)(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),(0,Q.filterChanged)()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,Q.filterChanged)()).subscribe(c=>{let d=pr(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,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(Uc(m));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,Q.filterChanged)()).subscribe(c=>{let d=pr(this.audioTracksMap.entries(),([,{representation:v}])=>v.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Fc(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe((0,Q.map)(({to:c})=>c==="ready"),(0,Q.filterChanged)());this.subscription.add((0,Q.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,Q.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,Q.merge)(l,this.player.state$.stateChangeEnded$,(0,Q.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=(0,Q.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ar:sr,t=this.params.tuning.useNewAutoSelectVideoTrack?Hr:jr,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:qr,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=pr(this.videoTracksMap.keys(),M=>M.id===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=pr(this.videoStreamsMap.keys(),M=>M.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=Be(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,v=Math.min(h/Math.min(m,b||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),y=S?.id&&pr(this.audioStreamsMap.keys(),M=>M.id===S.id)||this.audioStreamsMap.keys().next().value,k=0;if(y){if(u&&!n){let M=e(u,d,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);k=Math.max(k,M?.bitrate??-1/0)}if(l){let M=e(l,d,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);k=Math.max(k,M?.bitrate??-1/0)}}let x=u;(n||!x)&&(x=i(d,{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:k,forwardBufferHealth:v,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let L=y&&t(x,d,this.audioStreamsMap.get(y)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),O=this.videoTracksMap.get(x)?.representation,N=L&&this.audioTracksMap.get(L)?.representation;O&&N?(this.selectedRepresentations.video=O,this.selectedRepresentations.audio=N):O&&!N&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=O,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Q.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ye(this.video),this.tracer.end()}};var qa=class extends fr{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 ve=require("@vkontakte/videoplayer-shared");var ja=class extends fr{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 ve.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,ve.filterChanged)()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!u&&!l&&c?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,ve.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,ve.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ve.map)(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,ve.filter)(u=>(0,ve.isNonNullable)(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add((0,ve.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ve.merge)(r.playbackRateState$,new ve.ValueSubject(1))}).pipe((0,ve.filter)(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||(0,ve.isNullable)(p)||(t=u-p)})).add((0,ve.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ve.merge)(r.playbackRateState$,new ve.ValueSubject(1))}).pipe((0,ve.filterChanged)((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||(0,ve.isNullable)(u)||(0,ve.isNullable)(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=hy(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var vy="X-Playback-Duration",zc=async s=>{let e=await ft(s),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(vy)?parseInt(e.headers.get(vy),10):void 0};var ue=require("@vkontakte/videoplayer-shared");var Qc=q(nl(),1);var zo=require("@vkontakte/videoplayer-shared");var VM=s=>{let e=null;if(s.QUALITY&&(e=Xt(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,zo.videoSizeToQuality)({width:t,height:i})}return e??null},_M=(s,e)=>{let t=s.split(`
179
179
  `),i=[],r=[];for(let a=0;a<t.length;a++){let n=t[a],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,Qc.default)(o[1].split(",").map(v=>v.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,c=VM(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[v,S]=l.RESOLUTION.split("x").map(y=>parseInt(y,10));v&&S&&(m={width:v,height:S})}let b=new URL(t[++a],e).toString();c&&i.push({id:p,quality:c,url:b,bandwidth:d,size:m,fps:h})}if(u){let l=(0,Qc.default)(u[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,d=l.NAME;p&&c&&r.push({type:"internal",id:c,label:d,language:c,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},OM=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),Wc=0,yy=async(s,e=s,t,i)=>{let a=await(await ft(s,i)).text();Wc+=1;try{let{qualityManifests:n,textTracks:o}=_M(a,e);return{qualityManifests:n,textTracks:o}}catch{if(Wc<=t.manifestRetryMaxCount)return await OM((0,zo.getExponentialDelay)(Wc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),yy(s,e,t)}return{qualityManifests:[],textTracks:[]}},Wo=yy;var xt=require("@vkontakte/videoplayer-shared");var Qo=class{constructor(e,t,i,r,a){this.subscription=new xt.Subscription;this.abortControllers={destroy:new le,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new xt.ValueSubject(null);this.getCurrentTime$=new xt.ValueSubject(null);this.error$=new xt.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe((0,xt.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 ft(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],l=new URL(u,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+p},url:l}),a=a+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,xt.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 le;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(){let e=this.prepareUrl??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:xt.ErrorCategory.WTF,thrown:t,message:e})}};var Ha=class{constructor(e){this.subscription=new ue.Subscription;this.videoState=new te("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ue.ValueSubject([]);this.liveOffset=new ir;this.manifestStartTime$=new ue.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.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 l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?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?.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 p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,ue.assertNever)(t)}};this.params=e,this.video=Ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ue.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,r)=>Wo(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Qo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ct(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ue.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:ue.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(De(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ue.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:ue.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.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(Ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(lt(this.video,t.playbackRate,r.playbackRateState$,i)),a(pt(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(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,ue.filterChanged)(),(0,ue.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ue.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(De(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.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(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,ue.combine)({startTime:this.manifestStartTime$.pipe((0,ue.filter)(ue.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,ue.map)(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,ue.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Ye(this.video)}prepare(){let e=this.selectManifest();if((0,ue.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,p]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ae(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),zc(n).then(o=>{if(!(0,ue.isNullable)(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();((0,ue.isNullable)(u)||!isFinite(u))&&ft(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,n).toString();zc(c).then(d=>{(0,ue.isNullable)(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ue.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=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 fe=require("@vkontakte/videoplayer-shared");var za=class{constructor(e){this.subscription=new fe.Subscription;this.videoState=new te("stopped");this.manifests$=new fe.ValueSubject([]);this.unmuteAfterBrowserResetsHappened=new fe.ValueSubject(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),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 l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.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?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,fe.assertNever)(t)}};this.textTracksManager=new ct(e.source.url),this.params=e,this.video=Ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:fe.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(De(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Wo(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:fe.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"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(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:fe.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.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,fe.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(At(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(lt(this.video,t.playbackRate,r.playbackRateState$,i)),Di({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ke(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(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,fe.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(b=>b.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(De(m.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe((0,fe.map)(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!F.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,fe.merge)((0,fe.fromEvent)(o,"addtrack"),(0,fe.fromEvent)(o,"removetrack"),(0,fe.fromEvent)(o,"change"),(0,fe.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,fe.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,fe.observableFrom)(["init"])).pipe((0,fe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ye(this.video)}prepare(){let e=this.selectManifest();if((0,fe.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:a,min:n}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Ty=q(ki(),1),Gc=q(Yi(),1),Iy=q(dt(),1);var Ie=require("@vkontakte/videoplayer-shared");var Wa=class{constructor(e){this.subscription=new Ie.Subscription;this.videoState=new te("stopped");this.trackUrls={};this.textTracksManager=new ct;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?.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?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,Ie.assertNever)(e)}};this.params=e,this.video=Ge(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Ty.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Gc.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:Ie.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.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,Ie.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(At(this.video,t.isLooped,i)),Di({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(lt(this.video,t.playbackRate,r.playbackRateState$,i)),a(pt(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(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,Ie.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(u),p.playbackRate=u)}}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,Ie.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Ie.observableFrom)(["init"])).pipe((0,Ie.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ye(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,Ie.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,Ie.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=jt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(De(t))}playIfAllowed(){Je(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:Ie.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){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=Rt(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=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),n=(0,Gc.default)(this.trackUrls).map(l=>l.track);if(!r||!a||Fr(e,n[0].quality,(0,Iy.default)(n,-1)?.quality)){i();return}let o=e.max?(0,Ie.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,Ie.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var Ee=require("@vkontakte/videoplayer-shared");var wy=require("@vkontakte/videoplayer-shared"),Ey=["stun:videostun.mycdn.me:80"],NM=1e3,FM=3,Yc=()=>null,Go=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=Yc;this.externalStopCallback=Yc;this.externalErrorCallback=Yc;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:Ey}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=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:wy.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{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),NM)}normalizeOptions(e={}){let t={stunServerList:Ey,maxRetryNumber:FM,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Qa=class{constructor(e){this.videoState=new te("stopped");this.maxSeekBackTime$=new Ee.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.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?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,Ee.assertNever)(e)}};this.subscription=new Ee.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ge(e.container,e.tuning),this.liveStreamClient=new Go(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ye(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ee.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,Ee.merge)(this.videoState.stateChangeStarted$.pipe((0,Ee.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Ee.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Xe(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(pt(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(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ke(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,Ee.assertNever)(n.to)}},i)).add((0,Ee.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Ee.observableFrom)(["init"])).pipe((0,Ee.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(De(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Ee.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:Ee.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Je(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),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}))}prepare(){this.liveStreamClient.connect()}};var cs=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};var w=require("@vkontakte/videoplayer-shared");var fi=require("@vkontakte/videoplayer-shared");var xy=s=>new fi.Observable(e=>{let t=new fi.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe((0,fi.map)(({from:l,to:p})=>`${l}-${p}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe((0,fi.map)(({type:l})=>l!==void 0)),n=new fi.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval),Z({m:"hangup.set",l,id:o})})),t.add(r.subscribe(()=>{Z({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(Z({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval),Z({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Lt=require("@vkontakte/videoplayer-shared");function ky(){return new(window.AudioContext||window.webkitAudioContext)}var ds=class s{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new le;this.subscriptions=new Lt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Lt.filter)(a=>!!a.type),(0,Lt.once)()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){F.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Lt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Lt.filter)(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),(0,Lt.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=ky();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){this.volumeMultiplierError$.next({id:s.errorId,category:Lt.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${s.errorId} exception`,thrown:e})}};var UM={chunkDuration:5e3,maxParallelRequests:5},Ga=class{constructor(e){this.current$=new w.ValueSubject({type:void 0});this.providerError$=new w.Subject;this.noAvailableProvidersError$=new w.Subject;this.volumeMultiplierError$=new w.Subject;this.providerOutput={position$:new w.ValueSubject(0),duration$:new w.ValueSubject(1/0),volume$:new w.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new w.ValueSubject([]),currentVideoStream$:new w.ValueSubject(void 0),availableVideoTracks$:new w.ValueSubject([]),currentVideoTrack$:new w.ValueSubject(void 0),availableVideoCodecs$:new w.ValueSubject([]),availableAudioStreams$:new w.ValueSubject([]),currentAudioStream$:new w.ValueSubject(void 0),availableAudioTracks$:new w.ValueSubject([]),availableAudioCodecs$:new w.ValueSubject([]),currentVideoSegmentLength$:new w.ValueSubject(0),currentAudioSegmentLength$:new w.ValueSubject(0),isAudioAvailable$:new w.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new w.ValueSubject(!1),autoVideoTrackLimits$:new w.ValueSubject(void 0),currentBuffer$:new w.ValueSubject(void 0),currentNativeBuffer$:new w.ValueSubject(void 0),isBuffering$:new w.ValueSubject(!0),error$:new w.Subject,fetcherError$:new w.Subject,fetcherRecoverableError$:new w.Subject,warning$:new w.Subject,willSeekEvent$:new w.Subject,soundProhibitedEvent$:new w.Subject,seekedEvent$:new w.Subject,loopedEvent$:new w.Subject,endedEvent$:new w.Subject,manifestRequested$:new w.Subject,firstBytesManifest$:new w.Subject,manifestReceived$:new w.Subject,firstBytesRequested$:new w.Subject,firstBytesReceived$:new w.Subject,firstBytesEvent$:new w.Subject,loadedMetadataEvent$:new w.Subject,firstFrameEvent$:new w.Subject,canplay$:new w.Subject,isLive$:new w.ValueSubject(void 0),isLiveEnded$:new w.ValueSubject(null),canPlayLiveTailBuffer$:new w.ValueSubject(!1),isLowLatency$:new w.ValueSubject(!1),canChangePlaybackSpeed$:new w.ValueSubject(!0),liveTime$:new w.ValueSubject(void 0),liveBufferTime$:new w.ValueSubject(void 0),liveLatency$:new w.ValueSubject(void 0),severeStallOccurred$:new w.Subject,availableTextTracks$:new w.ValueSubject([]),currentTextTrack$:new w.ValueSubject(void 0),hostname$:new w.ValueSubject(void 0),httpConnectionType$:new w.ValueSubject(void 0),httpConnectionReused$:new w.ValueSubject(void 0),inPiP$:new w.ValueSubject(!1),inFullscreen$:new w.ValueSubject(!1),element$:new w.ValueSubject(void 0),elementVisible$:new w.ValueSubject(!0),availableSources$:new w.ValueSubject(void 0),is3DVideo$:new w.ValueSubject(!1),playbackState$:new w.ValueSubject(""),getCurrentTime$:new w.ValueSubject(null)};this.subscription=new w.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Ou([...Vv(this.params.tuning),...Cv(this.params.tuning)]).filter(l=>(0,w.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Kc.default)(r,l)),...t.filter(l=>(0,Kc.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",(0,w.flattenObject)(a)),this.screenFormatsIterator=new cs(a);let n=[...Ac(!0),...Ac(!1)];this.chromecastFormatsIterator=new cs(n.filter(l=>(0,w.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ds.isSupported()&&(this.volumeMultiplierManager=new ds(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){Z.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 cs(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,w.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:w.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let 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,w.assertNever)(e)}}createScreenProvider(e){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 u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,w.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new qa({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtual&&!F.device.isMobile?new os({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&F.device.isMobile?new os({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new _a({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new ja({...o,source:u}):new Oa({...o,source:u})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),new za({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),new Ha({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),new Wa({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),new zg({...o,source:u,config:{...UM,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,w.assertNonNullable)(u),new Qa({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,w.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta: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 si){let{chromecastConnector:l}=this.params.dependencies.chromecastInitializer;return(0,w.assertNonNullable)(l),new Ls({...o,chromecastConnector:l})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,w.assertNonNullable)(u),new Ws({...o,connection:u})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,w.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,w.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,w.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let 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,Py.default)((0,Xc.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new w.Subscription,t=!1,i=0;e.add((0,w.merge)(this.providerOutput.error$.pipe((0,w.filter)(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),xy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,w.map)(a=>({id:`ProviderHangup:${a}`,category:w.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,w.filter)(({to:n})=>n==="playing"),(0,w.once)()).subscribe(()=>t=!0);e.add(a)}));let r=()=>{let a=Z.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&(0,w.getWindow)().console.log(`===== DASH_LIVE DEBUG START ====
181
181
  `,a.map(({time:u,data:l,stack:p})=>`${u}: ${JSON.stringify(l)}${p?`