@vkontakte/videoplayer-core 2.0.150-dev.10447541.0 → 2.0.150-dev.169e8a40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs +44 -44
- package/es2015.esm.js +42 -42
- package/es2018.cjs +34 -34
- package/es2018.esm.js +39 -39
- package/es2024.cjs +55 -55
- package/es2024.esm.js +46 -46
- package/esnext.cjs +55 -55
- package/esnext.esm.js +46 -46
- package/evergreen.esm.js +62 -62
- package/package.json +2 -2
- package/types/player/Player.d.ts +1 -0
- package/types/player/types.d.ts +1 -0
- package/types/utils/tuningConfig.d.ts +4 -4
- package/types/providers/DashProviderNew/baseDashProvider.d.ts +0 -61
- package/types/providers/DashProviderNew/consts.d.ts +0 -3
- package/types/providers/DashProviderNew/index.d.ts +0 -2
- package/types/providers/DashProviderNew/lib/ElementSizeManager.d.ts +0 -19
- package/types/providers/DashProviderNew/lib/LiveTextManager.d.ts +0 -23
- package/types/providers/DashProviderNew/lib/buffer.d.ts +0 -130
- package/types/providers/DashProviderNew/lib/fetcher.d.ts +0 -64
- package/types/providers/DashProviderNew/lib/player.d.ts +0 -107
- package/types/providers/DashProviderNew/lib/sourceBufferBufferedDiff.d.ts +0 -19
- package/types/providers/DashProviderNew/lib/sourceBufferTaskQueue.d.ts +0 -20
- package/types/providers/DashProviderNew/lib/types.d.ts +0 -29
- package/types/providers/DashProviderNew/lib/utils.d.ts +0 -24
- package/types/providers/DashProviderNew/newDashCmafLiveProvider.d.ts +0 -8
- package/types/providers/DashProviderNew/newDashProvider.d.ts +0 -6
package/es2018.esm.js
CHANGED
|
@@ -1,85 +1,85 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.150-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.150-dev.169e8a40.0
|
|
3
|
+
* Thu, 15 Jan 2026 09:31:09 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-150/doc/
|
|
5
5
|
*/
|
|
6
|
-
var nP=Object.create;var Ef=Object.defineProperty;var oP=Object.getOwnPropertyDescriptor;var uP=Object.getOwnPropertyNames;var lP=Object.getPrototypeOf,cP=Object.prototype.hasOwnProperty;var S=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var dP=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of uP(e))!cP.call(a,r)&&r!==t&&Ef(a,r,{get:()=>e[r],enumerable:!(i=oP(e,r))||i.enumerable});return a};var O=(a,e,t)=>(t=a!=null?nP(lP(a)):{},dP(e||!a||!a.__esModule?Ef(t,"default",{value:a,enumerable:!0}):t,a));var oe=S((wl,xf)=>{"use strict";var Os=function(a){return a&&a.Math===Math&&a};xf.exports=Os(typeof globalThis=="object"&&globalThis)||Os(typeof window=="object"&&window)||Os(typeof self=="object"&&self)||Os(typeof global=="object"&&global)||Os(typeof wl=="object"&&wl)||function(){return this}()||Function("return this")()});var ve=S((zF,Pf)=>{"use strict";Pf.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ns=S((QF,kf)=>{"use strict";var pP=ve();kf.exports=!pP(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var xl=S((GF,Mf)=>{"use strict";var hP=Ns(),$f=Function.prototype,Af=$f.apply,Rf=$f.call;Mf.exports=typeof Reflect=="object"&&Reflect.apply||(hP?Rf.bind(Af):function(){return Rf.apply(Af,arguments)})});var ye=S((YF,Bf)=>{"use strict";var Lf=Ns(),Df=Function.prototype,Pl=Df.call,fP=Lf&&Df.bind.bind(Pl,Pl);Bf.exports=Lf?fP:function(a){return function(){return Pl.apply(a,arguments)}}});var Oi=S((KF,Vf)=>{"use strict";var Cf=ye(),mP=Cf({}.toString),bP=Cf("".slice);Vf.exports=function(a){return bP(mP(a),8,-1)}});var kl=S((XF,_f)=>{"use strict";var gP=Oi(),SP=ye();_f.exports=function(a){if(gP(a)==="Function")return SP(a)}});var ue=S((JF,Of)=>{"use strict";var Al=typeof document=="object"&&document.all;Of.exports=typeof Al=="undefined"&&Al!==void 0?function(a){return typeof a=="function"||a===Al}:function(a){return typeof a=="function"}});var Ze=S((ZF,Nf)=>{"use strict";var vP=ve();Nf.exports=!vP(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var et=S((eU,Ff)=>{"use strict";var yP=Ns(),oo=Function.prototype.call;Ff.exports=yP?oo.bind(oo):function(){return oo.apply(oo,arguments)}});var Rl=S(jf=>{"use strict";var Uf={}.propertyIsEnumerable,qf=Object.getOwnPropertyDescriptor,TP=qf&&!Uf.call({1:2},1);jf.f=TP?function(e){var t=qf(this,e);return!!t&&t.enumerable}:Uf});var Fs=S((iU,Hf)=>{"use strict";Hf.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var zf=S((rU,Wf)=>{"use strict";var IP=ye(),EP=ve(),wP=Oi(),$l=Object,xP=IP("".split);Wf.exports=EP(function(){return!$l("z").propertyIsEnumerable(0)})?function(a){return wP(a)==="String"?xP(a,""):$l(a)}:$l});var Us=S((sU,Qf)=>{"use strict";Qf.exports=function(a){return a==null}});var ui=S((aU,Gf)=>{"use strict";var PP=Us(),kP=TypeError;Gf.exports=function(a){if(PP(a))throw new kP("Can't call method on "+a);return a}});var Ni=S((nU,Yf)=>{"use strict";var AP=zf(),RP=ui();Yf.exports=function(a){return AP(RP(a))}});var ze=S((oU,Kf)=>{"use strict";var $P=ue();Kf.exports=function(a){return typeof a=="object"?a!==null:$P(a)}});var Fi=S((uU,Xf)=>{"use strict";Xf.exports={}});var Ft=S((lU,Zf)=>{"use strict";var Ml=Fi(),Ll=oe(),MP=ue(),Jf=function(a){return MP(a)?a:void 0};Zf.exports=function(a,e){return arguments.length<2?Jf(Ml[a])||Jf(Ll[a]):Ml[a]&&Ml[a][e]||Ll[a]&&Ll[a][e]}});var qs=S((cU,em)=>{"use strict";var LP=ye();em.exports=LP({}.isPrototypeOf)});var Ui=S((dU,rm)=>{"use strict";var DP=oe(),tm=DP.navigator,im=tm&&tm.userAgent;rm.exports=im?String(im):""});var Bl=S((pU,lm)=>{"use strict";var um=oe(),Dl=Ui(),sm=um.process,am=um.Deno,nm=sm&&sm.versions||am&&am.version,om=nm&&nm.v8,mt,uo;om&&(mt=om.split("."),uo=mt[0]>0&&mt[0]<4?1:+(mt[0]+mt[1]));!uo&&Dl&&(mt=Dl.match(/Edge\/(\d+)/),(!mt||mt[1]>=74)&&(mt=Dl.match(/Chrome\/(\d+)/),mt&&(uo=+mt[1])));lm.exports=uo});var Cl=S((hU,dm)=>{"use strict";var cm=Bl(),BP=ve(),CP=oe(),VP=CP.String;dm.exports=!!Object.getOwnPropertySymbols&&!BP(function(){var a=Symbol("symbol detection");return!VP(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&cm&&cm<41})});var Vl=S((fU,pm)=>{"use strict";var _P=Cl();pm.exports=_P&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var _l=S((mU,hm)=>{"use strict";var OP=Ft(),NP=ue(),FP=qs(),UP=Vl(),qP=Object;hm.exports=UP?function(a){return typeof a=="symbol"}:function(a){var e=OP("Symbol");return NP(e)&&FP(e.prototype,qP(a))}});var js=S((bU,fm)=>{"use strict";var jP=String;fm.exports=function(a){try{return jP(a)}catch(e){return"Object"}}});var At=S((gU,mm)=>{"use strict";var HP=ue(),WP=js(),zP=TypeError;mm.exports=function(a){if(HP(a))return a;throw new zP(WP(a)+" is not a function")}});var Hs=S((SU,bm)=>{"use strict";var QP=At(),GP=Us();bm.exports=function(a,e){var t=a[e];return GP(t)?void 0:QP(t)}});var Sm=S((vU,gm)=>{"use strict";var Ol=et(),Nl=ue(),Fl=ze(),YP=TypeError;gm.exports=function(a,e){var t,i;if(e==="string"&&Nl(t=a.toString)&&!Fl(i=Ol(t,a))||Nl(t=a.valueOf)&&!Fl(i=Ol(t,a))||e!=="string"&&Nl(t=a.toString)&&!Fl(i=Ol(t,a)))return i;throw new YP("Can't convert object to primitive value")}});var bt=S((yU,vm)=>{"use strict";vm.exports=!0});var Im=S((TU,Tm)=>{"use strict";var ym=oe(),KP=Object.defineProperty;Tm.exports=function(a,e){try{KP(ym,a,{value:e,configurable:!0,writable:!0})}catch(t){ym[a]=e}return e}});var Ws=S((IU,xm)=>{"use strict";var XP=bt(),JP=oe(),ZP=Im(),Em="__core-js_shared__",wm=xm.exports=JP[Em]||ZP(Em,{});(wm.versions||(wm.versions=[])).push({version:"3.43.0",mode:XP?"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 Ul=S((EU,km)=>{"use strict";var Pm=Ws();km.exports=function(a,e){return Pm[a]||(Pm[a]=e||{})}});var kr=S((wU,Am)=>{"use strict";var ek=ui(),tk=Object;Am.exports=function(a){return tk(ek(a))}});var gt=S((xU,Rm)=>{"use strict";var ik=ye(),rk=kr(),sk=ik({}.hasOwnProperty);Rm.exports=Object.hasOwn||function(e,t){return sk(rk(e),t)}});var ql=S((PU,$m)=>{"use strict";var ak=ye(),nk=0,ok=Math.random(),uk=ak(1.1.toString);$m.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+uk(++nk+ok,36)}});var Ae=S((kU,Lm)=>{"use strict";var lk=oe(),ck=Ul(),Mm=gt(),dk=ql(),pk=Cl(),hk=Vl(),Ar=lk.Symbol,jl=ck("wks"),fk=hk?Ar.for||Ar:Ar&&Ar.withoutSetter||dk;Lm.exports=function(a){return Mm(jl,a)||(jl[a]=pk&&Mm(Ar,a)?Ar[a]:fk("Symbol."+a)),jl[a]}});var Vm=S((AU,Cm)=>{"use strict";var mk=et(),Dm=ze(),Bm=_l(),bk=Hs(),gk=Sm(),Sk=Ae(),vk=TypeError,yk=Sk("toPrimitive");Cm.exports=function(a,e){if(!Dm(a)||Bm(a))return a;var t=bk(a,yk),i;if(t){if(e===void 0&&(e="default"),i=mk(t,a,e),!Dm(i)||Bm(i))return i;throw new vk("Can't convert object to primitive value")}return e===void 0&&(e="number"),gk(a,e)}});var Hl=S((RU,_m)=>{"use strict";var Tk=Vm(),Ik=_l();_m.exports=function(a){var e=Tk(a,"string");return Ik(e)?e:e+""}});var lo=S(($U,Nm)=>{"use strict";var Ek=oe(),Om=ze(),Wl=Ek.document,wk=Om(Wl)&&Om(Wl.createElement);Nm.exports=function(a){return wk?Wl.createElement(a):{}}});var zl=S((MU,Fm)=>{"use strict";var xk=Ze(),Pk=ve(),kk=lo();Fm.exports=!xk&&!Pk(function(){return Object.defineProperty(kk("div"),"a",{get:function(){return 7}}).a!==7})});var jm=S(qm=>{"use strict";var Ak=Ze(),Rk=et(),$k=Rl(),Mk=Fs(),Lk=Ni(),Dk=Hl(),Bk=gt(),Ck=zl(),Um=Object.getOwnPropertyDescriptor;qm.f=Ak?Um:function(e,t){if(e=Lk(e),t=Dk(t),Ck)try{return Um(e,t)}catch(i){}if(Bk(e,t))return Mk(!Rk($k.f,e,t),e[t])}});var Ql=S((DU,Hm)=>{"use strict";var Vk=ve(),_k=ue(),Ok=/#|\.prototype\./,zs=function(a,e){var t=Fk[Nk(a)];return t===qk?!0:t===Uk?!1:_k(e)?Vk(e):!!e},Nk=zs.normalize=function(a){return String(a).replace(Ok,".").toLowerCase()},Fk=zs.data={},Uk=zs.NATIVE="N",qk=zs.POLYFILL="P";Hm.exports=zs});var Rr=S((BU,zm)=>{"use strict";var Wm=kl(),jk=At(),Hk=Ns(),Wk=Wm(Wm.bind);zm.exports=function(a,e){return jk(a),e===void 0?a:Hk?Wk(a,e):function(){return a.apply(e,arguments)}}});var Gl=S((CU,Qm)=>{"use strict";var zk=Ze(),Qk=ve();Qm.exports=zk&&Qk(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Rt=S((VU,Gm)=>{"use strict";var Gk=ze(),Yk=String,Kk=TypeError;Gm.exports=function(a){if(Gk(a))return a;throw new Kk(Yk(a)+" is not an object")}});var qi=S(Km=>{"use strict";var Xk=Ze(),Jk=zl(),Zk=Gl(),co=Rt(),Ym=Hl(),eA=TypeError,Yl=Object.defineProperty,tA=Object.getOwnPropertyDescriptor,Kl="enumerable",Xl="configurable",Jl="writable";Km.f=Xk?Zk?function(e,t,i){if(co(e),t=Ym(t),co(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Jl in i&&!i[Jl]){var r=tA(e,t);r&&r[Jl]&&(e[t]=i.value,i={configurable:Xl in i?i[Xl]:r[Xl],enumerable:Kl in i?i[Kl]:r[Kl],writable:!1})}return Yl(e,t,i)}:Yl:function(e,t,i){if(co(e),t=Ym(t),co(i),Jk)try{return Yl(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new eA("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var $r=S((OU,Xm)=>{"use strict";var iA=Ze(),rA=qi(),sA=Fs();Xm.exports=iA?function(a,e,t){return rA.f(a,e,sA(1,t))}:function(a,e,t){return a[e]=t,a}});var pe=S((NU,Zm)=>{"use strict";var Qs=oe(),aA=xl(),nA=kl(),oA=ue(),uA=jm().f,lA=Ql(),Mr=Fi(),cA=Rr(),Lr=$r(),Jm=gt();Ws();var dA=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return aA(a,this,arguments)};return e.prototype=a.prototype,e};Zm.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Qs:r?Qs[t]:Qs[t]&&Qs[t].prototype,o=i?Mr:Mr[t]||Lr(Mr,t,{})[t],u=o.prototype,l,d,c,p,h,f,m,g,b;for(p in e)l=lA(i?p:t+(r?".":"#")+p,a.forced),d=!l&&n&&Jm(n,p),f=o[p],d&&(a.dontCallGetSet?(b=uA(n,p),m=b&&b.value):m=n[p]),h=d&&m?m:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&d?g=cA(h,Qs):a.wrap&&d?g=dA(h):s&&oA(h)?g=nA(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Lr(g,"sham",!0),Lr(o,p,g),s&&(c=t+"Prototype",Jm(Mr,c)||Lr(Mr,c,{}),Lr(Mr[c],p,h),a.real&&u&&(l||!u[p])&&Lr(u,p,h)))}});var po=S((FU,tb)=>{"use strict";var pA=Ul(),hA=ql(),eb=pA("keys");tb.exports=function(a){return eb[a]||(eb[a]=hA(a))}});var rb=S((UU,ib)=>{"use strict";var fA=ve();ib.exports=!fA(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ho=S((qU,ab)=>{"use strict";var mA=gt(),bA=ue(),gA=kr(),SA=po(),vA=rb(),sb=SA("IE_PROTO"),Zl=Object,yA=Zl.prototype;ab.exports=vA?Zl.getPrototypeOf:function(a){var e=gA(a);if(mA(e,sb))return e[sb];var t=e.constructor;return bA(t)&&e instanceof t?t.prototype:e instanceof Zl?yA:null}});var ob=S((jU,nb)=>{"use strict";var TA=Math.ceil,IA=Math.floor;nb.exports=Math.trunc||function(e){var t=+e;return(t>0?IA:TA)(t)}});var Gs=S((HU,ub)=>{"use strict";var EA=ob();ub.exports=function(a){var e=+a;return e!==e||e===0?0:EA(e)}});var cb=S((WU,lb)=>{"use strict";var wA=Gs(),xA=Math.max,PA=Math.min;lb.exports=function(a,e){var t=wA(a);return t<0?xA(t+e,0):PA(t,e)}});var ec=S((zU,db)=>{"use strict";var kA=Gs(),AA=Math.min;db.exports=function(a){var e=kA(a);return e>0?AA(e,9007199254740991):0}});var Dr=S((QU,pb)=>{"use strict";var RA=ec();pb.exports=function(a){return RA(a.length)}});var tc=S((GU,fb)=>{"use strict";var $A=Ni(),MA=cb(),LA=Dr(),hb=function(a){return function(e,t,i){var r=$A(e),s=LA(r);if(s===0)return!a&&-1;var n=MA(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};fb.exports={includes:hb(!0),indexOf:hb(!1)}});var fo=S((YU,mb)=>{"use strict";mb.exports={}});var Sb=S((KU,gb)=>{"use strict";var DA=ye(),ic=gt(),BA=Ni(),CA=tc().indexOf,VA=fo(),bb=DA([].push);gb.exports=function(a,e){var t=BA(a),i=0,r=[],s;for(s in t)!ic(VA,s)&&ic(t,s)&&bb(r,s);for(;e.length>i;)ic(t,s=e[i++])&&(~CA(r,s)||bb(r,s));return r}});var rc=S((XU,vb)=>{"use strict";vb.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var sc=S((JU,yb)=>{"use strict";var _A=Sb(),OA=rc();yb.exports=Object.keys||function(e){return _A(e,OA)}});var ac=S((ZU,xb)=>{"use strict";var Ib=Ze(),NA=ve(),Eb=ye(),FA=ho(),UA=sc(),qA=Ni(),jA=Rl().f,wb=Eb(jA),HA=Eb([].push),WA=Ib&&NA(function(){var a=Object.create(null);return a[2]=2,!wb(a,2)}),Tb=function(a){return function(e){for(var t=qA(e),i=UA(t),r=WA&&FA(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Ib||(r?u in t:wb(t,u)))&&HA(o,a?[u,t[u]]:t[u]);return o}};xb.exports={entries:Tb(!0),values:Tb(!1)}});var Pb=S(()=>{"use strict";var zA=pe(),QA=ac().values;zA({target:"Object",stat:!0},{values:function(e){return QA(e)}})});var Ab=S((iq,kb)=>{"use strict";Pb();var GA=Fi();kb.exports=GA.Object.values});var $b=S((rq,Rb)=>{"use strict";var YA=Ab();Rb.exports=YA});var ji=S((sq,Mb)=>{"use strict";var KA=$b();Mb.exports=KA});var Ys=S((aq,Lb)=>{"use strict";Lb.exports=function(){}});var Db=S(()=>{"use strict";var XA=pe(),JA=tc().includes,ZA=ve(),eR=Ys(),tR=ZA(function(){return!Array(1).includes()});XA({target:"Array",proto:!0,forced:tR},{includes:function(e){return JA(this,e,arguments.length>1?arguments[1]:void 0)}});eR("includes")});var li=S((uq,Bb)=>{"use strict";var iR=Ft();Bb.exports=iR});var Vb=S((lq,Cb)=>{"use strict";Db();var rR=li();Cb.exports=rR("Array","includes")});var Ob=S((cq,_b)=>{"use strict";var sR=Vb();_b.exports=sR});var Re=S((dq,Nb)=>{"use strict";var aR=Ob();Nb.exports=aR});var pg=S(()=>{"use strict";var jR=pe(),HR=ac().entries;jR({target:"Object",stat:!0},{entries:function(e){return HR(e)}})});var fg=S((dj,hg)=>{"use strict";pg();var WR=Fi();hg.exports=WR.Object.entries});var bg=S((pj,mg)=>{"use strict";var zR=fg();mg.exports=zR});var pi=S((hj,gg)=>{"use strict";var QR=bg();gg.exports=QR});var zi=S((fj,Sg)=>{"use strict";Sg.exports={}});var Tg=S((mj,yg)=>{"use strict";var GR=oe(),YR=ue(),vg=GR.WeakMap;yg.exports=YR(vg)&&/native code/.test(String(vg))});var Ec=S((bj,wg)=>{"use strict";var KR=Tg(),Eg=oe(),XR=ze(),JR=$r(),yc=gt(),Tc=Ws(),ZR=po(),e$=fo(),Ig="Object already initialized",Ic=Eg.TypeError,t$=Eg.WeakMap,xo,ea,Po,i$=function(a){return Po(a)?ea(a):xo(a,{})},r$=function(a){return function(e){var t;if(!XR(e)||(t=ea(e)).type!==a)throw new Ic("Incompatible receiver, "+a+" required");return t}};KR||Tc.state?(vt=Tc.state||(Tc.state=new t$),vt.get=vt.get,vt.has=vt.has,vt.set=vt.set,xo=function(a,e){if(vt.has(a))throw new Ic(Ig);return e.facade=a,vt.set(a,e),e},ea=function(a){return vt.get(a)||{}},Po=function(a){return vt.has(a)}):(Qi=ZR("state"),e$[Qi]=!0,xo=function(a,e){if(yc(a,Qi))throw new Ic(Ig);return e.facade=a,JR(a,Qi,e),e},ea=function(a){return yc(a,Qi)?a[Qi]:{}},Po=function(a){return yc(a,Qi)});var vt,Qi;wg.exports={set:xo,get:ea,has:Po,enforce:i$,getterFor:r$}});var Pc=S((gj,Pg)=>{"use strict";var wc=Ze(),s$=gt(),xg=Function.prototype,a$=wc&&Object.getOwnPropertyDescriptor,xc=s$(xg,"name"),n$=xc&&function(){}.name==="something",o$=xc&&(!wc||wc&&a$(xg,"name").configurable);Pg.exports={EXISTS:xc,PROPER:n$,CONFIGURABLE:o$}});var Ag=S(kg=>{"use strict";var u$=Ze(),l$=Gl(),c$=qi(),d$=Rt(),p$=Ni(),h$=sc();kg.f=u$&&!l$?Object.defineProperties:function(e,t){d$(e);for(var i=p$(t),r=h$(t),s=r.length,n=0,o;s>n;)c$.f(e,o=r[n++],i[o]);return e}});var kc=S((vj,Rg)=>{"use strict";var f$=Ft();Rg.exports=f$("document","documentElement")});var Mc=S((yj,Vg)=>{"use strict";var m$=Rt(),b$=Ag(),$g=rc(),g$=fo(),S$=kc(),v$=lo(),y$=po(),Mg=">",Lg="<",Rc="prototype",$c="script",Bg=y$("IE_PROTO"),Ac=function(){},Cg=function(a){return Lg+$c+Mg+a+Lg+"/"+$c+Mg},Dg=function(a){a.write(Cg("")),a.close();var e=a.parentWindow.Object;return a=null,e},T$=function(){var a=v$("iframe"),e="java"+$c+":",t;return a.style.display="none",S$.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Cg("document.F=Object")),t.close(),t.F},ko,Ao=function(){try{ko=new ActiveXObject("htmlfile")}catch(e){}Ao=typeof document!="undefined"?document.domain&&ko?Dg(ko):T$():Dg(ko);for(var a=$g.length;a--;)delete Ao[Rc][$g[a]];return Ao()};g$[Bg]=!0;Vg.exports=Object.create||function(e,t){var i;return e!==null?(Ac[Rc]=m$(e),i=new Ac,Ac[Rc]=null,i[Bg]=e):i=Ao(),t===void 0?i:b$.f(i,t)}});var _r=S((Tj,_g)=>{"use strict";var I$=$r();_g.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:I$(a,e,t),a}});var Cc=S((Ij,Fg)=>{"use strict";var E$=ve(),w$=ue(),x$=ze(),P$=Mc(),Og=ho(),k$=_r(),A$=Ae(),R$=bt(),Bc=A$("iterator"),Ng=!1,qt,Lc,Dc;[].keys&&(Dc=[].keys(),"next"in Dc?(Lc=Og(Og(Dc)),Lc!==Object.prototype&&(qt=Lc)):Ng=!0);var $$=!x$(qt)||E$(function(){var a={};return qt[Bc].call(a)!==a});$$?qt={}:R$&&(qt=P$(qt));w$(qt[Bc])||k$(qt,Bc,function(){return this});Fg.exports={IteratorPrototype:qt,BUGGY_SAFARI_ITERATORS:Ng}});var Ro=S((Ej,qg)=>{"use strict";var M$=Ae(),L$=M$("toStringTag"),Ug={};Ug[L$]="z";qg.exports=String(Ug)==="[object z]"});var ta=S((wj,jg)=>{"use strict";var D$=Ro(),B$=ue(),$o=Oi(),C$=Ae(),V$=C$("toStringTag"),_$=Object,O$=$o(function(){return arguments}())==="Arguments",N$=function(a,e){try{return a[e]}catch(t){}};jg.exports=D$?$o:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=N$(e=_$(a),V$))=="string"?t:O$?$o(e):(i=$o(e))==="Object"&&B$(e.callee)?"Arguments":i}});var Wg=S((xj,Hg)=>{"use strict";var F$=Ro(),U$=ta();Hg.exports=F$?{}.toString:function(){return"[object "+U$(this)+"]"}});var ia=S((Pj,Qg)=>{"use strict";var q$=Ro(),j$=qi().f,H$=$r(),W$=gt(),z$=Wg(),Q$=Ae(),zg=Q$("toStringTag");Qg.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(W$(r,zg)||j$(r,zg,{configurable:!0,value:e}),i&&!q$&&H$(r,"toString",z$))}});var Yg=S((kj,Gg)=>{"use strict";var G$=Cc().IteratorPrototype,Y$=Mc(),K$=Fs(),X$=ia(),J$=zi(),Z$=function(){return this};Gg.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=Y$(G$,{next:K$(+!i,t)}),X$(a,r,!1,!0),J$[r]=Z$,a}});var Xg=S((Aj,Kg)=>{"use strict";var eM=ye(),tM=At();Kg.exports=function(a,e,t){try{return eM(tM(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Zg=S((Rj,Jg)=>{"use strict";var iM=ze();Jg.exports=function(a){return iM(a)||a===null}});var tS=S(($j,eS)=>{"use strict";var rM=Zg(),sM=String,aM=TypeError;eS.exports=function(a){if(rM(a))return a;throw new aM("Can't set "+sM(a)+" as a prototype")}});var Vc=S((Mj,iS)=>{"use strict";var nM=Xg(),oM=ze(),uM=ui(),lM=tS();iS.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=nM(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return uM(r),lM(s),oM(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var hS=S((Lj,pS)=>{"use strict";var cM=pe(),dM=et(),Mo=bt(),cS=Pc(),pM=ue(),hM=Yg(),rS=ho(),sS=Vc(),fM=ia(),mM=$r(),_c=_r(),bM=Ae(),aS=zi(),dS=Cc(),gM=cS.PROPER,SM=cS.CONFIGURABLE,nS=dS.IteratorPrototype,Lo=dS.BUGGY_SAFARI_ITERATORS,ra=bM("iterator"),oS="keys",sa="values",uS="entries",lS=function(){return this};pS.exports=function(a,e,t,i,r,s,n){hM(t,e,i);var o=function(b){if(b===r&&p)return p;if(!Lo&&b&&b in d)return d[b];switch(b){case oS:return function(){return new t(this,b)};case sa:return function(){return new t(this,b)};case uS:return function(){return new t(this,b)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[ra]||d["@@iterator"]||r&&d[r],p=!Lo&&c||o(r),h=e==="Array"&&d.entries||c,f,m,g;if(h&&(f=rS(h.call(new a)),f!==Object.prototype&&f.next&&(!Mo&&rS(f)!==nS&&(sS?sS(f,nS):pM(f[ra])||_c(f,ra,lS)),fM(f,u,!0,!0),Mo&&(aS[u]=lS))),gM&&r===sa&&c&&c.name!==sa&&(!Mo&&SM?mM(d,"name",sa):(l=!0,p=function(){return dM(c,this)})),r)if(m={values:o(sa),keys:s?p:o(oS),entries:o(uS)},n)for(g in m)(Lo||l||!(g in d))&&_c(d,g,m[g]);else cM({target:e,proto:!0,forced:Lo||l},m);return(!Mo||n)&&d[ra]!==p&&_c(d,ra,p,{name:r}),aS[e]=p,m}});var mS=S((Dj,fS)=>{"use strict";fS.exports=function(a,e){return{value:a,done:e}}});var Nc=S((Bj,yS)=>{"use strict";var vM=Ni(),Oc=Ys(),bS=zi(),SS=Ec(),yM=qi().f,TM=hS(),Do=mS(),IM=bt(),EM=Ze(),vS="Array Iterator",wM=SS.set,xM=SS.getterFor(vS);yS.exports=TM(Array,"Array",function(a,e){wM(this,{type:vS,target:vM(a),index:0,kind:e})},function(){var a=xM(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,Do(void 0,!0);switch(a.kind){case"keys":return Do(t,!1);case"values":return Do(e[t],!1)}return Do([t,e[t]],!1)},"values");var gS=bS.Arguments=bS.Array;Oc("keys");Oc("values");Oc("entries");if(!IM&&EM&&gS.name!=="values")try{yM(gS,"name",{value:"values"})}catch(a){}});var IS=S((Cj,TS)=>{"use strict";var PM=Ae(),kM=zi(),AM=PM("iterator"),RM=Array.prototype;TS.exports=function(a){return a!==void 0&&(kM.Array===a||RM[AM]===a)}});var Fc=S((Vj,wS)=>{"use strict";var $M=ta(),ES=Hs(),MM=Us(),LM=zi(),DM=Ae(),BM=DM("iterator");wS.exports=function(a){if(!MM(a))return ES(a,BM)||ES(a,"@@iterator")||LM[$M(a)]}});var PS=S((_j,xS)=>{"use strict";var CM=et(),VM=At(),_M=Rt(),OM=js(),NM=Fc(),FM=TypeError;xS.exports=function(a,e){var t=arguments.length<2?NM(a):e;if(VM(t))return _M(CM(t,a));throw new FM(OM(a)+" is not iterable")}});var RS=S((Oj,AS)=>{"use strict";var UM=et(),kS=Rt(),qM=Hs();AS.exports=function(a,e,t){var i,r;kS(a);try{if(i=qM(a,"return"),!i){if(e==="throw")throw t;return t}i=UM(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return kS(i),t}});var Co=S((Nj,DS)=>{"use strict";var jM=Rr(),HM=et(),WM=Rt(),zM=js(),QM=IS(),GM=Dr(),$S=qs(),YM=PS(),KM=Fc(),MS=RS(),XM=TypeError,Bo=function(a,e){this.stopped=a,this.result=e},LS=Bo.prototype;DS.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=jM(e,i),l,d,c,p,h,f,m,g=function(v){return l&&MS(l,"normal"),new Bo(!0,v)},b=function(v){return r?(WM(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(s)l=a.iterator;else if(n)l=a;else{if(d=KM(a),!d)throw new XM(zM(a)+" is not iterable");if(QM(d)){for(c=0,p=GM(a);p>c;c++)if(h=b(a[c]),h&&$S(LS,h))return h;return new Bo(!1)}l=YM(a,d)}for(f=s?a.next:l.next;!(m=HM(f,l)).done;){try{h=b(m.value)}catch(v){MS(l,"throw",v)}if(typeof h=="object"&&h&&$S(LS,h))return h}return new Bo(!1)}});var CS=S((Fj,BS)=>{"use strict";var JM=Ze(),ZM=qi(),eL=Fs();BS.exports=function(a,e,t){JM?ZM.f(a,e,eL(0,t)):a[e]=t}});var VS=S(()=>{"use strict";var tL=pe(),iL=Co(),rL=CS();tL({target:"Object",stat:!0},{fromEntries:function(e){var t={};return iL(e,function(i,r){rL(t,i,r)},{AS_ENTRIES:!0}),t}})});var OS=S((jj,_S)=>{"use strict";Nc();VS();var sL=Fi();_S.exports=sL.Object.fromEntries});var FS=S((Hj,NS)=>{"use strict";NS.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 qS=S(()=>{"use strict";Nc();var aL=FS(),nL=oe(),oL=ia(),US=zi();for(Vo in aL)oL(nL[Vo],Vo),US[Vo]=US.Array;var Vo});var HS=S((Qj,jS)=>{"use strict";var uL=OS();qS();jS.exports=uL});var Uc=S((Gj,WS)=>{"use strict";var lL=HS();WS.exports=lL});var zS=S(()=>{"use strict"});var qc=S((Xj,QS)=>{"use strict";var aa=oe(),cL=Ui(),dL=Oi(),_o=function(a){return cL.slice(0,a.length)===a};QS.exports=function(){return _o("Bun/")?"BUN":_o("Cloudflare-Workers")?"CLOUDFLARE":_o("Deno/")?"DENO":_o("Node.js/")?"NODE":aa.Bun&&typeof Bun.version=="string"?"BUN":aa.Deno&&typeof Deno.version=="object"?"DENO":dL(aa.process)==="process"?"NODE":aa.window&&aa.document?"BROWSER":"REST"}()});var Oo=S((Jj,GS)=>{"use strict";var pL=qc();GS.exports=pL==="NODE"});var KS=S((Zj,YS)=>{"use strict";var hL=qi();YS.exports=function(a,e,t){return hL.f(a,e,t)}});var ZS=S((eH,JS)=>{"use strict";var fL=Ft(),mL=KS(),bL=Ae(),gL=Ze(),XS=bL("species");JS.exports=function(a){var e=fL(a);gL&&e&&!e[XS]&&mL(e,XS,{configurable:!0,get:function(){return this}})}});var tv=S((tH,ev)=>{"use strict";var SL=qs(),vL=TypeError;ev.exports=function(a,e){if(SL(e,a))return a;throw new vL("Incorrect invocation")}});var Hc=S((iH,iv)=>{"use strict";var yL=ye(),TL=ue(),jc=Ws(),IL=yL(Function.toString);TL(jc.inspectSource)||(jc.inspectSource=function(a){return IL(a)});iv.exports=jc.inspectSource});var zc=S((rH,ov)=>{"use strict";var EL=ye(),wL=ve(),rv=ue(),xL=ta(),PL=Ft(),kL=Hc(),sv=function(){},av=PL("Reflect","construct"),Wc=/^\s*(?:class|function)\b/,AL=EL(Wc.exec),RL=!Wc.test(sv),na=function(e){if(!rv(e))return!1;try{return av(sv,[],e),!0}catch(t){return!1}},nv=function(e){if(!rv(e))return!1;switch(xL(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return RL||!!AL(Wc,kL(e))}catch(t){return!0}};nv.sham=!0;ov.exports=!av||wL(function(){var a;return na(na.call)||!na(Object)||!na(function(){a=!0})||a})?nv:na});var lv=S((sH,uv)=>{"use strict";var $L=zc(),ML=js(),LL=TypeError;uv.exports=function(a){if($L(a))return a;throw new LL(ML(a)+" is not a constructor")}});var Qc=S((aH,dv)=>{"use strict";var cv=Rt(),DL=lv(),BL=Us(),CL=Ae(),VL=CL("species");dv.exports=function(a,e){var t=cv(a).constructor,i;return t===void 0||BL(i=cv(t)[VL])?e:DL(i)}});var hv=S((nH,pv)=>{"use strict";var _L=ye();pv.exports=_L([].slice)});var mv=S((oH,fv)=>{"use strict";var OL=TypeError;fv.exports=function(a,e){if(a<e)throw new OL("Not enough arguments");return a}});var Gc=S((uH,bv)=>{"use strict";var NL=Ui();bv.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(NL)});var rd=S((lH,xv)=>{"use strict";var tt=oe(),FL=xl(),UL=Rr(),gv=ue(),qL=gt(),wv=ve(),Sv=kc(),jL=hv(),vv=lo(),HL=mv(),WL=Gc(),zL=Oo(),ed=tt.setImmediate,td=tt.clearImmediate,QL=tt.process,Yc=tt.Dispatch,GL=tt.Function,yv=tt.MessageChannel,YL=tt.String,Kc=0,oa={},Tv="onreadystatechange",ua,Gi,Xc,Jc;wv(function(){ua=tt.location});var id=function(a){if(qL(oa,a)){var e=oa[a];delete oa[a],e()}},Zc=function(a){return function(){id(a)}},Iv=function(a){id(a.data)},Ev=function(a){tt.postMessage(YL(a),ua.protocol+"//"+ua.host)};(!ed||!td)&&(ed=function(e){HL(arguments.length,1);var t=gv(e)?e:GL(e),i=jL(arguments,1);return oa[++Kc]=function(){FL(t,void 0,i)},Gi(Kc),Kc},td=function(e){delete oa[e]},zL?Gi=function(a){QL.nextTick(Zc(a))}:Yc&&Yc.now?Gi=function(a){Yc.now(Zc(a))}:yv&&!WL?(Xc=new yv,Jc=Xc.port2,Xc.port1.onmessage=Iv,Gi=UL(Jc.postMessage,Jc)):tt.addEventListener&&gv(tt.postMessage)&&!tt.importScripts&&ua&&ua.protocol!=="file:"&&!wv(Ev)?(Gi=Ev,tt.addEventListener("message",Iv,!1)):Tv in vv("script")?Gi=function(a){Sv.appendChild(vv("script"))[Tv]=function(){Sv.removeChild(this),id(a)}}:Gi=function(a){setTimeout(Zc(a),0)});xv.exports={set:ed,clear:td}});var Av=S((cH,kv)=>{"use strict";var Pv=oe(),KL=Ze(),XL=Object.getOwnPropertyDescriptor;kv.exports=function(a){if(!KL)return Pv[a];var e=XL(Pv,a);return e&&e.value}});var sd=S((dH,$v)=>{"use strict";var Rv=function(){this.head=null,this.tail=null};Rv.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};$v.exports=Rv});var Lv=S((pH,Mv)=>{"use strict";var JL=Ui();Mv.exports=/ipad|iphone|ipod/i.test(JL)&&typeof Pebble!="undefined"});var Bv=S((hH,Dv)=>{"use strict";var ZL=Ui();Dv.exports=/web0s(?!.*chrome)/i.test(ZL)});var Uv=S((fH,Fv)=>{"use strict";var Nr=oe(),eD=Av(),Cv=Rr(),ad=rd().set,tD=sd(),iD=Gc(),rD=Lv(),sD=Bv(),nd=Oo(),Vv=Nr.MutationObserver||Nr.WebKitMutationObserver,_v=Nr.document,Ov=Nr.process,No=Nr.Promise,ld=eD("queueMicrotask"),Or,od,ud,Fo,Nv;ld||(la=new tD,ca=function(){var a,e;for(nd&&(a=Ov.domain)&&a.exit();e=la.get();)try{e()}catch(t){throw la.head&&Or(),t}a&&a.enter()},!iD&&!nd&&!sD&&Vv&&_v?(od=!0,ud=_v.createTextNode(""),new Vv(ca).observe(ud,{characterData:!0}),Or=function(){ud.data=od=!od}):!rD&&No&&No.resolve?(Fo=No.resolve(void 0),Fo.constructor=No,Nv=Cv(Fo.then,Fo),Or=function(){Nv(ca)}):nd?Or=function(){Ov.nextTick(ca)}:(ad=Cv(ad,Nr),Or=function(){ad(ca)}),ld=function(a){la.head||Or(),la.add(a)});var la,ca;Fv.exports=ld});var jv=S((mH,qv)=>{"use strict";qv.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Uo=S((bH,Hv)=>{"use strict";Hv.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Yi=S((gH,Wv)=>{"use strict";var aD=oe();Wv.exports=aD.Promise});var Fr=S((SH,Yv)=>{"use strict";var nD=oe(),da=Yi(),oD=ue(),uD=Ql(),lD=Hc(),cD=Ae(),zv=qc(),dD=bt(),cd=Bl(),Qv=da&&da.prototype,pD=cD("species"),dd=!1,Gv=oD(nD.PromiseRejectionEvent),hD=uD("Promise",function(){var a=lD(da),e=a!==String(da);if(!e&&cd===66||dD&&!(Qv.catch&&Qv.finally))return!0;if(!cd||cd<51||!/native code/.test(a)){var t=new da(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[pD]=i,dd=t.then(function(){})instanceof i,!dd)return!0}return!e&&(zv==="BROWSER"||zv==="DENO")&&!Gv});Yv.exports={CONSTRUCTOR:hD,REJECTION_EVENT:Gv,SUBCLASSING:dd}});var Ur=S((vH,Xv)=>{"use strict";var Kv=At(),fD=TypeError,mD=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new fD("Bad Promise constructor");e=i,t=r}),this.resolve=Kv(e),this.reject=Kv(t)};Xv.exports.f=function(a){return new mD(a)}});var gy=S(()=>{"use strict";var bD=pe(),gD=bt(),Wo=Oo(),hi=oe(),SD=Fi(),Wr=et(),Jv=_r(),Zv=Vc(),vD=ia(),yD=ZS(),TD=At(),Ho=ue(),ID=ze(),ED=tv(),wD=Qc(),sy=rd().set,bd=Uv(),xD=jv(),PD=Uo(),kD=sd(),ay=Ec(),zo=Yi(),gd=Fr(),ny=Ur(),Qo="Promise",oy=gd.CONSTRUCTOR,AD=gd.REJECTION_EVENT,RD=gd.SUBCLASSING,pd=ay.getterFor(Qo),$D=ay.set,qr=zo&&zo.prototype,Ki=zo,qo=qr,uy=hi.TypeError,hd=hi.document,Sd=hi.process,fd=ny.f,MD=fd,LD=!!(hd&&hd.createEvent&&hi.dispatchEvent),ly="unhandledrejection",DD="rejectionhandled",ey=0,cy=1,BD=2,vd=1,dy=2,jo,ty,py,iy,hy=function(a){var e;return ID(a)&&Ho(e=a.then)?e:!1},fy=function(a,e){var t=e.value,i=e.state===cy,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{r?(i||(e.rejection===dy&&VD(e),e.rejection=vd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new uy("Promise-chain cycle")):(l=hy(u))?Wr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},my=function(a,e){a.notified||(a.notified=!0,bd(function(){for(var t=a.reactions,i;i=t.get();)fy(i,a);a.notified=!1,e&&!a.rejection&&CD(a)}))},by=function(a,e,t){var i,r;LD?(i=hd.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),hi.dispatchEvent(i)):i={promise:e,reason:t},!AD&&(r=hi["on"+a])?r(i):a===ly&&xD("Unhandled promise rejection",t)},CD=function(a){Wr(sy,hi,function(){var e=a.facade,t=a.value,i=ry(a),r;if(i&&(r=PD(function(){Wo?Sd.emit("unhandledRejection",t,e):by(ly,e,t)}),a.rejection=Wo||ry(a)?dy:vd,r.error))throw r.value})},ry=function(a){return a.rejection!==vd&&!a.parent},VD=function(a){Wr(sy,hi,function(){var e=a.facade;Wo?Sd.emit("rejectionHandled",e):by(DD,e,a.value)})},jr=function(a,e,t){return function(i){a(e,i,t)}},Hr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=BD,my(a,!0))},md=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new uy("Promise can't be resolved itself");var i=hy(e);i?bd(function(){var r={done:!1};try{Wr(i,e,jr(md,r,a),jr(Hr,r,a))}catch(s){Hr(r,s,a)}}):(a.value=e,a.state=cy,my(a,!1))}catch(r){Hr({done:!1},r,a)}}};if(oy&&(Ki=function(e){ED(this,qo),TD(e),Wr(jo,this);var t=pd(this);try{e(jr(md,t),jr(Hr,t))}catch(i){Hr(t,i)}},qo=Ki.prototype,jo=function(e){$D(this,{type:Qo,done:!1,notified:!1,parent:!1,reactions:new kD,rejection:!1,state:ey,value:null})},jo.prototype=Jv(qo,"then",function(e,t){var i=pd(this),r=fd(wD(this,Ki));return i.parent=!0,r.ok=Ho(e)?e:!0,r.fail=Ho(t)&&t,r.domain=Wo?Sd.domain:void 0,i.state===ey?i.reactions.add(r):bd(function(){fy(r,i)}),r.promise}),ty=function(){var a=new jo,e=pd(a);this.promise=a,this.resolve=jr(md,e),this.reject=jr(Hr,e)},ny.f=fd=function(a){return a===Ki||a===py?new ty(a):MD(a)},!gD&&Ho(zo)&&qr!==Object.prototype)){iy=qr.then,RD||Jv(qr,"then",function(e,t){var i=this;return new Ki(function(r,s){Wr(iy,i,r,s)}).then(e,t)},{unsafe:!0});try{delete qr.constructor}catch(a){}Zv&&Zv(qr,qo)}bD({global:!0,constructor:!0,wrap:!0,forced:oy},{Promise:Ki});py=SD.Promise;vD(Ki,Qo,!1,!0);yD(Qo)});var Iy=S((IH,Ty)=>{"use strict";var _D=Ae(),vy=_D("iterator"),yy=!1;try{Sy=0,yd={next:function(){return{done:!!Sy++}},return:function(){yy=!0}},yd[vy]=function(){return this},Array.from(yd,function(){throw 2})}catch(a){}var Sy,yd;Ty.exports=function(a,e){try{if(!e&&!yy)return!1}catch(r){return!1}var t=!1;try{var i={};i[vy]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Td=S((EH,Ey)=>{"use strict";var OD=Yi(),ND=Iy(),FD=Fr().CONSTRUCTOR;Ey.exports=FD||!ND(function(a){OD.all(a).then(void 0,function(){})})});var wy=S(()=>{"use strict";var UD=pe(),qD=et(),jD=At(),HD=Ur(),WD=Uo(),zD=Co(),QD=Td();UD({target:"Promise",stat:!0,forced:QD},{all:function(e){var t=this,i=HD.f(t),r=i.resolve,s=i.reject,n=WD(function(){var o=jD(t.resolve),u=[],l=0,d=1;zD(e,function(c){var p=l++,h=!1;d++,qD(o,t,c).then(function(f){h||(h=!0,u[p]=f,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var Py=S(()=>{"use strict";var GD=pe(),YD=bt(),KD=Fr().CONSTRUCTOR,Ed=Yi(),XD=Ft(),JD=ue(),ZD=_r(),xy=Ed&&Ed.prototype;GD({target:"Promise",proto:!0,forced:KD,real:!0},{catch:function(a){return this.then(void 0,a)}});!YD&&JD(Ed)&&(Id=XD("Promise").prototype.catch,xy.catch!==Id&&ZD(xy,"catch",Id,{unsafe:!0}));var Id});var ky=S(()=>{"use strict";var eB=pe(),tB=et(),iB=At(),rB=Ur(),sB=Uo(),aB=Co(),nB=Td();eB({target:"Promise",stat:!0,forced:nB},{race:function(e){var t=this,i=rB.f(t),r=i.reject,s=sB(function(){var n=iB(t.resolve);aB(e,function(o){tB(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Ay=S(()=>{"use strict";var oB=pe(),uB=Ur(),lB=Fr().CONSTRUCTOR;oB({target:"Promise",stat:!0,forced:lB},{reject:function(e){var t=uB.f(this),i=t.reject;return i(e),t.promise}})});var wd=S((LH,Ry)=>{"use strict";var cB=Rt(),dB=ze(),pB=Ur();Ry.exports=function(a,e){if(cB(a),dB(e)&&e.constructor===a)return e;var t=pB.f(a),i=t.resolve;return i(e),t.promise}});var Ly=S(()=>{"use strict";var hB=pe(),fB=Ft(),$y=bt(),mB=Yi(),My=Fr().CONSTRUCTOR,bB=wd(),gB=fB("Promise"),SB=$y&&!My;hB({target:"Promise",stat:!0,forced:$y||My},{resolve:function(e){return bB(SB&&this===gB?mB:this,e)}})});var Dy=S(()=>{"use strict";gy();wy();Py();ky();Ay();Ly()});var _y=S(()=>{"use strict";var vB=pe(),yB=bt(),Go=Yi(),TB=ve(),Cy=Ft(),Vy=ue(),IB=Qc(),By=wd(),EB=_r(),Pd=Go&&Go.prototype,wB=!!Go&&TB(function(){Pd.finally.call({then:function(){}},function(){})});vB({target:"Promise",proto:!0,real:!0,forced:wB},{finally:function(a){var e=IB(this,Cy("Promise")),t=Vy(a);return this.then(t?function(i){return By(e,a()).then(function(){return i})}:a,t?function(i){return By(e,a()).then(function(){throw i})}:a)}});!yB&&Vy(Go)&&(xd=Cy("Promise").prototype.finally,Pd.finally!==xd&&EB(Pd,"finally",xd,{unsafe:!0}));var xd});var Ny=S((NH,Oy)=>{"use strict";zS();Dy();_y();var xB=li();Oy.exports=xB("Promise","finally")});var Uy=S((FH,Fy)=>{"use strict";var PB=Ny();Fy.exports=PB});var Yo=S((UH,qy)=>{"use strict";var kB=Uy();qy.exports=kB});var oT=S(()=>{"use strict";var iC=pe(),rC=kr(),sC=Dr(),aC=Gs(),nC=Ys();iC({target:"Array",proto:!0},{at:function(e){var t=rC(this),i=sC(t),r=aC(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});nC("at")});var lT=S((qW,uT)=>{"use strict";oT();var oC=li();uT.exports=oC("Array","at")});var dT=S((jW,cT)=>{"use strict";var uC=lT();cT.exports=uC});var Ye=S((HW,pT)=>{"use strict";var lC=dT();pT.exports=lC});var ap=S((aG,nI)=>{"use strict";var f0=Oi();nI.exports=Array.isArray||function(e){return f0(e)==="Array"}});var uI=S((nG,oI)=>{"use strict";var m0=TypeError,b0=9007199254740991;oI.exports=function(a){if(a>b0)throw m0("Maximum allowed index exceeded");return a}});var dI=S((oG,cI)=>{"use strict";var g0=ap(),S0=Dr(),v0=uI(),y0=Rr(),lI=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,d=n?y0(n,o):!1,c,p;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&g0(c)?(p=S0(c),u=lI(a,e,c,p,u,s-1)-1):(v0(u+1),a[u]=c),u++),l++;return u};cI.exports=lI});var mI=S((uG,fI)=>{"use strict";var pI=ap(),T0=zc(),I0=ze(),E0=Ae(),w0=E0("species"),hI=Array;fI.exports=function(a){var e;return pI(a)&&(e=a.constructor,T0(e)&&(e===hI||pI(e.prototype))?e=void 0:I0(e)&&(e=e[w0],e===null&&(e=void 0))),e===void 0?hI:e}});var gI=S((lG,bI)=>{"use strict";var x0=mI();bI.exports=function(a,e){return new(x0(a))(e===0?0:e)}});var SI=S(()=>{"use strict";var P0=pe(),k0=dI(),A0=At(),R0=kr(),$0=Dr(),M0=gI();P0({target:"Array",proto:!0},{flatMap:function(e){var t=R0(this),i=$0(t),r;return A0(e),r=M0(t,0),r.length=k0(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var vI=S(()=>{"use strict";var L0=Ys();L0("flatMap")});var TI=S((fG,yI)=>{"use strict";SI();vI();var D0=li();yI.exports=D0("Array","flatMap")});var EI=S((mG,II)=>{"use strict";var B0=TI();II.exports=B0});var rr=S((bG,wI)=>{"use strict";var C0=EI();wI.exports=C0});var ka=S((DG,AI)=>{"use strict";var _0=ta(),O0=String;AI.exports=function(a){if(_0(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return O0(a)}});var op=S((BG,RI)=>{"use strict";RI.exports=`
|
|
7
|
-
\v\f\r \u2028\u2029\uFEFF`});var LI=S((CG,MI)=>{"use strict";var N0=ye(),F0=ui(),U0=ka(),lp=op(),$I=N0("".replace),q0=RegExp("^["+lp+"]+"),j0=RegExp("(^|[^"+lp+"])["+lp+"]+$"),up=function(a){return function(e){var t=U0(F0(e));return a&1&&(t=$I(t,q0,"")),a&2&&(t=$I(t,j0,"$1")),t}};MI.exports={start:up(1),end:up(2),trim:up(3)}});var VI=S((VG,CI)=>{"use strict";var H0=Pc().PROPER,W0=ve(),DI=op(),BI="
";CI.exports=function(a){return W0(function(){return!!DI[a]()||BI[a]()!==BI||H0&&DI[a].name!==a})}});var cp=S((_G,_I)=>{"use strict";var z0=LI().start,Q0=VI();_I.exports=Q0("trimStart")?function(){return z0(this)}:"".trimStart});var NI=S(()=>{"use strict";var G0=pe(),OI=cp();G0({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==OI},{trimLeft:OI})});var UI=S(()=>{"use strict";NI();var Y0=pe(),FI=cp();Y0({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==FI},{trimStart:FI})});var jI=S((qG,qI)=>{"use strict";UI();var K0=li();qI.exports=K0("String","trimLeft")});var WI=S((jG,HI)=>{"use strict";var X0=jI();HI.exports=X0});var QI=S((HG,zI)=>{"use strict";var J0=WI();zI.exports=J0});var XI=S(()=>{"use strict"});var JI=S(()=>{"use strict"});var eE=S((k3,ZI)=>{"use strict";var iV=ze(),rV=Oi(),sV=Ae(),aV=sV("match");ZI.exports=function(a){var e;return iV(a)&&((e=a[aV])!==void 0?!!e:rV(a)==="RegExp")}});var rE=S((A3,iE)=>{"use strict";var nV=oe(),oV=ve(),tE=nV.RegExp,uV=!oV(function(){var a=!0;try{tE(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(tE.prototype,"flags").get.call(e);return o!==i||t!==i});iE.exports={correct:uV}});var aE=S((R3,sE)=>{"use strict";var lV=Rt();sE.exports=function(){var a=lV(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var uE=S(($3,oE)=>{"use strict";var cV=et(),dV=gt(),pV=qs(),nE=rE(),hV=aE(),fV=RegExp.prototype;oE.exports=nE.correct?function(a){return a.flags}:function(a){return!nE.correct&&pV(fV,a)&&!dV(a,"flags")?cV(hV,a):a.flags}});var cE=S((M3,lE)=>{"use strict";var mp=ye(),mV=kr(),bV=Math.floor,hp=mp("".charAt),gV=mp("".replace),fp=mp("".slice),SV=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,vV=/\$([$&'`]|\d{1,2})/g;lE.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=vV;return r!==void 0&&(r=mV(r),u=SV),gV(s,u,function(l,d){var c;switch(hp(d,0)){case"$":return"$";case"&":return a;case"`":return fp(e,0,t);case"'":return fp(e,n);case"<":c=r[fp(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=bV(p/10);return h===0?l:h<=o?i[h-1]===void 0?hp(d,1):i[h-1]+hp(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var hE=S(()=>{"use strict";var yV=pe(),TV=et(),gp=ye(),dE=ui(),IV=ue(),EV=ze(),wV=eE(),us=ka(),xV=Hs(),PV=uE(),kV=cE(),AV=Ae(),RV=bt(),$V=AV("replace"),MV=TypeError,bp=gp("".indexOf),LV=gp("".replace),pE=gp("".slice),DV=Math.max;yV({target:"String",proto:!0},{replaceAll:function(e,t){var i=dE(this),r,s,n,o,u,l,d,c,p,h,f=0,m="";if(EV(e)){if(r=wV(e),r&&(s=us(dE(PV(e))),!~bp(s,"g")))throw new MV("`.replaceAll` does not allow non-global regexes");if(n=xV(e,$V),n)return TV(n,e,i,t);if(RV&&r)return LV(us(i),e,t)}for(o=us(i),u=us(e),l=IV(t),l||(t=us(t)),d=u.length,c=DV(1,d),p=bp(o,u);p!==-1;)h=l?us(t(u,p,o)):kV(u,o,p,[],void 0,t),m+=pE(o,f,p)+h,f=p+d,p=p+c>o.length?-1:bp(o,u,p+c);return f<o.length&&(m+=pE(o,f)),m}})});var mE=S((B3,fE)=>{"use strict";XI();JI();hE();var BV=li();fE.exports=BV("String","replaceAll")});var gE=S((C3,bE)=>{"use strict";var CV=mE();bE.exports=CV});var vE=S((V3,SE)=>{"use strict";var VV=gE();SE.exports=VV});var TE=S((_3,yE)=>{"use strict";var _V=Gs(),OV=ka(),NV=ui(),FV=RangeError;yE.exports=function(e){var t=OV(NV(this)),i="",r=_V(e);if(r<0||r===1/0)throw new FV("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var PE=S((O3,xE)=>{"use strict";var wE=ye(),UV=ec(),IE=ka(),qV=TE(),jV=ui(),HV=wE(qV),WV=wE("".slice),zV=Math.ceil,EE=function(a){return function(e,t,i){var r=IE(jV(e)),s=UV(t),n=r.length,o=i===void 0?" ":IE(i),u,l;return s<=n||o===""?r:(u=s-n,l=HV(o,zV(u/o.length)),l.length>u&&(l=WV(l,0,u)),a?r+l:l+r)}};xE.exports={start:EE(!1),end:EE(!0)}});var AE=S((N3,kE)=>{"use strict";var QV=Ui();kE.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(QV)});var RE=S(()=>{"use strict";var GV=pe(),YV=PE().start,KV=AE();GV({target:"String",proto:!0,forced:KV},{padStart:function(e){return YV(this,e,arguments.length>1?arguments[1]:void 0)}})});var ME=S((q3,$E)=>{"use strict";RE();var XV=li();$E.exports=XV("String","padStart")});var DE=S((j3,LE)=>{"use strict";var JV=ME();LE.exports=JV});var CE=S((H3,BE)=>{"use strict";var ZV=DE();BE.exports=ZV});var wf="2.0.150-dev.10447541.0";var ke=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ke||{}),Nt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Nt||{});var _s=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(_s||{}),Il=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Il||{});var El=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(El||{}),no=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(no||{});var _h=O(ji(),1),Jx=O(Re(),1);import{assertNever as Wb,assertNonNullable as nR,isNonNullable as mo,ValueSubject as nc,Subject as oR,Subscription as uR,merge as lR,observableFrom as cR,fromEvent as Ub,map as qb,tap as jb,filterChanged as dR,isNullable as oc,ErrorCategory as Hb}from"@vkontakte/videoplayer-shared/es2018";var Fb=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var bo=class{constructor(e){this.connection$=new nc(void 0);this.castState$=new nc("NOT_AVAILABLE");this.errorEvent$=new oR;this.realCastState$=new nc("NOT_AVAILABLE");this.subscription=new uR;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=mo((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Fb("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Hb.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){mo(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();oc(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();oc(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(Ub(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Wb(r.sessionState)}})).add(lR(Ub(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(jb(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),qb(r=>r.castState)),cR([i.getCastState()])).pipe(dR(),qb(pR),jb(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=mo(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();nR(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(oc(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?mo(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Hb.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},pR=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Wb(a)}};import{assertNonNullable as hc,combine as fc,debounce as mc,ErrorCategory as MR,filter as Cr,filterChanged as ng,isNonNullable as bc,isNullable as og,map as LR,Subscription as DR,ValueSubject as gc}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as hR,assertNonNullable as Hi,ErrorCategory as fR,getHighestQuality as mR,isNonNullable as Qb}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as zb}from"@vkontakte/videoplayer-shared/es2018";var le=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:zb(t)}return a},ci=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:zb(e)}};var So=a=>{var c;let{source:e,format:t,meta:i,output:r}=a,s,n,o;switch(t){case"MPEG":{let p=e[t];Hi(p);let h=mR(Object.keys(p));Hi(h);let f=p[h];Hi(f),s=f,n="video/mp4",o=go();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];Hi(p),s=p.url,n="application/x-mpegurl",o=go();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];Hi(p),s=p.url,n="application/dash+xml",o=go();break}case"DASH_LIVE_CMAF":{let p=e[t];Hi(p),s=p.url,n="application/dash+xml",o=Gb();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];Hi(p),s=le(p.url),n="application/x-mpegurl",o=Gb();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let p="Unsupported format for Chromecast",h=new Error(p);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:fR.VIDEO_PIPELINE,message:p,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return hR(t)}let u=bR((c=i.videoId)!=null?c:s,n);u.contentUrl=s,u.streamType=o,u.metadata=gR();let{title:l,subtitle:d}=i;return Qb(l)&&(u.metadata.title=l),Qb(d)&&(u.metadata.subtitle=d),u};function go(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function Gb(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function bR(a,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(a,e):{contentId:a,contentType:e,metadata:{title:"",subtitle:""},streamType:go()}}function gR(){var a,e;return(e=(a=chrome.cast)==null?void 0:a.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var R=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var vo=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)}};import{assertNever as ag}from"@vkontakte/videoplayer-shared/es2018";import{isBrowserWindow as AR,ValueSubject as RR}from"@vkontakte/videoplayer-shared/es2018";var Yb=O(Re(),1);import{getWindow as SR}from"@vkontakte/videoplayer-shared/es2018";var yo=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Yb.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=SR().navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Kb=O(Re(),1);import{getWindow as uc,isBrowserWindow as lc}from"@vkontakte/videoplayer-shared/es2018";var Wi=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var To=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,Kb.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=uc();if(!lc(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=Wi()}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=uc();if(!lc(e))return;let{userAgentData:t}=e.navigator;if(t!=null&&t.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r.length>0,o=r.length>1,u="Unknown",l="Unknown";if(n){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(u=s[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(l=s[d]):d!==void 0&&(l=d)}else s[2]!==void 0?l=s[2]:s[1]!==void 0&&n&&typeof r[0]=="string"&&(l=s[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 s=e.match(i);if(s){let n=r[0],o=r[1],u=typeof n=="number"?s[n]!==void 0?this.normalizeVendorName(s[n]):"Unknown":this.normalizeVendorName(n),l="Unknown";typeof o=="number"?l=s[o]!==void 0?s[o]:"Unknown":o!==void 0?l=o:s[1]!==void 0?l=s[1]:s[0]!==void 0&&(l=s[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=uc();if(!lc(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t!=null&&t[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};import{getWindow as Xb,isBrowserWindow as vR}from"@vkontakte/videoplayer-shared/es2018";var Io=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in Xb()}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var s;let e=Xb();if(!vR(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((s=e.matchMedia("(dynamic-range: high)"))!=null&&s.matches),this._colorDepth=i.colorDepth}catch(n){console.error(n)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(n){console.error(n)}}};import{getWindow as cc,isBrowserWindow as eg}from"@vkontakte/videoplayer-shared/es2018";var Oe=()=>window.ManagedMediaSource||window.MediaSource,di=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Jb=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Br=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Zb,yR=(Zb=cc().document)==null?void 0:Zb.createElement("video"),TR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',IR='video/mp4; codecs="hev1.1.6.L93.B0"',tg='video/webm; codecs="vp09.00.10.08"',ig='video/webm; codecs="av01.0.00M.08"',ER='audio/mp4; codecs="mp4a.40.2"',wR='audio/webm; codecs="opus"',rg,xR=async()=>{let a=cc();if(!eg(a))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:ig}}),a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:tg}})]);rg={DASH_WEBM_AV1:t,DASH_WEBM:i}};xR().catch(a=>{console.log(yR),console.error(a)});var Eo=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 rg}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,s,n,o,u,l,d,c,p,h,f,m,g,b,v,T,y,E,P;let e=cc();if(!eg(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:di(),mse:Jb(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(s=this._video).canPlayType)!=null&&n.call(s,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((d=(l=this._video).canPlayType)!=null&&d.call(l,"video/webm")),cmaf:!0};let $=!!((p=(c=Oe())==null?void 0:c.isTypeSupported)!=null&&p.call(c,TR)),A=!!((f=(h=Oe())==null?void 0:h.isTypeSupported)!=null&&f.call(h,IR)),L=!!((g=(m=Oe())==null?void 0:m.isTypeSupported)!=null&&g.call(m,ER));this._codecs={h264:$,h265:A,vp9:!!((v=(b=Oe())==null?void 0:b.isTypeSupported)!=null&&v.call(b,tg)),av1:!!((y=(T=Oe())==null?void 0:T.isTypeSupported)!=null&&y.call(T,ig)),aac:L,opus:!!((P=(E=Oe())==null?void 0:E.isTypeSupported)!=null&&P.call(E,wR)),mpeg:($||A)&&L},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch($){console.error($)}try{this.destroyVideoElement()}catch($){console.error("Error destroying video element:",$)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};import{getWindow as PR,isBrowserWindow as kR}from"@vkontakte/videoplayer-shared/es2018";var sg="audio/mpeg",wo=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,s,n;let e=PR();if(!kR(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!((r=(i=this._audio).canPlayType)!=null&&r.call(i,sg))},this._codecs={mp3:!!((n=(s=Oe())==null?void 0:s.isTypeSupported)!=null&&n.call(s,sg))}}catch(o){console.error(o)}try{this.destroyAudioElement()}catch(o){console.error("Error destroying audio element:",o)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var dc=class{constructor(){this.isInited$=new RR(!1);this._displayChecker=new Io,this._deviceChecker=new To(this._displayChecker),this._browserChecker=new yo,this._videoChecker=new Eo(this._deviceChecker,this._browserChecker),this._audioChecker=new wo,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(){AR()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},C=new dc;var pc=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=C.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return ag(o)}})},Ks=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return ag(a)}},$R=a=>{let t=Object.keys(a).filter(i=>!Ks(i));return pc(t).length>0};var Xs=class{constructor(e){this.subscription=new DR;this.sessionId$=new gc(null);this.mediaSessionId$=new gc(null);this.contentId$=new gc(null);this.isMobile=Wi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var s,n,o;if(og(e))return;this.media=e,this.mediaSessionId$.next((s=e.mediaSessionId)!=null?s:null);let t=(n=e.media)==null?void 0:n.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=(o=e.media)==null?void 0:o.duration;bc(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(bc(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let l=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!l?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new vo(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ks(e.format)),this.subscribe()}subscribe(){let e=r=>{var s;this.params.output.error$.next({category:MR.WTF,id:"ChromecastPresentationApiProvider",message:(s=r==null?void 0:r.message)!=null?s:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(Cr(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(Cr(bc),ng(),mc(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(ng(),LR(Boolean));this.subscription.add(fc({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(Cr(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=fc({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(Cr(({mediaLoaded:r})=>r),mc(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(Cr(({mediaLoaded:r,playbackState:{from:s,to:n}})=>!r&&s==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(fc({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(mc(30)),mediaLoaded:t}).pipe(Cr(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:n}=r.to;this.setVolume(n,s)},e))}handleMessage(e){var t,i,r,s,n,o;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let u=(i=(t=e.message)==null?void 0:t.media)==null?void 0:i[0];this.syncMediaState(u);let l=(r=e.message)==null?void 0:r.receiver.volume;this.syncVolumeState(l)}break;case"v2_message":{switch((s=e.message)==null?void 0:s.type){case"MEDIA_STATUS":{let u=(o=(n=e.message)==null?void 0:n.status)==null?void 0:o[0];this.syncMediaState(u);break}}break}}}loadMedia(){var o;let e=So(this.params),t=(o=this.media)==null?void 0:o.currentTime,i=this.params.desiredState.seekState.getState(),r=t!=null?t:i.state!=="none"?i.position/1e3:0,n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();hc(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();hc(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();hc(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":R(this.params.desiredState.playbackState,"paused");break;case"PLAYING":R(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),R(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):R(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(og(e))return;let{level:t,muted:i}=e,r={muted:i!=null?i:!1,volume:t!=null?t:0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let s=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,s+=`, volume passed to state machine: ${r.volume}`),this.log({message:s}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as BR,ErrorCategory as Sc,filter as CR,Subject as VR,Subscription as vc,tap as _R,ValueSubject as Vr,fromEvent as Js}from"@vkontakte/videoplayer-shared/es2018";var ug=a=>({castDevice:{friendlyName:a},remotePlayer:{},remotePlayerController:{},session:{}}),lg=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Zs=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new Vr(null);this.sessionId$=new Vr(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new vc;this.subscriptionEvents=new vc;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new Vr(!1);this.presentationConnection$=new Vr(null);this.message$=new Vr(null);this.friendlyName$=new Vr(null);this.errorEvent$=new VR;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(Js(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){var e;this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let t=this.presentationRequest$.getValue();BR(t,"connect with null presentationRequest");let i=await t.start();this.handleConnection(i)}catch(t){switch(t==null?void 0:t.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:Sc.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}}subscribe(){this.subscription.add(Js(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(_R(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),CR(e=>!!e)).subscribe(e=>{let t=Js(e,"message").subscribe(s=>{let n=JSON.parse(s.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(n),this.message$.next(n))}),i=Js(e,"connect").subscribe(()=>{this.send("client_connect")}),r=Js(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:Sc.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:s});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();(t==null?void 0:t.state)==="connected"&&(t==null||t.send(e))}catch(t){this.errorEvent$.next({category:Sc.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){var t;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":((t=e.message)==null?void 0:t.action)==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||lg()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new vc}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))}};import{ValueSubject as cg,Subject as OR,map as NR,Subscription as FR,combine as UR,filterChanged as dg,assertNonNullable as qR}from"@vkontakte/videoplayer-shared/es2018";var Ut=class a{constructor(e){this.subscription=new FR;this.connection$=new cg(void 0);this.castState$=new cg("NOT_AVAILABLE");this.errorEvent$=new OR;let t=a.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Zs({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){qR(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=UR({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(dg())});this.subscription.add(e.pipe(NR(({connection:t,friendlyName:i})=>!!(t&&i)),dg()).subscribe(t=>{var r,s;let i=(s=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?s:"";this.connection$.next(t?ug(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){var e;this.log({message:"connect"}),(e=this.chromecastConnector)==null||e.connect()}disconnect(){var e;this.log({message:"disconnect"}),(e=this.chromecastConnector)==null||e.disconnect()}async stopMedia(){var e;this.log({message:"stopMedia"}),(e=this.chromecastConnector)==null||e.stopMedia()}toggleConnection(){var t;let e=!!((t=this.chromecastConnector)!=null&&t.presentationConnection$.getValue());this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){var e;this.log({message:"destroy"}),(e=this.chromecastConnector)==null||e.destroy(),this.subscription.unsubscribe()}};var xh=O(Re(),1),Ph=O(pi(),1),Lx=O(Uc(),1);var Gy=O(Yo(),1);import{isNonNullable as AB,Subject as Ko,merge as jy}from"@vkontakte/videoplayer-shared/es2018";var j=class{constructor(e){this.transitionStarted$=new Ko;this.transitionEnded$=new Ko;this.transitionUpdated$=new Ko;this.forceChanged$=new Ko;this.stateChangeStarted$=jy(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=jy(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||AB(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}};import{assertNever as pa,debounce as Hy,ErrorCategory as RB,fromEvent as Xi,map as Wy,merge as zy,observableFrom as $B,Subject as MB,Subscription as kd,timeout as LB}from"@vkontakte/videoplayer-shared/es2018";var DB=5,BB=5,CB=500,Qy=7e3,ha=class{constructor(e){this.subscription=new kd;this.loadMediaTimeoutSubscription=new kd;this.videoState=new j("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:pa(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:pa(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:pa(e)}break}default:pa(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ks(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 kd;this.subscription.add(e),this.subscription.add(zy(this.videoState.stateChangeStarted$.pipe(Wy(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Wy(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new MB;e.add(r.pipe(Hy(CB)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>DB)&&r.next(o),s=o})),e.add(Xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<BB&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(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:pa(n)}}),t(Xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=zy(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$B(["init"])).pipe(Hy(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"),R(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),R(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=So(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&R(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(LB(Qy).subscribe(()=>s(`timeout(${Qy})`)))});(0,Gy.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:RB.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var zd=O(Re(),1);import{clearVideoElement as Ky,getWindow as _B}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as VB}from"@vkontakte/videoplayer-shared/es2018";var Yy=a=>{try{a.pause(),a.playbackRate=0,VB(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as OB,Subscription as NB}from"@vkontakte/videoplayer-shared/es2018";var Ad=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)}},Xo=_B(),Rd=Xo.WeakMap?new Xo.WeakMap:new Ad,$d=Xo.WeakMap?new Xo.WeakMap:new Map,FB=(a,e=20)=>{let t=0;return OB(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},$e=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?Ky(i):(i=document.createElement("video"),a.appendChild(i)),Rd.set(i,r);let s=new NB;return s.add(FB(i,e)),$d.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Me=a=>{let e=$d.get(a);e==null||e.unsubscribe(),$d.delete(a);let t=Rd.get(a);Rd.delete(a),t?Ky(a):Yy(a)};var Ld=O(ji(),1);import{assertNonNullable as ma,isNonNullable as $t,isNullable as jB,fromEvent as zr,merge as Xy,observableFrom as Jy,filterChanged as Zy,map as ba,Subject as eT,Subscription as HB,ValueSubject as WB,ErrorCategory as zB}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Md,isNullable as UB,Subscription as qB}from"@vkontakte/videoplayer-shared/es2018";var Jo=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=UB(r),l=new qB;return r&&l.add(r.subscribe(d=>{let c=a.getState();i(d,c)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},ot=(a,e,t)=>Jo(e,()=>a.loop,i=>{Md(i)&&(a.loop=i)},{onError:t}),Le=(a,e,t,i)=>Jo(e,()=>({muted:a.muted,volume:a.volume}),r=>{Md(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Qe=(a,e,t,i)=>Jo(e,()=>a.playbackRate,r=>{Md(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),fa=Jo;var QB=a=>["__",a.language,a.label].join("|"),GB=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Dd=class a{constructor(e){this.available$=new eT;this.current$=new WB(void 0);this.error$=new eT;this.subscription=new HB;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:zB.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(fa(t.internalTextTracks,()=>(0,Ld.default)(this.internalTracks),s=>{$t(s)&&this.setInternal(s)},{equal:(s,n)=>$t(s)&&$t(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ba(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(fa(t.externalTextTracks,()=>(0,Ld.default)(this.externalTracks),s=>{$t(s)&&this.setExternal(s)},{equal:(s,n)=>$t(s)&&$t(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ba(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(fa(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(fa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ma(this.video);let{textTracks:e}=this.video;this.subscription.add(zr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Xy(zr(e,"addtrack"),zr(e,"removetrack"),Jy(["init"])).pipe(ba(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Zy((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(Xy(zr(e,"change"),Jy(["init"])).pipe(ba(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),ba(i=>i&&this.htmlTextTrackToITextTrack(i).id),Zy()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(zr(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,d,c,p,h;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(zr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;$t(t.align)&&(r.align=t.align),$t(t.position)&&(r.position=t.position),$t(t.size)&&(r.size=t.size),$t(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ma(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:QB(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){ma(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(jB(e)||!GB(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){ma(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){ma(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)}},Ge=Dd;var Ji=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 tT=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Bd=a=>{let e=tT(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},iT=a=>{let e=tT(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ne,map as Mt,merge as Zo,filterChanged as sT,isNonNullable as aT,Subject as KB,filter as Cd,mapTo as Vd,combine as XB,once as JB,shareReplay as Fe,throttle as ZB,ErrorCategory as eC,ValueSubject as nT,Subscription as tC}from"@vkontakte/videoplayer-shared/es2018";var YB=3,rT=(a,e,t=YB)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var De=a=>{let e=M=>Ne(a,M).pipe(Vd(void 0),Fe(1)),t=new tC,i=()=>t.unsubscribe(),r=Zo(Ne(a,"progress"),Ne(a,"timeupdate")).pipe(Mt(()=>rT(a.buffered,a.currentTime)),Fe(1)),s=C.browser.isSafari?XB({play:e("play").pipe(JB()),playing:e("playing")}).pipe(Vd(void 0),Fe(1)):e("playing"),n=Ne(a,"volumechange").pipe(Mt(()=>({muted:a.muted,volume:a.volume})),Fe(1)),o=Ne(a,"ratechange").pipe(Mt(()=>a.playbackRate),Fe(1)),u=Ne(a,"error").pipe(Cd(()=>!!(a.error||a.played.length)),Mt(()=>{var B;let M=a.error;return{id:M?`MediaError#${M.code}`:"HtmlVideoError",category:eC.VIDEO_PIPELINE,message:M?M.message:"Error event from HTML video element",thrown:(B=a.error)!=null?B:void 0}}),Fe(1)),l=Ne(a,"timeupdate").pipe(Mt(()=>a.currentTime),Fe(1)),d=["waiting","seeking","seeked","timeupdate"],c=new KB,p=.3,h;t.add(Zo(...d.map(M=>Ne(a,M))).subscribe(M=>{let B=a.currentTime;a.loop&&aT(h)&&aT(B)&&h>=a.duration-p&&B<=p&&c.next(h),h=B}));let f=e("pause").pipe(Cd(()=>!a.error&&h!==a.duration),Fe(1)),m=Ne(a,"enterpictureinpicture").pipe(Fe(1)),g=Ne(a,"leavepictureinpicture").pipe(Fe(1)),b=new nT(iT(a));t.add(m.subscribe(()=>b.next(!0))),t.add(g.subscribe(()=>b.next(!1)));let v=new nT(Bd(a)),T=Ne(a,"fullscreenchange").pipe(Fe(1));t.add(T.pipe(Mt(()=>Bd(a))).subscribe(v));let y=.1,E=1e3,P=Ne(a,"timeupdate").pipe(Mt(M=>a.duration-a.currentTime<y),sT(),Fe(1)),$=Zo(P.pipe(Cd(M=>!a.loop&&M)),Ne(a,"ended")).pipe(ZB(E),Vd(void 0),Fe(1)),L=Zo(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(M=>Ne(a,M)),P.pipe(Mt(M=>({type:M?"ended":"unknown"})))).pipe(Mt(M=>C.browser.isFirefox&&M.type==="ended"?a.readyState<2:a.readyState<3),sT(),Fe(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:$,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$:Ne(a,"durationchange").pipe(Mt(()=>a.duration),Fe(1)),isBuffering$:L,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:b,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as fi}from"@vkontakte/videoplayer-shared/es2018";var Lt=a=>{switch(a){case"mobile":return fi.Q_144P;case"lowest":return fi.Q_240P;case"low":return fi.Q_360P;case"sd":case"medium":return fi.Q_480P;case"hd":case"high":return fi.Q_720P;case"fullhd":case"full":return fi.Q_1080P;case"quadhd":case"quad":return fi.Q_1440P;case"ultrahd":case"ultra":return fi.Q_2160P}};var qe=O(Ye(),1),Od=O(Re(),1),er=O(pi(),1);import{isNonNullable as Z,isNullable as ru,now as ET,isHigher as su,isHigherOrEqual as Zi,isInvariantQuality as au,isLowerOrEqual as Gr,videoSizeToQuality as wT,assertNotEmptyArray as nu,assertNonNullable as xT}from"@vkontakte/videoplayer-shared/es2018";var _d=!1,jt={},hT=a=>{_d=a},fT=()=>{jt={}},mT=a=>{a(jt)},ga=(a,e)=>{var t;_d&&(jt.meta=(t=jt.meta)!=null?t:{},jt.meta[a]=e)},Ue=class{constructor(e){this.name=e}next(e){var i,r;if(!_d)return;jt.series=(i=jt.series)!=null?i:{};let t=(r=jt.series[this.name])!=null?r:[];t.push([Date.now(),e]),jt.series[this.name]=t}};import{isHigher as cC,isHigherOrEqual as KW,isLower as bT,isLowerOrEqual as XW,isNonNullable as eu,isNullable as dC,videoHeightToQuality as tu}from"@vkontakte/videoplayer-shared/es2018";function gT(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Qr(a,e,t){return dC(a)||eu(a.min)&&eu(a.max)&&bT(a.max,a.min)||eu(a.min)&&e&&cC(a.min,e)||eu(a.max)&&t&&bT(a.max,t)}function ST({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Qr({max:a!=null&&a.max?tu(a.max):void 0,min:a!=null&&a.min?tu(a.min):void 0},e?tu(e):void 0,t?tu(t):void 0)}var PT=new Ue("best_bitrate"),ou=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Yr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),yt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ET()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},uu='Assertion "ABR Tracks is empty array" failed',iu=new WeakMap,vT=new WeakMap,yT=new WeakMap,tr=(a,e,t,i)=>{var u;let r=[...e].sort(Yr(1)),s=[...t].sort(Yr(1)),n=s.filter(l=>Z(l.bitrate)&&Z(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,qe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,qe.default)(s,-1);return o&&(0,Od.default)(n,o)?o:n.length?(0,qe.default)(n,-1):(0,qe.default)(s,0)},ir=(a,e,t,i)=>{var u;let r=iu.get(e);r||(r=[...e].sort(Yr(1)),iu.set(e,r));let s=iu.get(t);s||(s=[...t].sort(Yr(1)),iu.set(t,s));let n=yT.get(a);n||(n=s.filter(l=>Z(l.bitrate)&&Z(a.bitrate)?a.bitrate/l.bitrate>i:!0),yT.set(a,n));let o=(u=(0,qe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,qe.default)(s,-1);return o&&(0,Od.default)(n,o)?o:n.length?(0,qe.default)(n,-1):(0,qe.default)(s,0)},TT=a=>"quality"in a,lu=(a,e,t,i)=>{var n;let r=Z((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&Z(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&ET()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=TT(o)?"video":"audio",l=TT(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var kw=Object.create;var ph=Object.defineProperty;var Aw=Object.getOwnPropertyDescriptor;var Rw=Object.getOwnPropertyNames;var $w=Object.getPrototypeOf,Mw=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Cw=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Rw(e))!Mw.call(a,r)&&r!==t&&ph(a,r,{get:()=>e[r],enumerable:!(i=Aw(e,r))||i.enumerable});return a};var _=(a,e,t)=>(t=a!=null?kw($w(a)):{},Cw(e||!a||!a.__esModule?ph(t,"default",{value:a,enumerable:!0}):t,a));var ne=b(($u,mh)=>{"use strict";var Jr=function(a){return a&&a.Math===Math&&a};mh.exports=Jr(typeof globalThis=="object"&&globalThis)||Jr(typeof window=="object"&&window)||Jr(typeof self=="object"&&self)||Jr(typeof global=="object"&&global)||Jr(typeof $u=="object"&&$u)||function(){return this}()||Function("return this")()});var me=b((CO,fh)=>{"use strict";fh.exports=function(a){try{return!!a()}catch(e){return!0}}});var Zr=b((LO,bh)=>{"use strict";var Lw=me();bh.exports=!Lw(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Mu=b((DO,yh)=>{"use strict";var Dw=Zr(),Sh=Function.prototype,gh=Sh.apply,vh=Sh.call;yh.exports=typeof Reflect=="object"&&Reflect.apply||(Dw?vh.bind(gh):function(){return vh.apply(gh,arguments)})});var fe=b((BO,Eh)=>{"use strict";var Th=Zr(),Ih=Function.prototype,Cu=Ih.call,Bw=Th&&Ih.bind.bind(Cu,Cu);Eh.exports=Th?Bw:function(a){return function(){return Cu.apply(a,arguments)}}});var vi=b((VO,xh)=>{"use strict";var wh=fe(),Vw=wh({}.toString),_w=wh("".slice);xh.exports=function(a){return _w(Vw(a),8,-1)}});var Lu=b((_O,Ph)=>{"use strict";var Ow=vi(),Nw=fe();Ph.exports=function(a){if(Ow(a)==="Function")return Nw(a)}});var oe=b((OO,kh)=>{"use strict";var Du=typeof document=="object"&&document.all;kh.exports=typeof Du=="undefined"&&Du!==void 0?function(a){return typeof a=="function"||a===Du}:function(a){return typeof a=="function"}});var qe=b((NO,Ah)=>{"use strict";var Fw=me();Ah.exports=!Fw(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ue=b((FO,Rh)=>{"use strict";var qw=Zr(),dn=Function.prototype.call;Rh.exports=qw?dn.bind(dn):function(){return dn.apply(dn,arguments)}});var Bu=b(Ch=>{"use strict";var $h={}.propertyIsEnumerable,Mh=Object.getOwnPropertyDescriptor,Uw=Mh&&!$h.call({1:2},1);Ch.f=Uw?function(e){var t=Mh(this,e);return!!t&&t.enumerable}:$h});var ea=b((UO,Lh)=>{"use strict";Lh.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Bh=b((jO,Dh)=>{"use strict";var jw=fe(),Hw=me(),Qw=vi(),Vu=Object,Ww=jw("".split);Dh.exports=Hw(function(){return!Vu("z").propertyIsEnumerable(0)})?function(a){return Qw(a)==="String"?Ww(a,""):Vu(a)}:Vu});var ta=b((HO,Vh)=>{"use strict";Vh.exports=function(a){return a==null}});var Qt=b((QO,_h)=>{"use strict";var zw=ta(),Gw=TypeError;_h.exports=function(a){if(zw(a))throw new Gw("Can't call method on "+a);return a}});var Si=b((WO,Oh)=>{"use strict";var Yw=Bh(),Kw=Qt();Oh.exports=function(a){return Yw(Kw(a))}});var Le=b((zO,Nh)=>{"use strict";var Xw=oe();Nh.exports=function(a){return typeof a=="object"?a!==null:Xw(a)}});var yi=b((GO,Fh)=>{"use strict";Fh.exports={}});var Pt=b((YO,Uh)=>{"use strict";var _u=yi(),Ou=ne(),Jw=oe(),qh=function(a){return Jw(a)?a:void 0};Uh.exports=function(a,e){return arguments.length<2?qh(_u[a])||qh(Ou[a]):_u[a]&&_u[a][e]||Ou[a]&&Ou[a][e]}});var ia=b((KO,jh)=>{"use strict";var Zw=fe();jh.exports=Zw({}.isPrototypeOf)});var Ti=b((XO,Wh)=>{"use strict";var ex=ne(),Hh=ex.navigator,Qh=Hh&&Hh.userAgent;Wh.exports=Qh?String(Qh):""});var Fu=b((JO,Jh)=>{"use strict";var Xh=ne(),Nu=Ti(),zh=Xh.process,Gh=Xh.Deno,Yh=zh&&zh.versions||Gh&&Gh.version,Kh=Yh&&Yh.v8,rt,pn;Kh&&(rt=Kh.split("."),pn=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!pn&&Nu&&(rt=Nu.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Nu.match(/Chrome\/(\d+)/),rt&&(pn=+rt[1])));Jh.exports=pn});var qu=b((ZO,em)=>{"use strict";var Zh=Fu(),tx=me(),ix=ne(),rx=ix.String;em.exports=!!Object.getOwnPropertySymbols&&!tx(function(){var a=Symbol("symbol detection");return!rx(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Zh&&Zh<41})});var Uu=b((eN,tm)=>{"use strict";var ax=qu();tm.exports=ax&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ju=b((tN,im)=>{"use strict";var sx=Pt(),nx=oe(),ox=ia(),ux=Uu(),lx=Object;im.exports=ux?function(a){return typeof a=="symbol"}:function(a){var e=sx("Symbol");return nx(e)&&ox(e.prototype,lx(a))}});var ra=b((iN,rm)=>{"use strict";var cx=String;rm.exports=function(a){try{return cx(a)}catch(e){return"Object"}}});var mt=b((rN,am)=>{"use strict";var dx=oe(),px=ra(),hx=TypeError;am.exports=function(a){if(dx(a))return a;throw new hx(px(a)+" is not a function")}});var aa=b((aN,sm)=>{"use strict";var mx=mt(),fx=ta();sm.exports=function(a,e){var t=a[e];return fx(t)?void 0:mx(t)}});var om=b((sN,nm)=>{"use strict";var Hu=Ue(),Qu=oe(),Wu=Le(),bx=TypeError;nm.exports=function(a,e){var t,i;if(e==="string"&&Qu(t=a.toString)&&!Wu(i=Hu(t,a))||Qu(t=a.valueOf)&&!Wu(i=Hu(t,a))||e!=="string"&&Qu(t=a.toString)&&!Wu(i=Hu(t,a)))return i;throw new bx("Can't convert object to primitive value")}});var at=b((nN,um)=>{"use strict";um.exports=!0});var dm=b((oN,cm)=>{"use strict";var lm=ne(),gx=Object.defineProperty;cm.exports=function(a,e){try{gx(lm,a,{value:e,configurable:!0,writable:!0})}catch(t){lm[a]=e}return e}});var sa=b((uN,mm)=>{"use strict";var vx=at(),Sx=ne(),yx=dm(),pm="__core-js_shared__",hm=mm.exports=Sx[pm]||yx(pm,{});(hm.versions||(hm.versions=[])).push({version:"3.43.0",mode:vx?"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 zu=b((lN,bm)=>{"use strict";var fm=sa();bm.exports=function(a,e){return fm[a]||(fm[a]=e||{})}});var ir=b((cN,gm)=>{"use strict";var Tx=Qt(),Ix=Object;gm.exports=function(a){return Ix(Tx(a))}});var st=b((dN,vm)=>{"use strict";var Ex=fe(),wx=ir(),xx=Ex({}.hasOwnProperty);vm.exports=Object.hasOwn||function(e,t){return xx(wx(e),t)}});var Gu=b((pN,Sm)=>{"use strict";var Px=fe(),kx=0,Ax=Math.random(),Rx=Px(1.1.toString);Sm.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Rx(++kx+Ax,36)}});var Ie=b((hN,Tm)=>{"use strict";var $x=ne(),Mx=zu(),ym=st(),Cx=Gu(),Lx=qu(),Dx=Uu(),rr=$x.Symbol,Yu=Mx("wks"),Bx=Dx?rr.for||rr:rr&&rr.withoutSetter||Cx;Tm.exports=function(a){return ym(Yu,a)||(Yu[a]=Lx&&ym(rr,a)?rr[a]:Bx("Symbol."+a)),Yu[a]}});var xm=b((mN,wm)=>{"use strict";var Vx=Ue(),Im=Le(),Em=ju(),_x=aa(),Ox=om(),Nx=Ie(),Fx=TypeError,qx=Nx("toPrimitive");wm.exports=function(a,e){if(!Im(a)||Em(a))return a;var t=_x(a,qx),i;if(t){if(e===void 0&&(e="default"),i=Vx(t,a,e),!Im(i)||Em(i))return i;throw new Fx("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ox(a,e)}});var Ku=b((fN,Pm)=>{"use strict";var Ux=xm(),jx=ju();Pm.exports=function(a){var e=Ux(a,"string");return jx(e)?e:e+""}});var hn=b((bN,Am)=>{"use strict";var Hx=ne(),km=Le(),Xu=Hx.document,Qx=km(Xu)&&km(Xu.createElement);Am.exports=function(a){return Qx?Xu.createElement(a):{}}});var Ju=b((gN,Rm)=>{"use strict";var Wx=qe(),zx=me(),Gx=hn();Rm.exports=!Wx&&!zx(function(){return Object.defineProperty(Gx("div"),"a",{get:function(){return 7}}).a!==7})});var Cm=b(Mm=>{"use strict";var Yx=qe(),Kx=Ue(),Xx=Bu(),Jx=ea(),Zx=Si(),eP=Ku(),tP=st(),iP=Ju(),$m=Object.getOwnPropertyDescriptor;Mm.f=Yx?$m:function(e,t){if(e=Zx(e),t=eP(t),iP)try{return $m(e,t)}catch(i){}if(tP(e,t))return Jx(!Kx(Xx.f,e,t),e[t])}});var Zu=b((SN,Lm)=>{"use strict";var rP=me(),aP=oe(),sP=/#|\.prototype\./,na=function(a,e){var t=oP[nP(a)];return t===lP?!0:t===uP?!1:aP(e)?rP(e):!!e},nP=na.normalize=function(a){return String(a).replace(sP,".").toLowerCase()},oP=na.data={},uP=na.NATIVE="N",lP=na.POLYFILL="P";Lm.exports=na});var ar=b((yN,Bm)=>{"use strict";var Dm=Lu(),cP=mt(),dP=Zr(),pP=Dm(Dm.bind);Bm.exports=function(a,e){return cP(a),e===void 0?a:dP?pP(a,e):function(){return a.apply(e,arguments)}}});var el=b((TN,Vm)=>{"use strict";var hP=qe(),mP=me();Vm.exports=hP&&mP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=b((IN,_m)=>{"use strict";var fP=Le(),bP=String,gP=TypeError;_m.exports=function(a){if(fP(a))return a;throw new gP(bP(a)+" is not an object")}});var Ii=b(Nm=>{"use strict";var vP=qe(),SP=Ju(),yP=el(),mn=ft(),Om=Ku(),TP=TypeError,tl=Object.defineProperty,IP=Object.getOwnPropertyDescriptor,il="enumerable",rl="configurable",al="writable";Nm.f=vP?yP?function(e,t,i){if(mn(e),t=Om(t),mn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&al in i&&!i[al]){var r=IP(e,t);r&&r[al]&&(e[t]=i.value,i={configurable:rl in i?i[rl]:r[rl],enumerable:il in i?i[il]:r[il],writable:!1})}return tl(e,t,i)}:tl:function(e,t,i){if(mn(e),t=Om(t),mn(i),SP)try{return tl(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new TP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var sr=b((wN,Fm)=>{"use strict";var EP=qe(),wP=Ii(),xP=ea();Fm.exports=EP?function(a,e,t){return wP.f(a,e,xP(1,t))}:function(a,e,t){return a[e]=t,a}});var ce=b((xN,Um)=>{"use strict";var oa=ne(),PP=Mu(),kP=Lu(),AP=oe(),RP=Cm().f,$P=Zu(),nr=yi(),MP=ar(),or=sr(),qm=st();sa();var CP=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return PP(a,this,arguments)};return e.prototype=a.prototype,e};Um.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?oa:r?oa[t]:oa[t]&&oa[t].prototype,o=i?nr:nr[t]||or(nr,t,{})[t],u=o.prototype,l,d,c,p,h,m,f,v,g;for(p in e)l=$P(i?p:t+(r?".":"#")+p,a.forced),d=!l&&n&&qm(n,p),m=o[p],d&&(a.dontCallGetSet?(g=RP(n,p),f=g&&g.value):f=n[p]),h=d&&f?f:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&d?v=MP(h,oa):a.wrap&&d?v=CP(h):s&&AP(h)?v=kP(h):v=h,(a.sham||h&&h.sham||m&&m.sham)&&or(v,"sham",!0),or(o,p,v),s&&(c=t+"Prototype",qm(nr,c)||or(nr,c,{}),or(nr[c],p,h),a.real&&u&&(l||!u[p])&&or(u,p,h)))}});var fn=b((PN,Hm)=>{"use strict";var LP=zu(),DP=Gu(),jm=LP("keys");Hm.exports=function(a){return jm[a]||(jm[a]=DP(a))}});var Wm=b((kN,Qm)=>{"use strict";var BP=me();Qm.exports=!BP(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var bn=b((AN,Gm)=>{"use strict";var VP=st(),_P=oe(),OP=ir(),NP=fn(),FP=Wm(),zm=NP("IE_PROTO"),sl=Object,qP=sl.prototype;Gm.exports=FP?sl.getPrototypeOf:function(a){var e=OP(a);if(VP(e,zm))return e[zm];var t=e.constructor;return _P(t)&&e instanceof t?t.prototype:e instanceof sl?qP:null}});var Km=b((RN,Ym)=>{"use strict";var UP=Math.ceil,jP=Math.floor;Ym.exports=Math.trunc||function(e){var t=+e;return(t>0?jP:UP)(t)}});var ua=b(($N,Xm)=>{"use strict";var HP=Km();Xm.exports=function(a){var e=+a;return e!==e||e===0?0:HP(e)}});var Zm=b((MN,Jm)=>{"use strict";var QP=ua(),WP=Math.max,zP=Math.min;Jm.exports=function(a,e){var t=QP(a);return t<0?WP(t+e,0):zP(t,e)}});var nl=b((CN,ef)=>{"use strict";var GP=ua(),YP=Math.min;ef.exports=function(a){var e=GP(a);return e>0?YP(e,9007199254740991):0}});var ur=b((LN,tf)=>{"use strict";var KP=nl();tf.exports=function(a){return KP(a.length)}});var ol=b((DN,af)=>{"use strict";var XP=Si(),JP=Zm(),ZP=ur(),rf=function(a){return function(e,t,i){var r=XP(e),s=ZP(r);if(s===0)return!a&&-1;var n=JP(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};af.exports={includes:rf(!0),indexOf:rf(!1)}});var gn=b((BN,sf)=>{"use strict";sf.exports={}});var uf=b((VN,of)=>{"use strict";var ek=fe(),ul=st(),tk=Si(),ik=ol().indexOf,rk=gn(),nf=ek([].push);of.exports=function(a,e){var t=tk(a),i=0,r=[],s;for(s in t)!ul(rk,s)&&ul(t,s)&&nf(r,s);for(;e.length>i;)ul(t,s=e[i++])&&(~ik(r,s)||nf(r,s));return r}});var ll=b((_N,lf)=>{"use strict";lf.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var cl=b((ON,cf)=>{"use strict";var ak=uf(),sk=ll();cf.exports=Object.keys||function(e){return ak(e,sk)}});var dl=b((NN,ff)=>{"use strict";var pf=qe(),nk=me(),hf=fe(),ok=bn(),uk=cl(),lk=Si(),ck=Bu().f,mf=hf(ck),dk=hf([].push),pk=pf&&nk(function(){var a=Object.create(null);return a[2]=2,!mf(a,2)}),df=function(a){return function(e){for(var t=lk(e),i=uk(t),r=pk&&ok(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!pf||(r?u in t:mf(t,u)))&&dk(o,a?[u,t[u]]:t[u]);return o}};ff.exports={entries:df(!0),values:df(!1)}});var bf=b(()=>{"use strict";var hk=ce(),mk=dl().values;hk({target:"Object",stat:!0},{values:function(e){return mk(e)}})});var vf=b((UN,gf)=>{"use strict";bf();var fk=yi();gf.exports=fk.Object.values});var yf=b((jN,Sf)=>{"use strict";var bk=vf();Sf.exports=bk});var Ei=b((HN,Tf)=>{"use strict";var gk=yf();Tf.exports=gk});var la=b((QN,If)=>{"use strict";If.exports=function(){}});var Ef=b(()=>{"use strict";var vk=ce(),Sk=ol().includes,yk=me(),Tk=la(),Ik=yk(function(){return!Array(1).includes()});vk({target:"Array",proto:!0,forced:Ik},{includes:function(e){return Sk(this,e,arguments.length>1?arguments[1]:void 0)}});Tk("includes")});var Wt=b((GN,wf)=>{"use strict";var Ek=Pt();wf.exports=Ek});var Pf=b((YN,xf)=>{"use strict";Ef();var wk=Wt();xf.exports=wk("Array","includes")});var Af=b((KN,kf)=>{"use strict";var xk=Pf();kf.exports=xk});var De=b((XN,Rf)=>{"use strict";var Pk=Af();Rf.exports=Pk});var ib=b(()=>{"use strict";var cA=ce(),dA=dl().entries;cA({target:"Object",stat:!0},{entries:function(e){return dA(e)}})});var ab=b((Xq,rb)=>{"use strict";ib();var pA=yi();rb.exports=pA.Object.entries});var nb=b((Jq,sb)=>{"use strict";var hA=ab();sb.exports=hA});var zt=b((Zq,ob)=>{"use strict";var mA=nb();ob.exports=mA});var Pi=b((eU,ub)=>{"use strict";ub.exports={}});var db=b((tU,cb)=>{"use strict";var fA=ne(),bA=oe(),lb=fA.WeakMap;cb.exports=bA(lb)&&/native code/.test(String(lb))});var Rl=b((iU,mb)=>{"use strict";var gA=db(),hb=ne(),vA=Le(),SA=sr(),Pl=st(),kl=sa(),yA=fn(),TA=gn(),pb="Object already initialized",Al=hb.TypeError,IA=hb.WeakMap,$n,ma,Mn,EA=function(a){return Mn(a)?ma(a):$n(a,{})},wA=function(a){return function(e){var t;if(!vA(e)||(t=ma(e)).type!==a)throw new Al("Incompatible receiver, "+a+" required");return t}};gA||kl.state?(nt=kl.state||(kl.state=new IA),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,$n=function(a,e){if(nt.has(a))throw new Al(pb);return e.facade=a,nt.set(a,e),e},ma=function(a){return nt.get(a)||{}},Mn=function(a){return nt.has(a)}):(ki=yA("state"),TA[ki]=!0,$n=function(a,e){if(Pl(a,ki))throw new Al(pb);return e.facade=a,SA(a,ki,e),e},ma=function(a){return Pl(a,ki)?a[ki]:{}},Mn=function(a){return Pl(a,ki)});var nt,ki;mb.exports={set:$n,get:ma,has:Mn,enforce:EA,getterFor:wA}});var Cl=b((rU,bb)=>{"use strict";var $l=qe(),xA=st(),fb=Function.prototype,PA=$l&&Object.getOwnPropertyDescriptor,Ml=xA(fb,"name"),kA=Ml&&function(){}.name==="something",AA=Ml&&(!$l||$l&&PA(fb,"name").configurable);bb.exports={EXISTS:Ml,PROPER:kA,CONFIGURABLE:AA}});var vb=b(gb=>{"use strict";var RA=qe(),$A=el(),MA=Ii(),CA=ft(),LA=Si(),DA=cl();gb.f=RA&&!$A?Object.defineProperties:function(e,t){CA(e);for(var i=LA(t),r=DA(t),s=r.length,n=0,o;s>n;)MA.f(e,o=r[n++],i[o]);return e}});var Ll=b((sU,Sb)=>{"use strict";var BA=Pt();Sb.exports=BA("document","documentElement")});var _l=b((nU,Pb)=>{"use strict";var VA=ft(),_A=vb(),yb=ll(),OA=gn(),NA=Ll(),FA=hn(),qA=fn(),Tb=">",Ib="<",Bl="prototype",Vl="script",wb=qA("IE_PROTO"),Dl=function(){},xb=function(a){return Ib+Vl+Tb+a+Ib+"/"+Vl+Tb},Eb=function(a){a.write(xb("")),a.close();var e=a.parentWindow.Object;return a=null,e},UA=function(){var a=FA("iframe"),e="java"+Vl+":",t;return a.style.display="none",NA.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(xb("document.F=Object")),t.close(),t.F},Cn,Ln=function(){try{Cn=new ActiveXObject("htmlfile")}catch(e){}Ln=typeof document!="undefined"?document.domain&&Cn?Eb(Cn):UA():Eb(Cn);for(var a=yb.length;a--;)delete Ln[Bl][yb[a]];return Ln()};OA[wb]=!0;Pb.exports=Object.create||function(e,t){var i;return e!==null?(Dl[Bl]=VA(e),i=new Dl,Dl[Bl]=null,i[wb]=e):i=Ln(),t===void 0?i:_A.f(i,t)}});var pr=b((oU,kb)=>{"use strict";var jA=sr();kb.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:jA(a,e,t),a}});var ql=b((uU,$b)=>{"use strict";var HA=me(),QA=oe(),WA=Le(),zA=_l(),Ab=bn(),GA=pr(),YA=Ie(),KA=at(),Fl=YA("iterator"),Rb=!1,At,Ol,Nl;[].keys&&(Nl=[].keys(),"next"in Nl?(Ol=Ab(Ab(Nl)),Ol!==Object.prototype&&(At=Ol)):Rb=!0);var XA=!WA(At)||HA(function(){var a={};return At[Fl].call(a)!==a});XA?At={}:KA&&(At=zA(At));QA(At[Fl])||GA(At,Fl,function(){return this});$b.exports={IteratorPrototype:At,BUGGY_SAFARI_ITERATORS:Rb}});var Dn=b((lU,Cb)=>{"use strict";var JA=Ie(),ZA=JA("toStringTag"),Mb={};Mb[ZA]="z";Cb.exports=String(Mb)==="[object z]"});var fa=b((cU,Lb)=>{"use strict";var eR=Dn(),tR=oe(),Bn=vi(),iR=Ie(),rR=iR("toStringTag"),aR=Object,sR=Bn(function(){return arguments}())==="Arguments",nR=function(a,e){try{return a[e]}catch(t){}};Lb.exports=eR?Bn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=nR(e=aR(a),rR))=="string"?t:sR?Bn(e):(i=Bn(e))==="Object"&&tR(e.callee)?"Arguments":i}});var Bb=b((dU,Db)=>{"use strict";var oR=Dn(),uR=fa();Db.exports=oR?{}.toString:function(){return"[object "+uR(this)+"]"}});var ba=b((pU,_b)=>{"use strict";var lR=Dn(),cR=Ii().f,dR=sr(),pR=st(),hR=Bb(),mR=Ie(),Vb=mR("toStringTag");_b.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(pR(r,Vb)||cR(r,Vb,{configurable:!0,value:e}),i&&!lR&&dR(r,"toString",hR))}});var Nb=b((hU,Ob)=>{"use strict";var fR=ql().IteratorPrototype,bR=_l(),gR=ea(),vR=ba(),SR=Pi(),yR=function(){return this};Ob.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=bR(fR,{next:gR(+!i,t)}),vR(a,r,!1,!0),SR[r]=yR,a}});var qb=b((mU,Fb)=>{"use strict";var TR=fe(),IR=mt();Fb.exports=function(a,e,t){try{return TR(IR(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var jb=b((fU,Ub)=>{"use strict";var ER=Le();Ub.exports=function(a){return ER(a)||a===null}});var Qb=b((bU,Hb)=>{"use strict";var wR=jb(),xR=String,PR=TypeError;Hb.exports=function(a){if(wR(a))return a;throw new PR("Can't set "+xR(a)+" as a prototype")}});var Ul=b((gU,Wb)=>{"use strict";var kR=qb(),AR=Le(),RR=Qt(),$R=Qb();Wb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=kR(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return RR(r),$R(s),AR(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var rg=b((vU,ig)=>{"use strict";var MR=ce(),CR=Ue(),Vn=at(),eg=Cl(),LR=oe(),DR=Nb(),zb=bn(),Gb=Ul(),BR=ba(),VR=sr(),jl=pr(),_R=Ie(),Yb=Pi(),tg=ql(),OR=eg.PROPER,NR=eg.CONFIGURABLE,Kb=tg.IteratorPrototype,_n=tg.BUGGY_SAFARI_ITERATORS,ga=_R("iterator"),Xb="keys",va="values",Jb="entries",Zb=function(){return this};ig.exports=function(a,e,t,i,r,s,n){DR(t,e,i);var o=function(g){if(g===r&&p)return p;if(!_n&&g&&g in d)return d[g];switch(g){case Xb:return function(){return new t(this,g)};case va:return function(){return new t(this,g)};case Jb:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[ga]||d["@@iterator"]||r&&d[r],p=!_n&&c||o(r),h=e==="Array"&&d.entries||c,m,f,v;if(h&&(m=zb(h.call(new a)),m!==Object.prototype&&m.next&&(!Vn&&zb(m)!==Kb&&(Gb?Gb(m,Kb):LR(m[ga])||jl(m,ga,Zb)),BR(m,u,!0,!0),Vn&&(Yb[u]=Zb))),OR&&r===va&&c&&c.name!==va&&(!Vn&&NR?VR(d,"name",va):(l=!0,p=function(){return CR(c,this)})),r)if(f={values:o(va),keys:s?p:o(Xb),entries:o(Jb)},n)for(v in f)(_n||l||!(v in d))&&jl(d,v,f[v]);else MR({target:e,proto:!0,forced:_n||l},f);return(!Vn||n)&&d[ga]!==p&&jl(d,ga,p,{name:r}),Yb[e]=p,f}});var sg=b((SU,ag)=>{"use strict";ag.exports=function(a,e){return{value:a,done:e}}});var Ql=b((yU,cg)=>{"use strict";var FR=Si(),Hl=la(),ng=Pi(),ug=Rl(),qR=Ii().f,UR=rg(),On=sg(),jR=at(),HR=qe(),lg="Array Iterator",QR=ug.set,WR=ug.getterFor(lg);cg.exports=UR(Array,"Array",function(a,e){QR(this,{type:lg,target:FR(a),index:0,kind:e})},function(){var a=WR(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,On(void 0,!0);switch(a.kind){case"keys":return On(t,!1);case"values":return On(e[t],!1)}return On([t,e[t]],!1)},"values");var og=ng.Arguments=ng.Array;Hl("keys");Hl("values");Hl("entries");if(!jR&&HR&&og.name!=="values")try{qR(og,"name",{value:"values"})}catch(a){}});var pg=b((TU,dg)=>{"use strict";var zR=Ie(),GR=Pi(),YR=zR("iterator"),KR=Array.prototype;dg.exports=function(a){return a!==void 0&&(GR.Array===a||KR[YR]===a)}});var Wl=b((IU,mg)=>{"use strict";var XR=fa(),hg=aa(),JR=ta(),ZR=Pi(),e$=Ie(),t$=e$("iterator");mg.exports=function(a){if(!JR(a))return hg(a,t$)||hg(a,"@@iterator")||ZR[XR(a)]}});var bg=b((EU,fg)=>{"use strict";var i$=Ue(),r$=mt(),a$=ft(),s$=ra(),n$=Wl(),o$=TypeError;fg.exports=function(a,e){var t=arguments.length<2?n$(a):e;if(r$(t))return a$(i$(t,a));throw new o$(s$(a)+" is not iterable")}});var Sg=b((wU,vg)=>{"use strict";var u$=Ue(),gg=ft(),l$=aa();vg.exports=function(a,e,t){var i,r;gg(a);try{if(i=l$(a,"return"),!i){if(e==="throw")throw t;return t}i=u$(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return gg(i),t}});var Fn=b((xU,Eg)=>{"use strict";var c$=ar(),d$=Ue(),p$=ft(),h$=ra(),m$=pg(),f$=ur(),yg=ia(),b$=bg(),g$=Wl(),Tg=Sg(),v$=TypeError,Nn=function(a,e){this.stopped=a,this.result=e},Ig=Nn.prototype;Eg.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=c$(e,i),l,d,c,p,h,m,f,v=function(S){return l&&Tg(l,"normal"),new Nn(!0,S)},g=function(S){return r?(p$(S),o?u(S[0],S[1],v):u(S[0],S[1])):o?u(S,v):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(d=g$(a),!d)throw new v$(h$(a)+" is not iterable");if(m$(d)){for(c=0,p=f$(a);p>c;c++)if(h=g(a[c]),h&&yg(Ig,h))return h;return new Nn(!1)}l=b$(a,d)}for(m=s?a.next:l.next;!(f=d$(m,l)).done;){try{h=g(f.value)}catch(S){Tg(l,"throw",S)}if(typeof h=="object"&&h&&yg(Ig,h))return h}return new Nn(!1)}});var xg=b((PU,wg)=>{"use strict";var S$=qe(),y$=Ii(),T$=ea();wg.exports=function(a,e,t){S$?y$.f(a,e,T$(0,t)):a[e]=t}});var Pg=b(()=>{"use strict";var I$=ce(),E$=Fn(),w$=xg();I$({target:"Object",stat:!0},{fromEntries:function(e){var t={};return E$(e,function(i,r){w$(t,i,r)},{AS_ENTRIES:!0}),t}})});var Ag=b((RU,kg)=>{"use strict";Ql();Pg();var x$=yi();kg.exports=x$.Object.fromEntries});var $g=b(($U,Rg)=>{"use strict";Rg.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 Cg=b(()=>{"use strict";Ql();var P$=$g(),k$=ne(),A$=ba(),Mg=Pi();for(qn in P$)A$(k$[qn],qn),Mg[qn]=Mg.Array;var qn});var Dg=b((LU,Lg)=>{"use strict";var R$=Ag();Cg();Lg.exports=R$});var zl=b((DU,Bg)=>{"use strict";var $$=Dg();Bg.exports=$$});var Vg=b(()=>{"use strict"});var Gl=b((_U,_g)=>{"use strict";var Sa=ne(),M$=Ti(),C$=vi(),Un=function(a){return M$.slice(0,a.length)===a};_g.exports=function(){return Un("Bun/")?"BUN":Un("Cloudflare-Workers")?"CLOUDFLARE":Un("Deno/")?"DENO":Un("Node.js/")?"NODE":Sa.Bun&&typeof Bun.version=="string"?"BUN":Sa.Deno&&typeof Deno.version=="object"?"DENO":C$(Sa.process)==="process"?"NODE":Sa.window&&Sa.document?"BROWSER":"REST"}()});var jn=b((OU,Og)=>{"use strict";var L$=Gl();Og.exports=L$==="NODE"});var Fg=b((NU,Ng)=>{"use strict";var D$=Ii();Ng.exports=function(a,e,t){return D$.f(a,e,t)}});var jg=b((FU,Ug)=>{"use strict";var B$=Pt(),V$=Fg(),_$=Ie(),O$=qe(),qg=_$("species");Ug.exports=function(a){var e=B$(a);O$&&e&&!e[qg]&&V$(e,qg,{configurable:!0,get:function(){return this}})}});var Qg=b((qU,Hg)=>{"use strict";var N$=ia(),F$=TypeError;Hg.exports=function(a,e){if(N$(e,a))return a;throw new F$("Incorrect invocation")}});var Kl=b((UU,Wg)=>{"use strict";var q$=fe(),U$=oe(),Yl=sa(),j$=q$(Function.toString);U$(Yl.inspectSource)||(Yl.inspectSource=function(a){return j$(a)});Wg.exports=Yl.inspectSource});var Jl=b((jU,Xg)=>{"use strict";var H$=fe(),Q$=me(),zg=oe(),W$=fa(),z$=Pt(),G$=Kl(),Gg=function(){},Yg=z$("Reflect","construct"),Xl=/^\s*(?:class|function)\b/,Y$=H$(Xl.exec),K$=!Xl.test(Gg),ya=function(e){if(!zg(e))return!1;try{return Yg(Gg,[],e),!0}catch(t){return!1}},Kg=function(e){if(!zg(e))return!1;switch(W$(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return K$||!!Y$(Xl,G$(e))}catch(t){return!0}};Kg.sham=!0;Xg.exports=!Yg||Q$(function(){var a;return ya(ya.call)||!ya(Object)||!ya(function(){a=!0})||a})?Kg:ya});var Zg=b((HU,Jg)=>{"use strict";var X$=Jl(),J$=ra(),Z$=TypeError;Jg.exports=function(a){if(X$(a))return a;throw new Z$(J$(a)+" is not a constructor")}});var Zl=b((QU,tv)=>{"use strict";var ev=ft(),eM=Zg(),tM=ta(),iM=Ie(),rM=iM("species");tv.exports=function(a,e){var t=ev(a).constructor,i;return t===void 0||tM(i=ev(t)[rM])?e:eM(i)}});var rv=b((WU,iv)=>{"use strict";var aM=fe();iv.exports=aM([].slice)});var sv=b((zU,av)=>{"use strict";var sM=TypeError;av.exports=function(a,e){if(a<e)throw new sM("Not enough arguments");return a}});var ec=b((GU,nv)=>{"use strict";var nM=Ti();nv.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(nM)});var lc=b((YU,fv)=>{"use strict";var He=ne(),oM=Mu(),uM=ar(),ov=oe(),lM=st(),mv=me(),uv=Ll(),cM=rv(),lv=hn(),dM=sv(),pM=ec(),hM=jn(),nc=He.setImmediate,oc=He.clearImmediate,mM=He.process,tc=He.Dispatch,fM=He.Function,cv=He.MessageChannel,bM=He.String,ic=0,Ta={},dv="onreadystatechange",Ia,Ai,rc,ac;mv(function(){Ia=He.location});var uc=function(a){if(lM(Ta,a)){var e=Ta[a];delete Ta[a],e()}},sc=function(a){return function(){uc(a)}},pv=function(a){uc(a.data)},hv=function(a){He.postMessage(bM(a),Ia.protocol+"//"+Ia.host)};(!nc||!oc)&&(nc=function(e){dM(arguments.length,1);var t=ov(e)?e:fM(e),i=cM(arguments,1);return Ta[++ic]=function(){oM(t,void 0,i)},Ai(ic),ic},oc=function(e){delete Ta[e]},hM?Ai=function(a){mM.nextTick(sc(a))}:tc&&tc.now?Ai=function(a){tc.now(sc(a))}:cv&&!pM?(rc=new cv,ac=rc.port2,rc.port1.onmessage=pv,Ai=uM(ac.postMessage,ac)):He.addEventListener&&ov(He.postMessage)&&!He.importScripts&&Ia&&Ia.protocol!=="file:"&&!mv(hv)?(Ai=hv,He.addEventListener("message",pv,!1)):dv in lv("script")?Ai=function(a){uv.appendChild(lv("script"))[dv]=function(){uv.removeChild(this),uc(a)}}:Ai=function(a){setTimeout(sc(a),0)});fv.exports={set:nc,clear:oc}});var vv=b((KU,gv)=>{"use strict";var bv=ne(),gM=qe(),vM=Object.getOwnPropertyDescriptor;gv.exports=function(a){if(!gM)return bv[a];var e=vM(bv,a);return e&&e.value}});var cc=b((XU,yv)=>{"use strict";var Sv=function(){this.head=null,this.tail=null};Sv.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};yv.exports=Sv});var Iv=b((JU,Tv)=>{"use strict";var SM=Ti();Tv.exports=/ipad|iphone|ipod/i.test(SM)&&typeof Pebble!="undefined"});var wv=b((ZU,Ev)=>{"use strict";var yM=Ti();Ev.exports=/web0s(?!.*chrome)/i.test(yM)});var Mv=b((e1,$v)=>{"use strict";var mr=ne(),TM=vv(),xv=ar(),dc=lc().set,IM=cc(),EM=ec(),wM=Iv(),xM=wv(),pc=jn(),Pv=mr.MutationObserver||mr.WebKitMutationObserver,kv=mr.document,Av=mr.process,Hn=mr.Promise,fc=TM("queueMicrotask"),hr,hc,mc,Qn,Rv;fc||(Ea=new IM,wa=function(){var a,e;for(pc&&(a=Av.domain)&&a.exit();e=Ea.get();)try{e()}catch(t){throw Ea.head&&hr(),t}a&&a.enter()},!EM&&!pc&&!xM&&Pv&&kv?(hc=!0,mc=kv.createTextNode(""),new Pv(wa).observe(mc,{characterData:!0}),hr=function(){mc.data=hc=!hc}):!wM&&Hn&&Hn.resolve?(Qn=Hn.resolve(void 0),Qn.constructor=Hn,Rv=xv(Qn.then,Qn),hr=function(){Rv(wa)}):pc?hr=function(){Av.nextTick(wa)}:(dc=xv(dc,mr),hr=function(){dc(wa)}),fc=function(a){Ea.head||hr(),Ea.add(a)});var Ea,wa;$v.exports=fc});var Lv=b((t1,Cv)=>{"use strict";Cv.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Wn=b((i1,Dv)=>{"use strict";Dv.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ri=b((r1,Bv)=>{"use strict";var PM=ne();Bv.exports=PM.Promise});var fr=b((a1,Nv)=>{"use strict";var kM=ne(),xa=Ri(),AM=oe(),RM=Zu(),$M=Kl(),MM=Ie(),Vv=Gl(),CM=at(),bc=Fu(),_v=xa&&xa.prototype,LM=MM("species"),gc=!1,Ov=AM(kM.PromiseRejectionEvent),DM=RM("Promise",function(){var a=$M(xa),e=a!==String(xa);if(!e&&bc===66||CM&&!(_v.catch&&_v.finally))return!0;if(!bc||bc<51||!/native code/.test(a)){var t=new xa(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[LM]=i,gc=t.then(function(){})instanceof i,!gc)return!0}return!e&&(Vv==="BROWSER"||Vv==="DENO")&&!Ov});Nv.exports={CONSTRUCTOR:DM,REJECTION_EVENT:Ov,SUBCLASSING:gc}});var br=b((s1,qv)=>{"use strict";var Fv=mt(),BM=TypeError,VM=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new BM("Bad Promise constructor");e=i,t=r}),this.resolve=Fv(e),this.reject=Fv(t)};qv.exports.f=function(a){return new VM(a)}});var oS=b(()=>{"use strict";var _M=ce(),OM=at(),Kn=jn(),Gt=ne(),NM=yi(),yr=Ue(),Uv=pr(),jv=Ul(),FM=ba(),qM=jg(),UM=mt(),Yn=oe(),jM=Le(),HM=Qg(),QM=Zl(),Gv=lc().set,Ic=Mv(),WM=Lv(),zM=Wn(),GM=cc(),Yv=Rl(),Xn=Ri(),Ec=fr(),Kv=br(),Jn="Promise",Xv=Ec.CONSTRUCTOR,YM=Ec.REJECTION_EVENT,KM=Ec.SUBCLASSING,vc=Yv.getterFor(Jn),XM=Yv.set,gr=Xn&&Xn.prototype,$i=Xn,zn=gr,Jv=Gt.TypeError,Sc=Gt.document,wc=Gt.process,yc=Kv.f,JM=yc,ZM=!!(Sc&&Sc.createEvent&&Gt.dispatchEvent),Zv="unhandledrejection",eC="rejectionhandled",Hv=0,eS=1,tC=2,xc=1,tS=2,Gn,Qv,iS,Wv,rS=function(a){var e;return jM(a)&&Yn(e=a.then)?e:!1},aS=function(a,e){var t=e.value,i=e.state===eS,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{r?(i||(e.rejection===tS&&rC(e),e.rejection=xc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new Jv("Promise-chain cycle")):(l=rS(u))?yr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},sS=function(a,e){a.notified||(a.notified=!0,Ic(function(){for(var t=a.reactions,i;i=t.get();)aS(i,a);a.notified=!1,e&&!a.rejection&&iC(a)}))},nS=function(a,e,t){var i,r;ZM?(i=Sc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Gt.dispatchEvent(i)):i={promise:e,reason:t},!YM&&(r=Gt["on"+a])?r(i):a===Zv&&WM("Unhandled promise rejection",t)},iC=function(a){yr(Gv,Gt,function(){var e=a.facade,t=a.value,i=zv(a),r;if(i&&(r=zM(function(){Kn?wc.emit("unhandledRejection",t,e):nS(Zv,e,t)}),a.rejection=Kn||zv(a)?tS:xc,r.error))throw r.value})},zv=function(a){return a.rejection!==xc&&!a.parent},rC=function(a){yr(Gv,Gt,function(){var e=a.facade;Kn?wc.emit("rejectionHandled",e):nS(eC,e,a.value)})},vr=function(a,e,t){return function(i){a(e,i,t)}},Sr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=tC,sS(a,!0))},Tc=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Jv("Promise can't be resolved itself");var i=rS(e);i?Ic(function(){var r={done:!1};try{yr(i,e,vr(Tc,r,a),vr(Sr,r,a))}catch(s){Sr(r,s,a)}}):(a.value=e,a.state=eS,sS(a,!1))}catch(r){Sr({done:!1},r,a)}}};if(Xv&&($i=function(e){HM(this,zn),UM(e),yr(Gn,this);var t=vc(this);try{e(vr(Tc,t),vr(Sr,t))}catch(i){Sr(t,i)}},zn=$i.prototype,Gn=function(e){XM(this,{type:Jn,done:!1,notified:!1,parent:!1,reactions:new GM,rejection:!1,state:Hv,value:null})},Gn.prototype=Uv(zn,"then",function(e,t){var i=vc(this),r=yc(QM(this,$i));return i.parent=!0,r.ok=Yn(e)?e:!0,r.fail=Yn(t)&&t,r.domain=Kn?wc.domain:void 0,i.state===Hv?i.reactions.add(r):Ic(function(){aS(r,i)}),r.promise}),Qv=function(){var a=new Gn,e=vc(a);this.promise=a,this.resolve=vr(Tc,e),this.reject=vr(Sr,e)},Kv.f=yc=function(a){return a===$i||a===iS?new Qv(a):JM(a)},!OM&&Yn(Xn)&&gr!==Object.prototype)){Wv=gr.then,KM||Uv(gr,"then",function(e,t){var i=this;return new $i(function(r,s){yr(Wv,i,r,s)}).then(e,t)},{unsafe:!0});try{delete gr.constructor}catch(a){}jv&&jv(gr,zn)}_M({global:!0,constructor:!0,wrap:!0,forced:Xv},{Promise:$i});iS=NM.Promise;FM($i,Jn,!1,!0);qM(Jn)});var pS=b((u1,dS)=>{"use strict";var aC=Ie(),lS=aC("iterator"),cS=!1;try{uS=0,Pc={next:function(){return{done:!!uS++}},return:function(){cS=!0}},Pc[lS]=function(){return this},Array.from(Pc,function(){throw 2})}catch(a){}var uS,Pc;dS.exports=function(a,e){try{if(!e&&!cS)return!1}catch(r){return!1}var t=!1;try{var i={};i[lS]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var kc=b((l1,hS)=>{"use strict";var sC=Ri(),nC=pS(),oC=fr().CONSTRUCTOR;hS.exports=oC||!nC(function(a){sC.all(a).then(void 0,function(){})})});var mS=b(()=>{"use strict";var uC=ce(),lC=Ue(),cC=mt(),dC=br(),pC=Wn(),hC=Fn(),mC=kc();uC({target:"Promise",stat:!0,forced:mC},{all:function(e){var t=this,i=dC.f(t),r=i.resolve,s=i.reject,n=pC(function(){var o=cC(t.resolve),u=[],l=0,d=1;hC(e,function(c){var p=l++,h=!1;d++,lC(o,t,c).then(function(m){h||(h=!0,u[p]=m,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var bS=b(()=>{"use strict";var fC=ce(),bC=at(),gC=fr().CONSTRUCTOR,Rc=Ri(),vC=Pt(),SC=oe(),yC=pr(),fS=Rc&&Rc.prototype;fC({target:"Promise",proto:!0,forced:gC,real:!0},{catch:function(a){return this.then(void 0,a)}});!bC&&SC(Rc)&&(Ac=vC("Promise").prototype.catch,fS.catch!==Ac&&yC(fS,"catch",Ac,{unsafe:!0}));var Ac});var gS=b(()=>{"use strict";var TC=ce(),IC=Ue(),EC=mt(),wC=br(),xC=Wn(),PC=Fn(),kC=kc();TC({target:"Promise",stat:!0,forced:kC},{race:function(e){var t=this,i=wC.f(t),r=i.reject,s=xC(function(){var n=EC(t.resolve);PC(e,function(o){IC(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var vS=b(()=>{"use strict";var AC=ce(),RC=br(),$C=fr().CONSTRUCTOR;AC({target:"Promise",stat:!0,forced:$C},{reject:function(e){var t=RC.f(this),i=t.reject;return i(e),t.promise}})});var $c=b((v1,SS)=>{"use strict";var MC=ft(),CC=Le(),LC=br();SS.exports=function(a,e){if(MC(a),CC(e)&&e.constructor===a)return e;var t=LC.f(a),i=t.resolve;return i(e),t.promise}});var IS=b(()=>{"use strict";var DC=ce(),BC=Pt(),yS=at(),VC=Ri(),TS=fr().CONSTRUCTOR,_C=$c(),OC=BC("Promise"),NC=yS&&!TS;DC({target:"Promise",stat:!0,forced:yS||TS},{resolve:function(e){return _C(NC&&this===OC?VC:this,e)}})});var ES=b(()=>{"use strict";oS();mS();bS();gS();vS();IS()});var kS=b(()=>{"use strict";var FC=ce(),qC=at(),Zn=Ri(),UC=me(),xS=Pt(),PS=oe(),jC=Zl(),wS=$c(),HC=pr(),Cc=Zn&&Zn.prototype,QC=!!Zn&&UC(function(){Cc.finally.call({then:function(){}},function(){})});FC({target:"Promise",proto:!0,real:!0,forced:QC},{finally:function(a){var e=jC(this,xS("Promise")),t=PS(a);return this.then(t?function(i){return wS(e,a()).then(function(){return i})}:a,t?function(i){return wS(e,a()).then(function(){throw i})}:a)}});!qC&&PS(Zn)&&(Mc=xS("Promise").prototype.finally,Cc.finally!==Mc&&HC(Cc,"finally",Mc,{unsafe:!0}));var Mc});var RS=b((x1,AS)=>{"use strict";Vg();ES();kS();var WC=Wt();AS.exports=WC("Promise","finally")});var MS=b((P1,$S)=>{"use strict";var zC=RS();$S.exports=zC});var Lc=b((k1,CS)=>{"use strict";var GC=MS();CS.exports=GC});var XS=b(()=>{"use strict";var EL=ce(),wL=ir(),xL=ur(),PL=ua(),kL=la();EL({target:"Array",proto:!0},{at:function(e){var t=wL(this),i=xL(t),r=PL(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});kL("at")});var ZS=b((Aj,JS)=>{"use strict";XS();var AL=Wt();JS.exports=AL("Array","at")});var ty=b((Rj,ey)=>{"use strict";var RL=ZS();ey.exports=RL});var Ke=b(($j,iy)=>{"use strict";var $L=ty();iy.exports=$L});var pd=b((QQ,Ky)=>{"use strict";var BD=vi();Ky.exports=Array.isArray||function(e){return BD(e)==="Array"}});var Jy=b((WQ,Xy)=>{"use strict";var VD=TypeError,_D=9007199254740991;Xy.exports=function(a){if(a>_D)throw VD("Maximum allowed index exceeded");return a}});var tT=b((zQ,eT)=>{"use strict";var OD=pd(),ND=ur(),FD=Jy(),qD=ar(),Zy=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,d=n?qD(n,o):!1,c,p;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&OD(c)?(p=ND(c),u=Zy(a,e,c,p,u,s-1)-1):(FD(u+1),a[u]=c),u++),l++;return u};eT.exports=Zy});var sT=b((GQ,aT)=>{"use strict";var iT=pd(),UD=Jl(),jD=Le(),HD=Ie(),QD=HD("species"),rT=Array;aT.exports=function(a){var e;return iT(a)&&(e=a.constructor,UD(e)&&(e===rT||iT(e.prototype))?e=void 0:jD(e)&&(e=e[QD],e===null&&(e=void 0))),e===void 0?rT:e}});var oT=b((YQ,nT)=>{"use strict";var WD=sT();nT.exports=function(a,e){return new(WD(a))(e===0?0:e)}});var uT=b(()=>{"use strict";var zD=ce(),GD=tT(),YD=mt(),KD=ir(),XD=ur(),JD=oT();zD({target:"Array",proto:!0},{flatMap:function(e){var t=KD(this),i=XD(t),r;return YD(e),r=JD(t,0),r.length=GD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var lT=b(()=>{"use strict";var ZD=la();ZD("flatMap")});var dT=b((eW,cT)=>{"use strict";uT();lT();var eB=Wt();cT.exports=eB("Array","flatMap")});var hT=b((tW,pT)=>{"use strict";var tB=dT();pT.exports=tB});var ja=b((iW,mT)=>{"use strict";var iB=hT();mT.exports=iB});var Qa=b((SW,vT)=>{"use strict";var aB=fa(),sB=String;vT.exports=function(a){if(aB(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return sB(a)}});var md=b((yW,ST)=>{"use strict";ST.exports=`
|
|
7
|
+
\v\f\r \u2028\u2029\uFEFF`});var IT=b((TW,TT)=>{"use strict";var nB=fe(),oB=Qt(),uB=Qa(),bd=md(),yT=nB("".replace),lB=RegExp("^["+bd+"]+"),cB=RegExp("(^|[^"+bd+"])["+bd+"]+$"),fd=function(a){return function(e){var t=uB(oB(e));return a&1&&(t=yT(t,lB,"")),a&2&&(t=yT(t,cB,"$1")),t}};TT.exports={start:fd(1),end:fd(2),trim:fd(3)}});var PT=b((IW,xT)=>{"use strict";var dB=Cl().PROPER,pB=me(),ET=md(),wT="
";xT.exports=function(a){return pB(function(){return!!ET[a]()||wT[a]()!==wT||dB&&ET[a].name!==a})}});var gd=b((EW,kT)=>{"use strict";var hB=IT().start,mB=PT();kT.exports=mB("trimStart")?function(){return hB(this)}:"".trimStart});var RT=b(()=>{"use strict";var fB=ce(),AT=gd();fB({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==AT},{trimLeft:AT})});var MT=b(()=>{"use strict";RT();var bB=ce(),$T=gd();bB({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==$T},{trimStart:$T})});var LT=b((AW,CT)=>{"use strict";MT();var gB=Wt();CT.exports=gB("String","trimLeft")});var BT=b((RW,DT)=>{"use strict";var vB=LT();DT.exports=vB});var _T=b(($W,VT)=>{"use strict";var SB=BT();VT.exports=SB});var qT=b(()=>{"use strict"});var UT=b(()=>{"use strict"});var HT=b((hz,jT)=>{"use strict";var EB=Le(),wB=vi(),xB=Ie(),PB=xB("match");jT.exports=function(a){var e;return EB(a)&&((e=a[PB])!==void 0?!!e:wB(a)==="RegExp")}});var zT=b((mz,WT)=>{"use strict";var kB=ne(),AB=me(),QT=kB.RegExp,RB=!AB(function(){var a=!0;try{QT(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(QT.prototype,"flags").get.call(e);return o!==i||t!==i});WT.exports={correct:RB}});var YT=b((fz,GT)=>{"use strict";var $B=ft();GT.exports=function(){var a=$B(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var JT=b((bz,XT)=>{"use strict";var MB=Ue(),CB=st(),LB=ia(),KT=zT(),DB=YT(),BB=RegExp.prototype;XT.exports=KT.correct?function(a){return a.flags}:function(a){return!KT.correct&&LB(BB,a)&&!CB(a,"flags")?MB(DB,a):a.flags}});var eI=b((gz,ZT)=>{"use strict";var Id=fe(),VB=ir(),_B=Math.floor,yd=Id("".charAt),OB=Id("".replace),Td=Id("".slice),NB=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,FB=/\$([$&'`]|\d{1,2})/g;ZT.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=FB;return r!==void 0&&(r=VB(r),u=NB),OB(s,u,function(l,d){var c;switch(yd(d,0)){case"$":return"$";case"&":return a;case"`":return Td(e,0,t);case"'":return Td(e,n);case"<":c=r[Td(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=_B(p/10);return h===0?l:h<=o?i[h-1]===void 0?yd(d,1):i[h-1]+yd(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var rI=b(()=>{"use strict";var qB=ce(),UB=Ue(),wd=fe(),tI=Qt(),jB=oe(),HB=Le(),QB=HT(),Cr=Qa(),WB=aa(),zB=JT(),GB=eI(),YB=Ie(),KB=at(),XB=YB("replace"),JB=TypeError,Ed=wd("".indexOf),ZB=wd("".replace),iI=wd("".slice),e0=Math.max;qB({target:"String",proto:!0},{replaceAll:function(e,t){var i=tI(this),r,s,n,o,u,l,d,c,p,h,m=0,f="";if(HB(e)){if(r=QB(e),r&&(s=Cr(tI(zB(e))),!~Ed(s,"g")))throw new JB("`.replaceAll` does not allow non-global regexes");if(n=WB(e,XB),n)return UB(n,e,i,t);if(KB&&r)return ZB(Cr(i),e,t)}for(o=Cr(i),u=Cr(e),l=jB(t),l||(t=Cr(t)),d=u.length,c=e0(1,d),p=Ed(o,u);p!==-1;)h=l?Cr(t(u,p,o)):GB(u,o,p,[],void 0,t),f+=iI(o,m,p)+h,m=p+d,p=p+c>o.length?-1:Ed(o,u,p+c);return m<o.length&&(f+=iI(o,m)),f}})});var sI=b((yz,aI)=>{"use strict";qT();UT();rI();var t0=Wt();aI.exports=t0("String","replaceAll")});var oI=b((Tz,nI)=>{"use strict";var i0=sI();nI.exports=i0});var lI=b((Iz,uI)=>{"use strict";var r0=oI();uI.exports=r0});var dI=b((Ez,cI)=>{"use strict";var a0=ua(),s0=Qa(),n0=Qt(),o0=RangeError;cI.exports=function(e){var t=s0(n0(this)),i="",r=a0(e);if(r<0||r===1/0)throw new o0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var bI=b((wz,fI)=>{"use strict";var mI=fe(),u0=nl(),pI=Qa(),l0=dI(),c0=Qt(),d0=mI(l0),p0=mI("".slice),h0=Math.ceil,hI=function(a){return function(e,t,i){var r=pI(c0(e)),s=u0(t),n=r.length,o=i===void 0?" ":pI(i),u,l;return s<=n||o===""?r:(u=s-n,l=d0(o,h0(u/o.length)),l.length>u&&(l=p0(l,0,u)),a?r+l:l+r)}};fI.exports={start:hI(!1),end:hI(!0)}});var vI=b((xz,gI)=>{"use strict";var m0=Ti();gI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(m0)});var SI=b(()=>{"use strict";var f0=ce(),b0=bI().start,g0=vI();f0({target:"String",proto:!0,forced:g0},{padStart:function(e){return b0(this,e,arguments.length>1?arguments[1]:void 0)}})});var TI=b((Az,yI)=>{"use strict";SI();var v0=Wt();yI.exports=v0("String","padStart")});var EI=b((Rz,II)=>{"use strict";var S0=TI();II.exports=S0});var xI=b(($z,wI)=>{"use strict";var y0=EI();wI.exports=y0});var hh="2.0.150-dev.169e8a40.0";var Pe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Pe||{}),xt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(xt||{});var Xr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Xr||{}),Au=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Au||{});var Ru=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ru||{}),cn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(cn||{});var kp=_(Ei(),1),Sw=_(De(),1);import{assertNever as Bf,assertNonNullable as kk,isNonNullable as vn,ValueSubject as pl,Subject as Ak,Subscription as Rk,merge as $k,observableFrom as Mk,fromEvent as Mf,map as Cf,tap as Lf,filterChanged as Ck,isNullable as hl,ErrorCategory as Df}from"@vkontakte/videoplayer-shared/es2018";var $f=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Sn=class{constructor(e){this.connection$=new pl(void 0);this.castState$=new pl("NOT_AVAILABLE");this.errorEvent$=new Ak;this.realCastState$=new pl("NOT_AVAILABLE");this.subscription=new Rk;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=vn((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||$f("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Df.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){vn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();hl(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();hl(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(Mf(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Bf(r.sessionState)}})).add($k(Mf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Lf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Cf(r=>r.castState)),Mk([i.getCastState()])).pipe(Ck(),Cf(Lk),Lf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=vn(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();kk(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(hl(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?vn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Df.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Lk=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Bf(a)}};import{assertNonNullable as Sl,combine as yl,debounce as Tl,ErrorCategory as Jk,filter as cr,filterChanged as Kf,isNonNullable as Il,isNullable as Xf,map as Zk,Subscription as eA,ValueSubject as El}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as Dk,assertNonNullable as wi,ErrorCategory as Bk,getHighestQuality as Vk,isNonNullable as _f}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as Vf}from"@vkontakte/videoplayer-shared/es2018";var Ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Vf(t)}return a},yn=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:Vf(e)}};var In=a=>{var c;let{source:e,format:t,meta:i,output:r}=a,s,n,o;switch(t){case"MPEG":{let p=e[t];wi(p);let h=Vk(Object.keys(p));wi(h);let m=p[h];wi(m),s=m,n="video/mp4",o=Tn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];wi(p),s=p.url,n="application/x-mpegurl",o=Tn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];wi(p),s=p.url,n="application/dash+xml",o=Tn();break}case"DASH_LIVE_CMAF":{let p=e[t];wi(p),s=p.url,n="application/dash+xml",o=Of();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];wi(p),s=Ee(p.url),n="application/x-mpegurl",o=Of();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let p="Unsupported format for Chromecast",h=new Error(p);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Bk.VIDEO_PIPELINE,message:p,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return Dk(t)}let u=_k((c=i.videoId)!=null?c:s,n);u.contentUrl=s,u.streamType=o,u.metadata=Ok();let{title:l,subtitle:d}=i;return _f(l)&&(u.metadata.title=l),_f(d)&&(u.metadata.subtitle=d),u};function Tn(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function Of(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function _k(a,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(a,e):{contentId:a,contentType:e,metadata:{title:"",subtitle:""},streamType:Tn()}}function Ok(){var a,e;return(e=(a=chrome.cast)==null?void 0:a.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var k=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var En=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)}};import{assertNever as Yf}from"@vkontakte/videoplayer-shared/es2018";import{isBrowserWindow as Yk,ValueSubject as Kk}from"@vkontakte/videoplayer-shared/es2018";var Nf=_(De(),1);import{getWindow as Nk}from"@vkontakte/videoplayer-shared/es2018";var wn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Nf.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=Nk().navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Ff=_(De(),1);import{getWindow as ml,isBrowserWindow as fl}from"@vkontakte/videoplayer-shared/es2018";var xi=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var xn=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,Ff.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=ml();if(!fl(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=xi()}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=ml();if(!fl(e))return;let{userAgentData:t}=e.navigator;if(t!=null&&t.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r.length>0,o=r.length>1,u="Unknown",l="Unknown";if(n){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(u=s[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(l=s[d]):d!==void 0&&(l=d)}else s[2]!==void 0?l=s[2]:s[1]!==void 0&&n&&typeof r[0]=="string"&&(l=s[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 s=e.match(i);if(s){let n=r[0],o=r[1],u=typeof n=="number"?s[n]!==void 0?this.normalizeVendorName(s[n]):"Unknown":this.normalizeVendorName(n),l="Unknown";typeof o=="number"?l=s[o]!==void 0?s[o]:"Unknown":o!==void 0?l=o:s[1]!==void 0?l=s[1]:s[0]!==void 0&&(l=s[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=ml();if(!fl(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t!=null&&t[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};import{getWindow as qf,isBrowserWindow as Fk}from"@vkontakte/videoplayer-shared/es2018";var Pn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in qf()}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var s;let e=qf();if(!Fk(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((s=e.matchMedia("(dynamic-range: high)"))!=null&&s.matches),this._colorDepth=i.colorDepth}catch(n){console.error(n)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(n){console.error(n)}}};import{getWindow as bl,isBrowserWindow as Hf}from"@vkontakte/videoplayer-shared/es2018";var je=()=>window.ManagedMediaSource||window.MediaSource,lr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Uf=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},kn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var jf,qk=(jf=bl().document)==null?void 0:jf.createElement("video"),Uk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',jk='video/mp4; codecs="hev1.1.6.L93.B0"',Qf='video/webm; codecs="vp09.00.10.08"',Wf='video/webm; codecs="av01.0.00M.08"',Hk='audio/mp4; codecs="mp4a.40.2"',Qk='audio/webm; codecs="opus"',zf,Wk=async()=>{let a=bl();if(!Hf(a))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Wf}}),a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Qf}})]);zf={DASH_WEBM_AV1:t,DASH_WEBM:i}};Wk().catch(a=>{console.log(qk),console.error(a)});var An=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 zf}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,s,n,o,u,l,d,c,p,h,m,f,v,g,S,T,y,w,R;let e=bl();if(!Hf(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:lr(),mse:Uf(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(s=this._video).canPlayType)!=null&&n.call(s,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((d=(l=this._video).canPlayType)!=null&&d.call(l,"video/webm")),cmaf:!0};let L=!!((p=(c=je())==null?void 0:c.isTypeSupported)!=null&&p.call(c,Uk)),$=!!((m=(h=je())==null?void 0:h.isTypeSupported)!=null&&m.call(h,jk)),D=!!((v=(f=je())==null?void 0:f.isTypeSupported)!=null&&v.call(f,Hk));this._codecs={h264:L,h265:$,vp9:!!((S=(g=je())==null?void 0:g.isTypeSupported)!=null&&S.call(g,Qf)),av1:!!((y=(T=je())==null?void 0:T.isTypeSupported)!=null&&y.call(T,Wf)),aac:D,opus:!!((R=(w=je())==null?void 0:w.isTypeSupported)!=null&&R.call(w,Qk)),mpeg:(L||$)&&D},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(L){console.error(L)}try{this.destroyVideoElement()}catch(L){console.error("Error destroying video element:",L)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};import{getWindow as zk,isBrowserWindow as Gk}from"@vkontakte/videoplayer-shared/es2018";var Gf="audio/mpeg",Rn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,s,n;let e=zk();if(!Gk(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!((r=(i=this._audio).canPlayType)!=null&&r.call(i,Gf))},this._codecs={mp3:!!((n=(s=je())==null?void 0:s.isTypeSupported)!=null&&n.call(s,Gf))}}catch(o){console.error(o)}try{this.destroyAudioElement()}catch(o){console.error("Error destroying audio element:",o)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var gl=class{constructor(){this.isInited$=new Kk(!1);this._displayChecker=new Pn,this._deviceChecker=new xn(this._displayChecker),this._browserChecker=new wn,this._videoChecker=new An(this._deviceChecker,this._browserChecker),this._audioChecker=new Rn,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(){Yk()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},B=new gl;var vl=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=B.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Yf(o)}})},ca=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Yf(a)}},Xk=a=>{let t=Object.keys(a).filter(i=>!ca(i));return vl(t).length>0};var da=class{constructor(e){this.subscription=new eA;this.sessionId$=new El(null);this.mediaSessionId$=new El(null);this.contentId$=new El(null);this.isMobile=xi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var s,n,o;if(Xf(e))return;this.media=e,this.mediaSessionId$.next((s=e.mediaSessionId)!=null?s:null);let t=(n=e.media)==null?void 0:n.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=(o=e.media)==null?void 0:o.duration;Il(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(Il(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let l=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!l?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new En(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ca(e.format)),this.subscribe()}subscribe(){let e=r=>{var s;this.params.output.error$.next({category:Jk.WTF,id:"ChromecastPresentationApiProvider",message:(s=r==null?void 0:r.message)!=null?s:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(cr(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(cr(Il),Kf(),Tl(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(Kf(),Zk(Boolean));this.subscription.add(yl({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(cr(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=yl({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(cr(({mediaLoaded:r})=>r),Tl(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(cr(({mediaLoaded:r,playbackState:{from:s,to:n}})=>!r&&s==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(yl({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(Tl(30)),mediaLoaded:t}).pipe(cr(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:n}=r.to;this.setVolume(n,s)},e))}handleMessage(e){var t,i,r,s,n,o;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let u=(i=(t=e.message)==null?void 0:t.media)==null?void 0:i[0];this.syncMediaState(u);let l=(r=e.message)==null?void 0:r.receiver.volume;this.syncVolumeState(l)}break;case"v2_message":{switch((s=e.message)==null?void 0:s.type){case"MEDIA_STATUS":{let u=(o=(n=e.message)==null?void 0:n.status)==null?void 0:o[0];this.syncMediaState(u);break}}break}}}loadMedia(){var o;let e=In(this.params),t=(o=this.media)==null?void 0:o.currentTime,i=this.params.desiredState.seekState.getState(),r=t!=null?t:i.state!=="none"?i.position/1e3:0,n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Sl(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Sl(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Sl(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":k(this.params.desiredState.playbackState,"paused");break;case"PLAYING":k(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),k(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):k(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(Xf(e))return;let{level:t,muted:i}=e,r={muted:i!=null?i:!1,volume:t!=null?t:0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let s=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,s+=`, volume passed to state machine: ${r.volume}`),this.log({message:s}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as tA,ErrorCategory as wl,filter as iA,Subject as rA,Subscription as xl,tap as aA,ValueSubject as dr,fromEvent as pa}from"@vkontakte/videoplayer-shared/es2018";var Jf=a=>({castDevice:{friendlyName:a},remotePlayer:{},remotePlayerController:{},session:{}}),Zf=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var ha=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new dr(null);this.sessionId$=new dr(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new xl;this.subscriptionEvents=new xl;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new dr(!1);this.presentationConnection$=new dr(null);this.message$=new dr(null);this.friendlyName$=new dr(null);this.errorEvent$=new rA;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(pa(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){var e;this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let t=this.presentationRequest$.getValue();tA(t,"connect with null presentationRequest");let i=await t.start();this.handleConnection(i)}catch(t){switch(t==null?void 0:t.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:wl.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}}subscribe(){this.subscription.add(pa(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(aA(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),iA(e=>!!e)).subscribe(e=>{let t=pa(e,"message").subscribe(s=>{let n=JSON.parse(s.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(n),this.message$.next(n))}),i=pa(e,"connect").subscribe(()=>{this.send("client_connect")}),r=pa(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:wl.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:s});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();(t==null?void 0:t.state)==="connected"&&(t==null||t.send(e))}catch(t){this.errorEvent$.next({category:wl.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){var t;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":((t=e.message)==null?void 0:t.action)==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||Zf()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new xl}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))}};import{ValueSubject as eb,Subject as sA,map as nA,Subscription as oA,combine as uA,filterChanged as tb,assertNonNullable as lA}from"@vkontakte/videoplayer-shared/es2018";var kt=class a{constructor(e){this.subscription=new oA;this.connection$=new eb(void 0);this.castState$=new eb("NOT_AVAILABLE");this.errorEvent$=new sA;let t=a.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new ha({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){lA(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=uA({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(tb())});this.subscription.add(e.pipe(nA(({connection:t,friendlyName:i})=>!!(t&&i)),tb()).subscribe(t=>{var r,s;let i=(s=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?s:"";this.connection$.next(t?Jf(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){var e;this.log({message:"connect"}),(e=this.chromecastConnector)==null||e.connect()}disconnect(){var e;this.log({message:"disconnect"}),(e=this.chromecastConnector)==null||e.disconnect()}async stopMedia(){var e;this.log({message:"stopMedia"}),(e=this.chromecastConnector)==null||e.stopMedia()}toggleConnection(){var t;let e=!!((t=this.chromecastConnector)!=null&&t.presentationConnection$.getValue());this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){var e;this.log({message:"destroy"}),(e=this.chromecastConnector)==null||e.destroy(),this.subscription.unsubscribe()}};var fp=_(De(),1),bp=_(zt(),1),JE=_(zl(),1);var OS=_(Lc(),1);import{isNonNullable as YC,Subject as eo,merge as LS}from"@vkontakte/videoplayer-shared/es2018";var j=class{constructor(e){this.transitionStarted$=new eo;this.transitionEnded$=new eo;this.transitionUpdated$=new eo;this.forceChanged$=new eo;this.stateChangeStarted$=LS(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=LS(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||YC(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}};import{assertNever as Pa,debounce as DS,ErrorCategory as KC,fromEvent as Mi,map as BS,merge as VS,observableFrom as XC,Subject as JC,Subscription as Dc,timeout as ZC}from"@vkontakte/videoplayer-shared/es2018";var eL=5,tL=5,iL=500,_S=7e3,ka=class{constructor(e){this.subscription=new Dc;this.loadMediaTimeoutSubscription=new Dc;this.videoState=new j("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Pa(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:Pa(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:Pa(e)}break}default:Pa(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ca(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 Dc;this.subscription.add(e),this.subscription.add(VS(this.videoState.stateChangeStarted$.pipe(BS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(BS(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new JC;e.add(r.pipe(DS(iL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>eL)&&r.next(o),s=o})),e.add(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<tL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Pa(n)}}),t(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=VS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,XC(["init"])).pipe(DS(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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(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=In(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(ZC(_S).subscribe(()=>s(`timeout(${_S})`)))});(0,OS.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:KC.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Zc=_(De(),1);import{clearVideoElement as FS,getWindow as aL}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as rL}from"@vkontakte/videoplayer-shared/es2018";var NS=a=>{try{a.pause(),a.playbackRate=0,rL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as sL,Subscription as nL}from"@vkontakte/videoplayer-shared/es2018";var Bc=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)}},to=aL(),Vc=to.WeakMap?new to.WeakMap:new Bc,_c=to.WeakMap?new to.WeakMap:new Map,oL=(a,e=20)=>{let t=0;return sL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Be=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?FS(i):(i=document.createElement("video"),a.appendChild(i)),Vc.set(i,r);let s=new nL;return s.add(oL(i,e)),_c.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ve=a=>{let e=_c.get(a);e==null||e.unsubscribe(),_c.delete(a);let t=Vc.get(a);Vc.delete(a),t?FS(a):NS(a)};var Nc=_(Ei(),1);import{assertNonNullable as Ra,isNonNullable as vt,isNullable as cL,fromEvent as Tr,merge as qS,observableFrom as US,filterChanged as jS,map as $a,Subject as HS,Subscription as dL,ValueSubject as pL,ErrorCategory as hL}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Oc,isNullable as uL,Subscription as lL}from"@vkontakte/videoplayer-shared/es2018";var io=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=uL(r),l=new lL;return r&&l.add(r.subscribe(d=>{let c=a.getState();i(d,c)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},gt=(a,e,t)=>io(e,()=>a.loop,i=>{Oc(i)&&(a.loop=i)},{onError:t}),_e=(a,e,t,i)=>io(e,()=>({muted:a.muted,volume:a.volume}),r=>{Oc(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ge=(a,e,t,i)=>io(e,()=>a.playbackRate,r=>{Oc(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Aa=io;var mL=a=>["__",a.language,a.label].join("|"),fL=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Fc=class a{constructor(e){this.available$=new HS;this.current$=new pL(void 0);this.error$=new HS;this.subscription=new dL;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:hL.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Aa(t.internalTextTracks,()=>(0,Nc.default)(this.internalTracks),s=>{vt(s)&&this.setInternal(s)},{equal:(s,n)=>vt(s)&&vt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($a(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Aa(t.externalTextTracks,()=>(0,Nc.default)(this.externalTracks),s=>{vt(s)&&this.setExternal(s)},{equal:(s,n)=>vt(s)&&vt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($a(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Aa(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Aa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ra(this.video);let{textTracks:e}=this.video;this.subscription.add(Tr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(qS(Tr(e,"addtrack"),Tr(e,"removetrack"),US(["init"])).pipe($a(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),jS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(qS(Tr(e,"change"),US(["init"])).pipe($a(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),$a(i=>i&&this.htmlTextTrackToITextTrack(i).id),jS()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Tr(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,d,c,p,h;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Tr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;vt(t.align)&&(r.align=t.align),vt(t.position)&&(r.position=t.position),vt(t.size)&&(r.size=t.size),vt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ra(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:mL(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Ra(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(cL(e)||!fL(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){Ra(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){Ra(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)}},Ye=Fc;var Ci=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 QS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},qc=a=>{let e=QS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},WS=a=>{let e=QS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as ke,map as St,merge as ro,filterChanged as GS,isNonNullable as YS,Subject as gL,filter as Uc,mapTo as jc,combine as vL,once as SL,shareReplay as Ae,throttle as yL,ErrorCategory as TL,ValueSubject as KS,Subscription as IL}from"@vkontakte/videoplayer-shared/es2018";var bL=3,zS=(a,e,t=bL)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Oe=a=>{let e=A=>ke(a,A).pipe(jc(void 0),Ae(1)),t=new IL,i=()=>t.unsubscribe(),r=ro(ke(a,"progress"),ke(a,"timeupdate")).pipe(St(()=>zS(a.buffered,a.currentTime)),Ae(1)),s=B.browser.isSafari?vL({play:e("play").pipe(SL()),playing:e("playing")}).pipe(jc(void 0),Ae(1)):e("playing"),n=ke(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume})),Ae(1)),o=ke(a,"ratechange").pipe(St(()=>a.playbackRate),Ae(1)),u=ke(a,"error").pipe(Uc(()=>!!(a.error||a.played.length)),St(()=>{var V;let A=a.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:TL.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:(V=a.error)!=null?V:void 0}}),Ae(1)),l=ke(a,"timeupdate").pipe(St(()=>a.currentTime),Ae(1)),d=["waiting","seeking","seeked","timeupdate"],c=new gL,p=.3,h;t.add(ro(...d.map(A=>ke(a,A))).subscribe(A=>{let V=a.currentTime;a.loop&&YS(h)&&YS(V)&&h>=a.duration-p&&V<=p&&c.next(h),h=V}));let m=e("pause").pipe(Uc(()=>!a.error&&h!==a.duration),Ae(1)),f=ke(a,"enterpictureinpicture").pipe(Ae(1)),v=ke(a,"leavepictureinpicture").pipe(Ae(1)),g=new KS(WS(a));t.add(f.subscribe(()=>g.next(!0))),t.add(v.subscribe(()=>g.next(!1)));let S=new KS(qc(a)),T=ke(a,"fullscreenchange").pipe(Ae(1));t.add(T.pipe(St(()=>qc(a))).subscribe(S));let y=.1,w=1e3,R=ke(a,"timeupdate").pipe(St(A=>a.duration-a.currentTime<y),GS(),Ae(1)),L=ro(R.pipe(Uc(A=>!a.loop&&A)),ke(a,"ended")).pipe(yL(w),jc(void 0),Ae(1)),D=ro(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>ke(a,A)),R.pipe(St(A=>({type:A?"ended":"unknown"})))).pipe(St(A=>B.browser.isFirefox&&A.type==="ended"?a.readyState<2:a.readyState<3),GS(),Ae(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:L,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$:ke(a,"durationchange").pipe(St(()=>a.duration),Ae(1)),isBuffering$:D,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:v,destroy:i}};import{VideoQuality as Yt}from"@vkontakte/videoplayer-shared/es2018";var Kt=a=>{switch(a){case"mobile":return Yt.Q_144P;case"lowest":return Yt.Q_240P;case"low":return Yt.Q_360P;case"sd":case"medium":return Yt.Q_480P;case"hd":case"high":return Yt.Q_720P;case"fullhd":case"full":return Yt.Q_1080P;case"quadhd":case"quad":return Yt.Q_1440P;case"ultrahd":case"ultra":return Yt.Q_2160P}};var $e=_(Ke(),1),Qc=_(De(),1),Di=_(zt(),1);import{isNonNullable as X,isNullable as oo,now as hy,isHigher as uo,isHigherOrEqual as Li,isInvariantQuality as lo,isLowerOrEqual as Er,videoSizeToQuality as my,assertNotEmptyArray as co,assertNonNullable as fy}from"@vkontakte/videoplayer-shared/es2018";var Hc=!1,Rt={},ry=a=>{Hc=a},ay=()=>{Rt={}},sy=a=>{a(Rt)},Ma=(a,e)=>{var t;Hc&&(Rt.meta=(t=Rt.meta)!=null?t:{},Rt.meta[a]=e)},Re=class{constructor(e){this.name=e}next(e){var i,r;if(!Hc)return;Rt.series=(i=Rt.series)!=null?i:{};let t=(r=Rt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Rt.series[this.name]=t}};import{isHigher as ML,isHigherOrEqual as Vj,isLower as ny,isLowerOrEqual as _j,isNonNullable as ao,isNullable as CL,videoHeightToQuality as so}from"@vkontakte/videoplayer-shared/es2018";function oy(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Ir(a,e,t){return CL(a)||ao(a.min)&&ao(a.max)&&ny(a.max,a.min)||ao(a.min)&&e&&ML(a.min,e)||ao(a.max)&&t&&ny(a.max,t)}function uy({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Ir({max:a!=null&&a.max?so(a.max):void 0,min:a!=null&&a.min?so(a.min):void 0},e?so(e):void 0,t?so(t):void 0)}var by=new Re("best_bitrate"),po=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var wr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=hy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ho='Assertion "ABR Tracks is empty array" failed',no=new WeakMap,ly=new WeakMap,cy=new WeakMap,Ca=(a,e,t,i)=>{var u;let r=[...e].sort(wr(1)),s=[...t].sort(wr(1)),n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,$e.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,$e.default)(s,-1);return o&&(0,Qc.default)(n,o)?o:n.length?(0,$e.default)(n,-1):(0,$e.default)(s,0)},La=(a,e,t,i)=>{var u;let r=no.get(e);r||(r=[...e].sort(wr(1)),no.set(e,r));let s=no.get(t);s||(s=[...t].sort(wr(1)),no.set(t,s));let n=cy.get(a);n||(n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),cy.set(a,n));let o=(u=(0,$e.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,$e.default)(s,-1);return o&&(0,Qc.default)(n,o)?o:n.length?(0,$e.default)(n,-1):(0,$e.default)(s,0)},dy=a=>"quality"in a,mo=(a,e,t,i)=>{var n;let r=X((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&X(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&hy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=dy(o)?"video":"audio",l=dy(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t},
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},LL=(a,e)=>Math.log(e)/Math.log(a),gy=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&B.display.pixelRatio){let s=B.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,d=LL(n,o*s+u)+l;Number.isFinite(d)&&(r*=d)}}return X(t==null?void 0:t.min)&&Li(t.min,a.highQualityLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},py=new WeakMap,yt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{var q,G,H,E,P;co(a,ho);let{containerSizeFactor:v,containerSizeLimit:g}=gy({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&X(o)?o:1,T=py.get(a);T||(T=a.filter(I=>!lo(I.quality)).sort((I,x)=>uo(I.quality,x.quality)?-1:1),py.set(a,T));let y=(q=(0,$e.default)(T,-1))==null?void 0:q.quality,w=(G=(0,$e.default)(T,0))==null?void 0:G.quality,R=Ir(r,w,y),L=S*po(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},D=null;for(let I of T){let x=!0;if(g)if(I.size)x=I.size.width<=g.width&&I.size.height<=g.height;else{let Fe=g&&my(g);x=Fe?Er(I.quality,Fe):!0}if(!x){$[I.quality]="FitsContainer";continue}let F=h||t,O=X(F)&&isFinite(F)&&X(I.bitrate)?F-s>=I.bitrate*L:!0,ct=(r==null?void 0:r.min)===I.quality;if(!O&&!ct){$[I.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!lo(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&uo(I.quality,u.quality)){$[I.quality]="Buffer";continue}if(!!c&&Li(I.quality,c)&&!ct){$[I.quality]="DroppedFramesLimit";continue}if(!!p&&Li(I.quality,p)&&!ct){$[I.quality]="StallsLimit";continue}let ye=R||(oo(r==null?void 0:r.max)||Er(I.quality,r.max))&&(oo(r==null?void 0:r.min)||Li(I.quality,r.min)),Te=X(d)&&!d?Er(I.quality,i.backgroundVideoQualityLimit):!0;if(!ye||!Te){$[I.quality]="FitsQualityLimits";continue}D||(D=I)}D&&D.bitrate&&by.next(D.bitrate);let A=(H=D!=null?D:(0,$e.default)(T,-1))!=null?H:a[0],V=l==null?void 0:l.last,M=mo(i,m,A,l);return X(l)&&M.quality!==(V==null?void 0:V.quality)&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(
|
|
12
|
+
${a.map(I=>{var x,F;return`{ id: ${I.id}, quality: ${I.quality}, bitrate: ${I.bitrate}, size: ${(x=I.size)==null?void 0:x.width}:${(F=I.size)==null?void 0:F.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Di.default)(i!=null?i:{}).map(([I,x])=>`${I}: ${x}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
|
-
containerSizeFactor: ${
|
|
21
|
-
containerSizeLimit: ${(
|
|
20
|
+
containerSizeFactor: ${v},
|
|
21
|
+
containerSizeLimit: ${(E=g==null?void 0:g.width)!=null?E:0} x ${(P=g==null?void 0:g.height)!=null?P:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${h},
|
|
24
24
|
reserve: ${s},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${S},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${L},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
30
|
droppedVideoMaxQualityLimit: ${c},
|
|
31
31
|
stallsVideoMaxQualityLimit: ${p},
|
|
32
|
-
limitsAreInvalid: ${
|
|
32
|
+
limitsAreInvalid: ${R},
|
|
33
33
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
34
34
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,Di.default)($).map(([I,x])=>`${I}: ${x}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${D==null?void 0:D.quality}
|
|
41
|
+
[selected video track] ${M==null?void 0:M.quality}
|
|
42
|
+
`}),M},fo=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{var G,H,E,P,I;co(a,ho);let{containerSizeFactor:v,containerSizeLimit:g}=gy({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&X(o)?o:1,T=a.filter(x=>!lo(x.quality)).sort((x,F)=>uo(x.quality,F.quality)?-1:1),y=(G=(0,$e.default)(T,-1))==null?void 0:G.quality,w=(H=(0,$e.default)(T,0))==null?void 0:H.quality,R=Ir(r,w,y),L=S*po(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},A=T.filter(x=>{let F=!0;if(g)if(x.size)F=x.size.width<=g.width&&x.size.height<=g.height;else{let It=g&&my(g);F=It?Er(x.quality,It):!0}if(!F)return $[x.quality]="FitsContainer",!1;let O=h||t,ct=X(O)&&isFinite(O)&&X(x.bitrate)?O-s>=x.bitrate*L:!0,dt=(r==null?void 0:r.min)===x.quality;if(!ct&&!dt)return $[x.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!lo(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&uo(x.quality,u.quality))return $[x.quality]="Buffer",!1;if(!!c&&Li(x.quality,c)&&!dt)return $[x.quality]="DroppedFramesLimit",!1;if(!!p&&Li(x.quality,p)&&!dt)return $[x.quality]="StallsLimit",!1;let Te=R||(oo(r==null?void 0:r.max)||Er(x.quality,r.max))&&(oo(r==null?void 0:r.min)||Li(x.quality,r.min)),Fe=X(d)&&!d?Er(x.quality,i.backgroundVideoQualityLimit):!0;return!Te||!Fe?($[x.quality]="FitsQualityLimits",!1):!0})[0];A&&A.bitrate&&by.next(A.bitrate);let V=(E=A!=null?A:(0,$e.default)(T,-1))!=null?E:a[0],M=l==null?void 0:l.last,q=mo(i,m,V,l);return X(l)&&q.quality!==(M==null?void 0:M.quality)&&m({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${a.map(
|
|
45
|
+
${a.map(x=>{var F,O;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(F=x.size)==null?void 0:F.width}:${(O=x.size)==null?void 0:O.height} }`}).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,Di.default)(i!=null?i:{}).map(([x,F])=>`${x}: ${F}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
|
-
containerSizeFactor: ${
|
|
54
|
-
containerSizeLimit: ${(
|
|
53
|
+
containerSizeFactor: ${v},
|
|
54
|
+
containerSizeLimit: ${(P=g==null?void 0:g.width)!=null?P:0} x ${(I=g==null?void 0:g.height)!=null?I:0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
56
|
stallsPredictedThroughput: ${h},
|
|
57
57
|
reserve: ${s},
|
|
58
58
|
playbackRate: ${o},
|
|
59
|
-
playbackRateFactor: ${
|
|
59
|
+
playbackRateFactor: ${S},
|
|
60
60
|
forwardBufferHealth: ${n},
|
|
61
|
-
bitrateFactor: ${
|
|
61
|
+
bitrateFactor: ${L},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
63
|
droppedVideoMaxQualityLimit: ${c},
|
|
64
64
|
stallsVideoMaxQualityLimit: ${p},
|
|
65
|
-
limitsAreInvalid: ${
|
|
65
|
+
limitsAreInvalid: ${R},
|
|
66
66
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
67
67
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
68
68
|
|
|
69
69
|
[limited video tracks]
|
|
70
|
-
${(0,
|
|
70
|
+
${(0,Di.default)($).map(([x,F])=>`${x}: ${F}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
|
-
[best video track] ${
|
|
74
|
-
[selected video track] ${
|
|
75
|
-
`}),
|
|
73
|
+
[best video track] ${A==null?void 0:A.quality}
|
|
74
|
+
[selected video track] ${q==null?void 0:q.quality}
|
|
75
|
+
`}),q},bo=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{co(t,ho);let d=r.considerPlaybackRate&&X(s)?s:1,c=[...t].sort(wr(-1)),p=a.bitrate;fy(p);let h=d*po(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Ca(a,e,t,r.minVideoAudioRatio),v=l||i;X(v)&&isFinite(v)&&(m=c.find(T=>X(T.bitrate)&&X(f==null?void 0:f.bitrate)?v-p>=T.bitrate*h&&T.bitrate>=f.bitrate:!1)),m||(m=f);let g=o==null?void 0:o.last,S=m&&mo(r,u,m,o);return X(o)&&(S==null?void 0:S.bitrate)!==(g==null?void 0:g.bitrate)&&u({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
78
|
${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,
|
|
82
|
+
${(0,Di.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
@@ -92,15 +92,15 @@ var nP=Object.create;var Ef=Object.defineProperty;var oP=Object.getOwnPropertyDe
|
|
|
92
92
|
bitrateFactor: ${h},
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
|
-
[selected audio track] ${
|
|
96
|
-
`}),
|
|
95
|
+
[selected audio track] ${S==null?void 0:S.id}
|
|
96
|
+
`}),S},go=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{co(t,ho);let d=r.considerPlaybackRate&&X(s)?s:1,c=ly.get(t);c||(c=[...t].sort(wr(-1)),ly.set(t,c));let p=a.bitrate;fy(p);let h=d*po(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=La(a,e,t,r.minVideoAudioRatio),v=l||i;X(v)&&isFinite(v)&&(m=c.find(T=>X(T.bitrate)&&X(f==null?void 0:f.bitrate)?v-p>=T.bitrate*h&&T.bitrate>=f.bitrate:!1)),m||(m=f);let g=o==null?void 0:o.last,S=m&&mo(r,u,m,o);return X(o)&&(S==null?void 0:S.bitrate)!==(g==null?void 0:g.bitrate)&&u({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
99
|
${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,
|
|
103
|
+
${(0,Di.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
@@ -113,8 +113,8 @@ var nP=Object.create;var Ef=Object.defineProperty;var oP=Object.getOwnPropertyDe
|
|
|
113
113
|
bitrateFactor: ${h},
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
|
-
[selected audio track] ${
|
|
117
|
-
`}),v};var fe=a=>new URL(a).hostname;import{assertNever as UT,assertNonNullable as qT,combine as _C,debounce as OC,ErrorCategory as jT,filter as HT,filterChanged as NC,isNonNullable as Hd,map as hu,merge as WT,observableFrom as FC,once as UC,Subscription as qC,ValueSubject as Wd,videoQualityToHeight as zT,videoSizeToQuality as jC}from"@vkontakte/videoplayer-shared/es2018";var _T=O(Ye(),1);var RT=O(Re(),1),AT=a=>{if(a instanceof DOMException&&(0,RT.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Be=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!AT(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return AT(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as du,isNullable as vC,assertNonNullable as ya}from"@vkontakte/videoplayer-shared/es2018";var MT=O(ji(),1);import{isNonNullable as $T,assertNonNullable as cu,now as hC}from"@vkontakte/videoplayer-shared/es2018";function Te(){return hC()}function Nd(a){return Te()-a}function Fd(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function LT(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Zr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",f=7e3,m=2e3,g=()=>{if(u)return;cu(d);let D=Nd(d),N;if(D<m){N=m-D,setTimeout(g,N);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,P()},b=D=>(s=D,B),v=D=>(c=D,B),T=()=>(h="json",B),y=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},E=D=>(p=D,B),P=()=>{d=Te(),n=new r,n.open("get",a);let D=0,N,z=0,W=()=>(cu(d),Math.max(d,Math.max(N||0,z||0)));if(s&&n.addEventListener("progress",I=>{let w=Te();s.updateChunk&&I.loaded>D&&(s.updateChunk(W(),I.loaded-D),D=I.loaded,N=w)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;cu(n);let I=n.status;if(I>=200&&I<300){let{response:w,responseType:x}=n,k=w==null?void 0:w.byteLength;if(typeof k=="number"&&s){let _=k-D;_&&s.updateChunk&&s.updateChunk(W(),_)}x==="json"&&(!w||!(0,MT.default)(w).length)?y():(c&&c(),e(w))}else y()}),n.addEventListener("error",()=>{y()}),p){let I=()=>{cu(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(z=Te(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=h,n.send(),B},B={withBitrateReporting:b,withParallel:E,withJSONResponse:T,withRetryCount:D=>(l=D,B),withRetryInterval:(D,N)=>($T(D)&&(m=D),$T(N)&&(f=N),B),withTimeout:D=>(o=D,B),withFinally:v,send:P,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return B}var Sa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var DT=O(ji(),1);var va=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Te(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Te()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Zr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Te()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Te();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,DT.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as yC}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as BT}from"@vkontakte/videoplayer-shared/es2018";var F=(a,e)=>BT(a)&&BT(e)&&a.readyState==="open"&&fC(a,e);function fC(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var VT=O(pi(),1);import{getWindow as mC,safeStorage as bC}from"@vkontakte/videoplayer-shared/es2018";var Ud=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){var t;let e=(0,VT.default)(this.data).map(([i,r])=>`${i}:${r}`).join(",");return{key:this.tag,strings:[e,(t=this.stack)!=null?t:""],numbers:[this.time]}}},gC=(a,e="warn")=>{let t=mC(),i=[];function r(s,n=!1){var l,d,c;let o=(c=(d=(l=t.performance)==null?void 0:l.timing)==null?void 0:d.navigationStart)!=null?c:0,u=new Ud(a,Math.round((Date.now()-o)/1e3),s,n?new Error().stack:void 0);i.push(u),e&&t.console[e](u.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let s=i;return i=[],s},r},CT,q=gC("vp_dash_live_debug",(CT=bC.get("vp_dev_null_console_method"))!=null?CT:!1);var pu=1e4,qd=3;var TC=6e4,IC=10,EC=1,wC=500,Ta=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new yC,this.chunkRateEstimator=new Sa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Fd(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(q({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",q({m:"ldp.catchUp.2"}),this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?(q({m:"ldp.play.1"}),this._playVideoElement()):(q({m:"ldp.play.2"}),this._notifyBuffering(!0))):(q({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,q({m:"startPlay",url:e.jidxUrl}),this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Fd(e),q({m:"ldp.reinit",url:e}),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;q({m:"iv"}),e.addEventListener("error",()=>{var r,s,n,o;!!e.error&&!this.destroyed&&(q({m:"iv.err",e:((r=e.error)==null?void 0:r.code)+":"+((s=e.error)==null?void 0:s.message)}),t(`Video element error: ${(n=e.error)==null?void 0:n.code}, details: ${(o=e.error)==null?void 0:o.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),q({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(C.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!ST({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,_T.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||du(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){var o;let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(q({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),(o=this.mediaSource)==null||o.addEventListener("sourceclose",u=>{q({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{q({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{LT(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new va(qd,pu,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let y=s&&(!d||d===this.rep);return y||t("Not running!"),y},p=(y,E,P)=>{u&&u.abort(),u=Zr(this.urlResolver.resolve(y,!1),E,P,()=>this._retryCallback()).withTimeout(pu).withBitrateReporting(this.bitrateSwitcher).withRetryCount(qd).withFinally(()=>{u=null}).send()},h=(y,E,P)=>{ya(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),E,P,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let E=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${E}=>${y}`),i.playbackRate=y)},m=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let P=Te()-1e4,$=0;for(let L=0;L<this.bufferStates.length;L++){let M=this.bufferStates[L];y=Math.min(y,M.buf),M.ts<P&&$++}this.bufferStates.splice(0,$),t(`update playback rate; minBuffer=${y} drop=${$} jitter=${this.sourceJitter}`);let A=y-EC;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?f(1.15):A>1?f(1.1):A>.3?f(1.05):f(1)}},b=y=>{let E,P=()=>E&&E.start?E.start.length:0,$=I=>E.start[I]/1e3,A=I=>E.dur[I]/1e3,L=I=>E.fragIndex+I,M=(I,w)=>({chunkIdx:L(I),startTS:$(I),dur:A(I),discontinuity:w}),B=()=>{let I=0;if(E&&E.dur){let w=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,x=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,k=w;this.sourceJitter>1&&(k+=this.sourceJitter-1);let _=E.dur.length-1;for(;_>=0&&(k-=E.dur[_],!(k<=0));--_);I=Math.min(_,E.dur.length-1-x),I=Math.max(I,0)}return M(I,!0)},D=I=>{let w=P();if(!(w<=0)){if(du(I)){for(let x=0;x<w;x++)if($(x)>I)return M(x)}return B()}},N=I=>{let w=P(),x=I?I.chunkIdx+1:0,k=x-E.fragIndex;if(!(w<=0)){if(!I||k<0||k-w>IC)return t(`Resync: offset=${k} bChunks=${w} chunk=`+JSON.stringify(I)),B();if(!(k>=w))return M(x-E.fragIndex,!1)}},z=(I,w,x)=>{l&&l.abort(),l=Zr(this.urlResolver.resolve(I,!0,this.lowLatency),w,x,()=>this._retryCallback()).withTimeout(pu).withRetryCount(qd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(I,w)=>{z(y,x=>{if(!c())return;E=x;let k=!!E.lowLatency;k!==this.lowLatency&&m(k);let _=0;for(let U=0;U<E.dur.length;++U)_+=E.dur[U];_>0&&(ya(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(_/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,I(D(w))},()=>this._handleNetworkError())},nextChunk:N}},v=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),ya(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:y=>{let{videoElement:E,logger:P}=this.params,$=b(e.jidxUrl),A,L,M,B,D=0,N,z,W,I=()=>{N&&(clearTimeout(N),N=void 0);let X=Math.max(wC,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),we=D+X,xe=Te(),Pe=Math.min(1e4,we-xe);D=xe;let Je=()=>{l||c()&&$.seek(()=>{c()&&(D=Te(),w(),I())})};Pe>0?N=window.setTimeout(()=>{this.paused?I():Je()},Pe):Je()},w=()=>{let X;for(;X=$.nextChunk(B);)B=X,wt(X);let we=$.nextChunk(M);if(we){if(M&&we.discontinuity){P("Detected discontinuity; restarting playback"),this.paused?I():(v(),q({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}U(we)}else I()},x=(X,we)=>{if(!c()||!this.sourceBuffer){q({m:"ab.0",c:[!c(),!this.sourceBuffer]});return}let xe,Pe,Je,Vt=_t=>{q({m:"ldp.postpone",t:_t}),window.setTimeout(()=>{c()&&x(X,we)},_t)};if(this.sourceBuffer.updating)P("Source buffer is updating; delaying appendBuffer"),q({m:"ldp.ab.1"}),Vt(100);else{let _t=Te(),Mi=E.currentTime;!this.paused&&E.buffered.length>1&&z===Mi&&_t-W>500&&(P("Stall suspected; trying to fix"),this._fixupStall()),z!==Mi&&(z=Mi,W=_t);let vr=this._getBufferSizeSec();if(vr>30)q({m:"ldp.ab.3"}),P(`Buffered ${vr} seconds; delaying appendBuffer`),Vt(2e3);else try{if(this.params.config.useInvalidBufferFix&&F(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(X),this.videoPlayStarted?(q({m:"ldp.ab.5"}),this.bufferStates.push({ts:_t,buf:vr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(q({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),we&&we()}catch(yr){if(q({m:"ldp.ab.err",e:yr.name}),yr.name==="QuotaExceededError")P("QuotaExceededError; delaying appendBuffer"),Je=this.sourceBuffer.buffered.length,Je!==0&&(xe=this.sourceBuffer.buffered.start(0),Pe=Mi,Pe-xe>4&&this.sourceBuffer.remove(xe,Pe-3)),Vt(1e3);else throw yr}}},k=()=>{L&&A&&(P([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(M)]),x(L,function(){L=null,w()}))},_=X=>e.fragUrlTemplate.replace("%%id%%",X.chunkIdx),U=X=>{c()&&h(_(X),(we,xe)=>{if(c()){if(xe/=1e3,L=we,M=X,n=X.startTS,xe){let Pe=Math.min(10,X.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}k()}},()=>this._handleNetworkError())},wt=X=>{c()&&(ya(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(_(X),!1)))},xt=X=>{c()&&(e.cachedHeader=X,x(X,()=>{A=!0,k()}))};s=!0,$.seek(X=>{if(c()){if(D=Te(),!X){I();return}B=X,!vC(y)||X.startTS>y?U(X):(M=X,w())}},y),e.cachedHeader?xt(e.cachedHeader):p(e.headerUrl,xt,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),du(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,ya(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return du(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),f=c/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,h)=>{let f=Te();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Nd(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=Te();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Zr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(pu).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Be(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{q({m:"ldp.pve.1"}),t||(q({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},TC))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var FT=O(pi(),1);import{debounce as xC,filter as OT,fromEvent as PC,interval as kC,isHigher as AC,isInvariantQuality as RC,isLower as $C,merge as MC,Subject as NT,Subscription as LC}from"@vkontakte/videoplayer-shared/es2018";var jd=class{constructor(){this.onDroopedVideoFramesLimit$=new NT;this.subscription=new LC;this.playing=!1;this.tracks=[];this.forceChecker$=new NT;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!RC(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&AC(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(PC(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=kC(this.droppedFramesChecker.checkTime).pipe(OT(()=>this.playing),OT(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(xC(this.droppedFramesChecker.checkTime)),i=MC(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,FT.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>$C(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},mi=jd;import{map as DC,Observable as BC}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as CC}from"@vkontakte/videoplayer-shared/es2018";var Ia=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var VC=(a,e)=>new BC(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ia()))},{...i,...e});r.observe(a);let s=CC(document,"visibilitychange").pipe(DC(n=>!document.hidden||Ia())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Ke=VC;var HC=["paused","playing","ready"],WC=["paused","playing","ready"],Ea=class{constructor(e){this.subscription=new qC;this.videoState=new j("stopped");this.representations$=new Wd([]);this.droppedFramesManager=new mi;this.maxSeekBackTime$=new Wd(1/0);this.zeroTime$=new Wd(void 0);this.liveOffset=new Ji;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:jT.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=Lt(u.name))!=null?i:jC(u.video),c=u.bitrate/1e3,p={...u.video};if(!d)continue;let h={id:l,quality:d,bitrate:c,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Hd(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,zd.default)(WC,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,zd.default)(HC,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){q({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&(q({m:"dlp.sync.2"}),this.dash.catchUp()),q({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(le(this.params.source.url,u))}return;default:return UT(e)}};this.textTracksManager=new Ge(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:jT.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(WT(this.videoState.stateChangeStarted$.pipe(hu(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(hu(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{q({m:"dlp.s.1",t:s+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=De(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(hu(r=>r.map(({track:s})=>s)),HT(r=>!!r.length),UC()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(NC(),hu(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(_C({zeroTime:this.zeroTime$.pipe(HT(Hd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Le(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Qe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&zT(r),min:s&&zT(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),q({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&(q({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":q({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":q({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return UT(r.to)}},t)).add(WT(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,FC(["init"])).pipe(OC(0)).subscribe(this.syncPlayback,t))}destroy(){q({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Me(this.video)}createLiveDashPlayer(){let e=new Ta({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,p,h,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Hd(t)?t:ut(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let m=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;qT(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;qT(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),q({m:"dlp.seek",p:e,no:n,url:this.params.source.url}),this.dash.reinit(le(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var QT=Ea;import{filterChanged as sO}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as o0,assertNonNullable as u0,debounce as l0,ErrorCategory as rI,filter as tp,filterChanged as ip,fromEvent as c0,isNonNullable as sI,isNullable as d0,map as rp,merge as vu,observableFrom as sp,once as aI,Subscription as p0,throttle as h0}from"@vkontakte/videoplayer-shared/es2018";var Qd=O(Ye(),1);import{videoSizeToQuality as zC}from"@vkontakte/videoplayer-shared/es2018";var GT=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Lt(s):void 0)!=null?u:zC({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},YT=({id:a,bitrate:e})=>({id:a,bitrate:e}),KT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e});var Gd=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Qd.default)(i.split("."),0),isDefault:r}),fu=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Qd.default)(r.split("."),0)});var je=a=>a.type==="template";var mu=class{constructor(e,t){this.fov=e,this.orientation=t}};var bu=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var XT=`attribute vec2 a_vertex;
|
|
116
|
+
[selected audio track] ${S==null?void 0:S.id}
|
|
117
|
+
`}),S};var we=a=>new URL(a).hostname;import{assertNever as My,assertNonNullable as Cy,combine as aD,debounce as sD,ErrorCategory as Ly,filter as Dy,filterChanged as nD,isNonNullable as Xc,map as To,merge as By,observableFrom as oD,once as uD,Subscription as lD,ValueSubject as Jc,videoQualityToHeight as Vy,videoSizeToQuality as cD}from"@vkontakte/videoplayer-shared/es2018";var ky=_(Ke(),1);var Sy=_(De(),1),vy=a=>{if(a instanceof DOMException&&(0,Sy.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Ne=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!vy(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return vy(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as So,isNullable as FL,assertNonNullable as Va}from"@vkontakte/videoplayer-shared/es2018";var Ty=_(Ei(),1);import{isNonNullable as yy,assertNonNullable as vo,now as DL}from"@vkontakte/videoplayer-shared/es2018";function be(){return DL()}function Wc(a){return be()-a}function zc(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Iy(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function xr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",m=7e3,f=2e3,v=()=>{if(u)return;vo(d);let M=Wc(d),q;if(M<f){q=f-M,setTimeout(v,q);return}f*=2,f>m&&(f=m),n&&n.abort(),n=new r,R()},g=M=>(s=M,V),S=M=>(c=M,V),T=()=>(h="json",V),y=()=>{if(!u){if(--l>=0){v(),i&&i();return}u=!0,c&&c(),t&&t()}},w=M=>(p=M,V),R=()=>{d=be(),n=new r,n.open("get",a);let M=0,q,G=0,H=()=>(vo(d),Math.max(d,Math.max(q||0,G||0)));if(s&&n.addEventListener("progress",E=>{let P=be();s.updateChunk&&E.loaded>M&&(s.updateChunk(H(),E.loaded-M),M=E.loaded,q=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;vo(n);let E=n.status;if(E>=200&&E<300){let{response:P,responseType:I}=n,x=P==null?void 0:P.byteLength;if(typeof x=="number"&&s){let F=x-M;F&&s.updateChunk&&s.updateChunk(H(),F)}I==="json"&&(!P||!(0,Ty.default)(P).length)?y():(c&&c(),e(P))}else y()}),n.addEventListener("error",()=>{y()}),p){let E=()=>{vo(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(G=be(),n.removeEventListener("readystatechange",E))};n.addEventListener("readystatechange",E)}return n.responseType=h,n.send(),V},V={withBitrateReporting:g,withParallel:w,withJSONResponse:T,withRetryCount:M=>(l=M,V),withRetryInterval:(M,q)=>(yy(M)&&(f=M),yy(q)&&(m=q),V),withTimeout:M=>(o=M,V),withFinally:S,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return V}var Da=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ey=_(Ei(),1);var Ba=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=be(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=be()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=xr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=be()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=be();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Ey.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as qL}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as wy}from"@vkontakte/videoplayer-shared/es2018";var ee=(a,e)=>wy(a)&&wy(e)&&a.readyState==="open"&&BL(a,e);function BL(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Py=_(zt(),1);import{getWindow as VL,safeStorage as _L}from"@vkontakte/videoplayer-shared/es2018";var Gc=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){var t;let e=(0,Py.default)(this.data).map(([i,r])=>`${i}:${r}`).join(",");return{key:this.tag,strings:[e,(t=this.stack)!=null?t:""],numbers:[this.time]}}},OL=(a,e="warn")=>{let t=VL(),i=[];function r(s,n=!1){var l,d,c;let o=(c=(d=(l=t.performance)==null?void 0:l.timing)==null?void 0:d.navigationStart)!=null?c:0,u=new Gc(a,Math.round((Date.now()-o)/1e3),s,n?new Error().stack:void 0);i.push(u),e&&t.console[e](u.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let s=i;return i=[],s},r},xy,N=OL("vp_dash_live_debug",(xy=_L.get("vp_dev_null_console_method"))!=null?xy:!1);var yo=1e4,Yc=3;var UL=6e4,jL=10,HL=1,QL=500,_a=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new qL,this.chunkRateEstimator=new Da(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=zc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(N({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",N({m:"ldp.catchUp.2"}),this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?(N({m:"ldp.play.1"}),this._playVideoElement()):(N({m:"ldp.play.2"}),this._notifyBuffering(!0))):(N({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,N({m:"startPlay",url:e.jidxUrl}),this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=zc(e),N({m:"ldp.reinit",url:e}),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;N({m:"iv"}),e.addEventListener("error",()=>{var r,s,n,o;!!e.error&&!this.destroyed&&(N({m:"iv.err",e:((r=e.error)==null?void 0:r.code)+":"+((s=e.error)==null?void 0:s.message)}),t(`Video element error: ${(n=e.error)==null?void 0:n.code}, details: ${(o=e.error)==null?void 0:o.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),N({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(B.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!uy({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,ky.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||So(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){var o;let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(N({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),(o=this.mediaSource)==null||o.addEventListener("sourceclose",u=>{N({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{N({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Iy(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ba(Yc,yo,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let y=s&&(!d||d===this.rep);return y||t("Not running!"),y},p=(y,w,R)=>{u&&u.abort(),u=xr(this.urlResolver.resolve(y,!1),w,R,()=>this._retryCallback()).withTimeout(yo).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Yc).withFinally(()=>{u=null}).send()},h=(y,w,R)=>{Va(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),w,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=y=>{let w=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${w}=>${y}`),i.playbackRate=y)},f=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let R=be()-1e4,L=0;for(let D=0;D<this.bufferStates.length;D++){let A=this.bufferStates[D];y=Math.min(y,A.buf),A.ts<R&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${y} drop=${L} jitter=${this.sourceJitter}`);let $=y-HL;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?m(1.15):$>1?m(1.1):$>.3?m(1.05):m(1)}},g=y=>{let w,R=()=>w&&w.start?w.start.length:0,L=E=>w.start[E]/1e3,$=E=>w.dur[E]/1e3,D=E=>w.fragIndex+E,A=(E,P)=>({chunkIdx:D(E),startTS:L(E),dur:$(E),discontinuity:P}),V=()=>{let E=0;if(w&&w.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,I=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,x=P;this.sourceJitter>1&&(x+=this.sourceJitter-1);let F=w.dur.length-1;for(;F>=0&&(x-=w.dur[F],!(x<=0));--F);E=Math.min(F,w.dur.length-1-I),E=Math.max(E,0)}return A(E,!0)},M=E=>{let P=R();if(!(P<=0)){if(So(E)){for(let I=0;I<P;I++)if(L(I)>E)return A(I)}return V()}},q=E=>{let P=R(),I=E?E.chunkIdx+1:0,x=I-w.fragIndex;if(!(P<=0)){if(!E||x<0||x-P>jL)return t(`Resync: offset=${x} bChunks=${P} chunk=`+JSON.stringify(E)),V();if(!(x>=P))return A(I-w.fragIndex,!1)}},G=(E,P,I)=>{l&&l.abort(),l=xr(this.urlResolver.resolve(E,!0,this.lowLatency),P,I,()=>this._retryCallback()).withTimeout(yo).withRetryCount(Yc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(E,P)=>{G(y,I=>{if(!c())return;w=I;let x=!!w.lowLatency;x!==this.lowLatency&&f(x);let F=0;for(let O=0;O<w.dur.length;++O)F+=w.dur[O];F>0&&(Va(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(F/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,E(M(P))},()=>this._handleNetworkError())},nextChunk:q}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Va(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:y=>{let{videoElement:w,logger:R}=this.params,L=g(e.jidxUrl),$,D,A,V,M=0,q,G,H,E=()=>{q&&(clearTimeout(q),q=void 0);let Y=Math.max(QL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=M+Y,ye=be(),Te=Math.min(1e4,Se-ye);M=ye;let Fe=()=>{l||c()&&L.seek(()=>{c()&&(M=be(),P(),E())})};Te>0?q=window.setTimeout(()=>{this.paused?E():Fe()},Te):Fe()},P=()=>{let Y;for(;Y=L.nextChunk(V);)V=Y,ct(Y);let Se=L.nextChunk(A);if(Se){if(A&&Se.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?E():(S(),N({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}O(Se)}else E()},I=(Y,Se)=>{if(!c()||!this.sourceBuffer){N({m:"ab.0",c:[!c(),!this.sourceBuffer]});return}let ye,Te,Fe,It=Et=>{N({m:"ldp.postpone",t:Et}),window.setTimeout(()=>{c()&&I(Y,Se)},Et)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),N({m:"ldp.ab.1"}),It(100);else{let Et=be(),di=w.currentTime;!this.paused&&w.buffered.length>1&&G===di&&Et-H>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),G!==di&&(G=di,H=Et);let Gi=this._getBufferSizeSec();if(Gi>30)N({m:"ldp.ab.3"}),R(`Buffered ${Gi} seconds; delaying appendBuffer`),It(2e3);else try{if(this.params.config.useInvalidBufferFix&&ee(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(N({m:"ldp.ab.5"}),this.bufferStates.push({ts:Et,buf:Gi}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(N({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(Yi){if(N({m:"ldp.ab.err",e:Yi.name}),Yi.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Fe=this.sourceBuffer.buffered.length,Fe!==0&&(ye=this.sourceBuffer.buffered.start(0),Te=di,Te-ye>4&&this.sourceBuffer.remove(ye,Te-3)),It(1e3);else throw Yi}}},x=()=>{D&&$&&(R([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(A)]),I(D,function(){D=null,P()}))},F=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),O=Y=>{c()&&h(F(Y),(Se,ye)=>{if(c()){if(ye/=1e3,D=Se,A=Y,n=Y.startTS,ye){let Te=Math.min(10,Y.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Te:Te}x()}},()=>this._handleNetworkError())},ct=Y=>{c()&&(Va(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(F(Y),!1)))},dt=Y=>{c()&&(e.cachedHeader=Y,I(Y,()=>{$=!0,x()}))};s=!0,L.seek(Y=>{if(c()){if(M=be(),!Y){E();return}V=Y,!FL(y)||Y.startTS>y?O(Y):(A=Y,P())}},y),e.cachedHeader?dt(e.cachedHeader):p(e.headerUrl,dt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),So(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Va(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return So(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,h)=>{let m=be();if(this.chunkRateEstimator.addInterval(p,m,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Wc(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=be();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=xr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(yo).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ne(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{N({m:"ldp.pve.1"}),t||(N({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},UL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var $y=_(zt(),1);import{debounce as WL,filter as Ay,fromEvent as zL,interval as GL,isHigher as YL,isInvariantQuality as KL,isLower as XL,merge as JL,Subject as Ry,Subscription as ZL}from"@vkontakte/videoplayer-shared/es2018";var Kc=class{constructor(){this.onDroopedVideoFramesLimit$=new Ry;this.subscription=new ZL;this.playing=!1;this.tracks=[];this.forceChecker$=new Ry;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!KL(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&YL(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(zL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=GL(this.droppedFramesChecker.checkTime).pipe(Ay(()=>this.playing),Ay(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(WL(this.droppedFramesChecker.checkTime)),i=JL(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,$y.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>XL(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Pr=Kc;import{map as eD,Observable as tD}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as iD}from"@vkontakte/videoplayer-shared/es2018";var Oa=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var rD=(a,e)=>new tD(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Oa()))},{...i,...e});r.observe(a);let s=iD(document,"visibilitychange").pipe(eD(n=>!document.hidden||Oa())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Xe=rD;var dD=["paused","playing","ready"],pD=["paused","playing","ready"],Na=class{constructor(e){this.subscription=new lD;this.videoState=new j("stopped");this.representations$=new Jc([]);this.droppedFramesManager=new Pr;this.maxSeekBackTime$=new Jc(1/0);this.zeroTime$=new Jc(void 0);this.liveOffset=new Ci;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Ly.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=Kt(u.name))!=null?i:cD(u.video),c=u.bitrate/1e3,p={...u.video};if(!d)continue;let h={id:l,quality:d,bitrate:c,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Xc(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Zc.default)(pD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Zc.default)(dD,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){N({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&(N({m:"dlp.sync.2"}),this.dash.catchUp()),N({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Ee(this.params.source.url,u))}return;default:return My(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Ly.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(By(this.videoState.stateChangeStarted$.pipe(To(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(To(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{N({m:"dlp.s.1",t:s+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Oe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(To(r=>r.map(({track:s})=>s)),Dy(r=>!!r.length),uD()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(nD(),To(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(aD({zeroTime:this.zeroTime$.pipe(Dy(Xc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(gt(this.video,this.params.desiredState.isLooped,t)).add(_e(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ge(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Xe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Vy(r),min:s&&Vy(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),N({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&(N({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":N({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":N({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return My(r.to)}},t)).add(By(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,oD(["init"])).pipe(sD(0)).subscribe(this.syncPlayback,t))}destroy(){N({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ve(this.video)}createLiveDashPlayer(){let e=new _a({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,p,h,m;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Xc(t)?t:yt(e.map(({track:f})=>f),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let f=(m=e.find(({track:v})=>v.id===s))==null?void 0:m.representation;Cy(f,"Representations missing"),this.dash.startPlay(f,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Cy(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),N({m:"dlp.seek",p:e,no:n,url:this.params.source.url}),this.dash.reinit(Ee(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var _y=Na;import{filterChanged as xV}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as AD,assertNonNullable as RD,debounce as $D,ErrorCategory as zy,filter as ud,filterChanged as ld,fromEvent as MD,isNonNullable as Gy,isNullable as CD,map as cd,merge as Ao,observableFrom as dd,once as Yy,Subscription as LD,throttle as DD}from"@vkontakte/videoplayer-shared/es2018";var ed=_(Ke(),1);import{videoSizeToQuality as hD}from"@vkontakte/videoplayer-shared/es2018";var Oy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:hD({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ny=({id:a,bitrate:e})=>({id:a,bitrate:e}),Fy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e});var td=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,ed.default)(i.split("."),0),isDefault:r}),Io=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,ed.default)(r.split("."),0)});var Me=a=>a.type==="template";var Eo=class{constructor(e,t){this.fov=e,this.orientation=t}};var wo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var qy=`attribute vec2 a_vertex;
|
|
118
118
|
attribute vec2 a_texel;
|
|
119
119
|
|
|
120
120
|
varying vec2 v_texel;
|
|
@@ -125,7 +125,7 @@ void main(void) {
|
|
|
125
125
|
// save texel vector to pass to fragment shader
|
|
126
126
|
v_texel = a_texel;
|
|
127
127
|
}
|
|
128
|
-
`;var
|
|
128
|
+
`;var Uy=`#ifdef GL_ES
|
|
129
129
|
precision highp float;
|
|
130
130
|
precision highp int;
|
|
131
131
|
#else
|
|
@@ -168,17 +168,17 @@ void main(void) {
|
|
|
168
168
|
// sample using new coordinates
|
|
169
169
|
gl_FragColor = texture2D(u_texture, tc);
|
|
170
170
|
}
|
|
171
|
-
`;var gi=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new mu(this.params.fov,this.params.orientation),this.cameraRotationManager=new bu(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(XT,this.gl.VERTEX_SHADER),i=this.createShader(JT,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,p=t+r;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as YC,now as wa,once as KC,Subscription as XC,ValueSubject as Kd,isNonNullable as JC,safeStorage as Xd,filterChanged as ZC}from"@vkontakte/videoplayer-shared/es2018";var Ht=(a,e,t)=>t*e+(1-t)*a,Yd=(a,e)=>a.reduce((t,i)=>t+i,0)/e,ZT=(a,e,t,i)=>{let r=0,s=t,n=Yd(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var gu="stalls_manager_metrics",Jd="stalls_manager_abr_params",eI="stalls_manager_default_tuning_abr_params",Zd=class{constructor(){this.isSeeked$=new Kd(!1);this.isBuffering$=new Kd(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new XC;this.severeStallOccurred$=new Kd(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(Jd):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=wa(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(wa()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(eI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(Jd),this.setStoredData(eI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(gu,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(gu,[]),this.setStoredData(Jd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>s&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){var i;return JSON.parse((i=Xd.get(e))!=null?i:t)}setStoredData(e,t){Xd.set(e,JSON.stringify(t))}removeStoredData(e){Xd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(gu,"[]"),r=t/e,s=i.length?Ht(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(gu,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(KC()).subscribe(t=>this.providerStartWatchingTimestamp=wa())),this.subscription.add(this.currentStallDuration$.pipe(ZC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(YC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=wa(),c=r&&this.currentStallsCount>=r,p=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,JC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&wa()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},es=Zd;import{combine as e0,map as t0,observeElementSize as i0,Subscription as r0,ValueSubject as ep,noop as s0}from"@vkontakte/videoplayer-shared/es2018";var Su=class{constructor(){this.subscription=new r0;this.pipSize$=new ep(void 0);this.videoSize$=new ep(void 0);this.elementSize$=new ep(void 0);this.pictureInPictureWindowRemoveEventListener=s0}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(i0(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(e0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(t0(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as tI,map as a0,once as iI}from"@vkontakte/videoplayer-shared/es2018";var Si=({subscription:a,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!C.browser.isSafari)return;let r=0,s=!1;a.add(e.volume.stateChangeStarted$.pipe(a0(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),tI(n=>!!n),iI()).subscribe(()=>{r=performance.now(),s=!0})),a.add(i.playbackRateState$.pipe(tI(()=>s),iI()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var xa=class{constructor(e){this.subscription=new p0;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new mi;this.stallsManager=new es;this.elementSizeManager=new Su;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(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"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return o0(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new gi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ge(e.source.url),this.params=e,this.video=$e(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(fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;d0(this.observableVideo)&&(this.observableVideo=De(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:rI.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(tp(c=>!!c.length),aI()).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(rp(c=>c.to.state!=="none"),ip());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.currentBuffer$,e.currentBuffer$),s(this.player.lastRequestFirstBytes$.pipe(tp(sI),aI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(rp(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(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Si({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams(),h=this.player.getCodecs();if(u0(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of p.audio){m.push(Gd(g));let b=[];for(let v of g.representations){let T=YT(v);b.push(T),this.audioTracksMap.set(T,{stream:g,representation:v})}this.audioStreamsMap.set(g,b)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of p.video){f.push(fu(m));let g=[];for(let b of m.representations){let v=GT({...b,streamId:m.id});v&&(g.push(v),this.videoTracksMap.set(v,{stream:m,representation:b}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(f);for(let m of p.text)for(let g of m.representations){let b=KT(m,g);this.textTracksMap.set(b,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=vu(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$,c0(this.video,"progress")).pipe(tp(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(h0(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(c!=="manifest_ready"&&c!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let f=this.selectVideoAudioRepresentations();if(!f)return;let[m,g]=f,b=[...this.videoTracksMap.keys()].find(T=>{var y;return((y=this.videoTracksMap.get(T))==null?void 0:y.representation.id)===m.id});sI(b)&&(this.stallsManager.lastVideoTrackSelected=b);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready"?await this.player.initRepresentations(m.id,g==null?void 0:g.id,this.params.sourceHls):(await this.player.switchRepresentation("video",m.id,h),g&&await this.player.switchRepresentation("audio",g.id,h))},r)),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.currentAudioRepresentation$.pipe(ip()).subscribe(c=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=p,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Gd(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(rp(({to:c})=>c==="ready"),ip());this.subscription.add(vu(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,sp(["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(vu(l,this.player.state$.stateChangeEnded$,sp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=vu(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,sp(["init"])).pipe(l0(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var A,L,M,B,D,N,z,W,I,w,x,k,_;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ir:tr,t=this.params.tuning.useNewAutoSelectVideoTrack?Jr:Xr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Kr,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(A=r.videoTrack.getState())==null?void 0:A.id,u=[...this.videoTracksMap.keys()].find(({id:U})=>U===o),l=s.currentVideoTrack$.getValue(),d=((B=(M=r.videoStream.getState())!=null?M:u&&((L=this.videoTracksMap.get(u))==null?void 0:L.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=[...this.videoStreamsMap.keys()].find(({id:U})=>U===d.id),p=c&&this.videoStreamsMap.get(c);if(!p)return;let h=this.player.bufferLength$.getValue(),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(h/Math.min(f,m||1/0),1),b=(D=r.audioStream.getState())!=null?D:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(N=[...this.audioStreamsMap.keys()].find(({id:U})=>U===(b==null?void 0:b.id)))!=null?N:this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let U=e(u,p,(z=this.audioStreamsMap.get(v))!=null?z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(W=U==null?void 0:U.bitrate)!=null?W:-1/0)}if(l){let U=e(l,p,(I=this.audioStreamsMap.get(v))!=null?I:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(w=U==null?void 0:U.bitrate)!=null?w:-1/0)}}let y=u;(n||!y)&&(y=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:g,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 E=v&&t(y,p,(x=this.audioStreamsMap.get(v))!=null?x:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=(k=this.videoTracksMap.get(y))==null?void 0:k.representation,$=E&&((_=this.audioTracksMap.get(E))==null?void 0:_.representation);if(P&&$)return[P,$];if(P&&!$&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:rI.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),Me(this.video),this.tracer.end()}};var Vp=O(rr(),1);var{NativeAbortSignal:gG,NativeAbortController:SG}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function xI(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function PI(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var yu=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ts=class extends yu{constructor(){super(),this.listeners||yu.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new sr;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new sr;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},sr=class{constructor(){Object.defineProperty(this,"signal",{value:new ts,writable:!0,configurable:!0})}abort(e){let t=PI(e),i=xI(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(sr.prototype[Symbol.toStringTag]="AbortController",ts.prototype[Symbol.toStringTag]="AbortSignal");function Tu(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function np(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Tu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(h){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var he=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window;var V0=()=>"fetch"in he,Pa=V0()&&Tu({fetch:he.fetch,Request:he.Request,AbortController:he.AbortController}),kI=Pa?np({fetch:he.fetch,Request:he.Request,AbortController:he.AbortController}):void 0,Xe=Pa?kI.fetch:he.fetch,$G=Pa?kI.Request:he.Request,Q=Pa?sr:he.AbortController,MG=Pa?ts:he.AbortSignal;var Sw=O(Re(),1);var GI=O(QI(),1);import{ErrorCategory as Aa}from"@vkontakte/videoplayer-shared/es2018";var is=a=>{if(!a)return{id:"EmptyResponse",category:Aa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Aa.NETWORK,message:`UV Error ${a}`};let e=(0,GI.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Aa.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Aa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Aa.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as mw,assertNonNullable as Gt,ErrorCategory as or,filter as Lp,filterChanged as Q_,flattenObject as Mu,fromEvent as ur,getTraceSubscriptionMethod as G_,getWindow as un,interval as Y_,isNonNullable as Ii,isNullable as ln,map as Dp,merge as cn,now as K_,Subject as Ei,Subscription as bw,SubscriptionRemovable as X_,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2018";var Tt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var rs=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as Ra,assertNever as YI,ErrorCategory as $a,flattenObject as as,fromEvent as KI,getWindow as Z0,merge as eV,now as Ma,Subject as ns,Subscription as tV,ValueSubject as dp}from"@vkontakte/videoplayer-shared/es2018";var Ce=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ss=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Eu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new ns;this.manifestReceived=new ns;this.firstBytesRequested=new ns;this.firstBytesReceived=new ns;this.lastConnectionType$=new dp(void 0);this.lastConnectionReused$=new dp(void 0);this.lastRequestFirstBytes$=new dp(void 0);this.recoverableError$=new ns;this.error$=new ns;this.abortAllController=new Q;this.subscription=new tV;this.fetchManifest=Ra(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ss(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Iu);return r?(t.log("success",as({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",as({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ra(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var N,z,W;let d=e,c=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(d,Z0().location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),d=I.toString();break}default:YI(t)}this.requestQuic&&(d=Tt(d));let h=this.abortAllController.signal,f;if(n){let I=new Q;if(f=eV(KI(this.abortAllController.signal,"abort"),KI(n,"abort")).subscribe(()=>{try{I.abort()}catch(w){Iu(w)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(w){Iu(w)}h=I.signal}let m=0,g=Ma();p.log("startRequest",as({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let b=yield this.doFetch(d,{priority:s,headers:c,signal:h}),v=Ma();if(!b)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((N=this.throughputEstimator)==null||N.addRawRtt(v-g),!b.ok||!b.body){f==null||f.unsubscribe();let I=`Fetch error ${b.status}: ${b.statusText}`;return p.error("error",{message:I}),p.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){f==null||f.unsubscribe();let I=Ma(),w={requestStartedAt:g,requestEndedAt:I,duration:I-g};return p.log("endRequest",as(w)),p.end(),b.arrayBuffer()}let T=b.body;if(o){let I;[T,I]=b.body.tee(),(z=this.throughputEstimator)==null||z.trackStream(I,u)}let y=T.getReader(),E,P=parseInt((W=b.headers.get("content-length"))!=null?W:"",10);Number.isFinite(P)&&(E=P),!E&&i&&(E=i.to-i.from+1);let $=E?new Uint8Array(E):new Uint8Array(0),A=!1,L=I=>{f==null||f.unsubscribe(),A=!0,Iu(I)},M=Ra(h,async function*({done:I,value:w}){if(m===0&&(this.lastRequestFirstBytes$.next(Ma()-g),this.firstBytesReceived.next()),h.aborted){f==null||f.unsubscribe();return}if(!I&&w){if(l&&E)$.set(w,m),m+=w.byteLength;else{let x=new Uint8Array($.length+w.length);x.set($),x.set(w,$.length),$=x,m+=w.byteLength}r==null||r(new DataView($.buffer),m),yield y==null?void 0:y.read().then(M,L)}}.bind(this));yield y==null?void 0:y.read().then(M,L),f==null||f.unsubscribe();let B=Ma(),D={failed:A,requestStartedAt:g,requestEndedAt:B,duration:B-g};return A?(p.error("endRequest",as(D)),p.end(),null):(p.log("endRequest",as(D)),p.end(),$.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ra(this.abortAllController.signal,async function*(e,t,i){var b;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),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 p=new DataView(c,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(b=e.indexRange)!=null?b:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,h,f).map(v=>({networkStatus:"none",bufferStatus:"none",status:"none",time:v.time,byte:v.byte}));return{initMetadata:h,initDataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ra(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});if(!r)return null;let s=e.segments.map(n=>({...n,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:s}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=rs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=this.fetchTemplateRepresentation(e,i))!=null?n:null;default:YI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Xe(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:$a.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:$a.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:$a.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:$a.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:$a.FATAL})}}},Iu=a=>{if(!Ce(a))throw a};var vp=O(vE(),1),UE=O(pi(),1),qE=O(CE(),1),jE=O(Ye(),1),yp=O(ji(),1);var VE=O(Re(),1),Sp=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,VE.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as t_,isNullable as NE}from"@vkontakte/videoplayer-shared/es2018";var _E=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var OE=a=>{var e;try{let t=e_(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function e_(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
171
|
+
`;var kr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Eo(this.params.fov,this.params.orientation),this.cameraRotationManager=new wo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(qy,this.gl.VERTEX_SHADER),i=this.createShader(Uy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,p=t+r;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as bD,now as qa,once as gD,Subscription as vD,ValueSubject as rd,isNonNullable as SD,safeStorage as ad,filterChanged as yD}from"@vkontakte/videoplayer-shared/es2018";var $t=(a,e,t)=>t*e+(1-t)*a,id=(a,e)=>a.reduce((t,i)=>t+i,0)/e,jy=(a,e,t,i)=>{let r=0,s=t,n=id(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var xo="stalls_manager_metrics",sd="stalls_manager_abr_params",Hy="stalls_manager_default_tuning_abr_params",nd=class{constructor(){this.isSeeked$=new rd(!1);this.isBuffering$=new rd(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new vD;this.severeStallOccurred$=new rd(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(sd):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=qa(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(qa()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Hy)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(sd),this.setStoredData(Hy,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(xo,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(xo,[]),this.setStoredData(sd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>s&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){var i;return JSON.parse((i=ad.get(e))!=null?i:t)}setStoredData(e,t){ad.set(e,JSON.stringify(t))}removeStoredData(e){ad.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(xo,"[]"),r=t/e,s=i.length?$t(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(xo,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(gD()).subscribe(t=>this.providerStartWatchingTimestamp=qa())),this.subscription.add(this.currentStallDuration$.pipe(yD()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(bD(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=qa(),c=r&&this.currentStallsCount>=r,p=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,SD(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&qa()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Po=nd;import{combine as TD,map as ID,observeElementSize as ED,Subscription as wD,ValueSubject as od,noop as xD}from"@vkontakte/videoplayer-shared/es2018";var ko=class{constructor(){this.subscription=new wD;this.pipSize$=new od(void 0);this.videoSize$=new od(void 0);this.elementSize$=new od(void 0);this.pictureInPictureWindowRemoveEventListener=xD}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(ED(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(TD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(ID(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as Qy,map as PD,once as Wy}from"@vkontakte/videoplayer-shared/es2018";var Jt=({subscription:a,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!B.browser.isSafari)return;let r=0,s=!1;a.add(e.volume.stateChangeStarted$.pipe(PD(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),Qy(n=>!!n),Wy()).subscribe(()=>{r=performance.now(),s=!0})),a.add(i.playbackRateState$.pipe(Qy(()=>s),Wy()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var Ua=class{constructor(e){this.subscription=new LD;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new Pr;this.stallsManager=new Po;this.elementSizeManager=new ko;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return AD(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new kr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Be(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;CD(this.observableVideo)&&(this.observableVideo=Oe(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:zy.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ud(c=>!!c.length),Yy()).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(cd(c=>c.to.state!=="none"),ld());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.currentBuffer$,e.currentBuffer$),s(this.player.lastRequestFirstBytes$.pipe(ud(Gy),Yy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(cd(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(gt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Ge(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams(),h=this.player.getCodecs();if(RD(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let v of p.audio){f.push(td(v));let g=[];for(let S of v.representations){let T=Ny(S);g.push(T),this.audioTracksMap.set(T,{stream:v,representation:S})}this.audioStreamsMap.set(v,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of p.video){m.push(Io(f));let v=[];for(let g of f.representations){let S=Oy({...g,streamId:f.id});S&&(v.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,v)}this.params.output.availableVideoStreams$.next(m);for(let f of p.text)for(let v of f.representations){let g=Fy(f,v);this.textTracksMap.set(g,{stream:f,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!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=Ao(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$,MD(this.video,"progress")).pipe(ud(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(DD(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(c!=="manifest_ready"&&c!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let m=this.selectVideoAudioRepresentations();if(!m)return;let[f,v]=m,g=[...this.videoTracksMap.keys()].find(T=>{var y;return((y=this.videoTracksMap.get(T))==null?void 0:y.representation.id)===f.id});Gy(g)&&(this.stallsManager.lastVideoTrackSelected=g);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready"?await this.player.initRepresentations(f.id,v==null?void 0:v.id,this.params.sourceHls):(await this.player.switchRepresentation("video",f.id,h),v&&await this.player.switchRepresentation("audio",v.id,h))},r)),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.currentAudioRepresentation$.pipe(ld()).subscribe(c=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(td(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(cd(({to:c})=>c==="ready"),ld());this.subscription.add(Ao(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,dd(["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(Ao(l,this.player.state$.stateChangeEnded$,dd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Ao(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dd(["init"])).pipe($D(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var $,D,A,V,M,q,G,H,E,P,I,x,F;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?La:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?go:bo,i=this.params.tuning.useNewAutoSelectVideoTrack?yt:fo,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=($=r.videoTrack.getState())==null?void 0:$.id,u=[...this.videoTracksMap.keys()].find(({id:O})=>O===o),l=s.currentVideoTrack$.getValue(),d=((V=(A=r.videoStream.getState())!=null?A:u&&((D=this.videoTracksMap.get(u))==null?void 0:D.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=[...this.videoStreamsMap.keys()].find(({id:O})=>O===d.id),p=c&&this.videoStreamsMap.get(c);if(!p)return;let h=this.player.bufferLength$.getValue(),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(h/Math.min(m,f||1/0),1),g=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(q=[...this.audioStreamsMap.keys()].find(({id:O})=>O===(g==null?void 0:g.id)))!=null?q:this.audioStreamsMap.keys().next().value,T=0;if(S){if(u&&!n){let O=e(u,p,(G=this.audioStreamsMap.get(S))!=null?G:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(H=O==null?void 0:O.bitrate)!=null?H:-1/0)}if(l){let O=e(l,p,(E=this.audioStreamsMap.get(S))!=null?E:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(P=O==null?void 0:O.bitrate)!=null?P:-1/0)}}let y=u;(n||!y)&&(y=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,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 w=S&&t(y,p,(I=this.audioStreamsMap.get(S))!=null?I:[],{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}),R=(x=this.videoTracksMap.get(y))==null?void 0:x.representation,L=w&&((F=this.audioTracksMap.get(w))==null?void 0:F.representation);if(R&&L)return[R,L];if(R&&!L&&this.audioTracksMap.size===0)return[R,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zy.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),Ve(this.video),this.tracer.end()}};var jd=_(ja(),1);var{NativeAbortSignal:rW,NativeAbortController:aW}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function fT(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function bT(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var Ro=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Rr=class extends Ro{constructor(){super(),this.listeners||Ro.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Bi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Bi;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},Bi=class{constructor(){Object.defineProperty(this,"signal",{value:new Rr,writable:!0,configurable:!0})}abort(e){let t=bT(e),i=fT(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Bi.prototype[Symbol.toStringTag]="AbortController",Rr.prototype[Symbol.toStringTag]="AbortSignal");function $o(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function hd(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!$o({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(h){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var de=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window;var rB=()=>"fetch"in de,Ha=rB()&&$o({fetch:de.fetch,Request:de.Request,AbortController:de.AbortController}),gT=Ha?hd({fetch:de.fetch,Request:de.Request,AbortController:de.AbortController}):void 0,Je=Ha?gT.fetch:de.fetch,bW=Ha?gT.Request:de.Request,te=Ha?Bi:de.AbortController,gW=Ha?Rr:de.AbortSignal;var uE=_(De(),1);var OT=_(_T(),1);import{ErrorCategory as Wa}from"@vkontakte/videoplayer-shared/es2018";var Mo=a=>{if(!a)return{id:"EmptyResponse",category:Wa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Wa.NETWORK,message:`UV Error ${a}`};let e=(0,OT.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Wa.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Wa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Wa.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as sE,assertNonNullable as Lt,ErrorCategory as qi,filter as Nd,filterChanged as mV,flattenObject as Go,fromEvent as Ui,getTraceSubscriptionMethod as fV,getWindow as xs,interval as bV,isNonNullable as ri,isNullable as Ps,map as Fd,merge as ks,now as gV,Subject as ai,Subscription as nE,SubscriptionRemovable as vV,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2018";var Zt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Co=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as za,assertNever as NT,ErrorCategory as Ga,flattenObject as $r,fromEvent as FT,getWindow as yB,merge as TB,now as Ya,Subject as Mr,Subscription as IB,ValueSubject as vd}from"@vkontakte/videoplayer-shared/es2018";var ot=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Lo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Bo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Mr;this.manifestReceived=new Mr;this.firstBytesRequested=new Mr;this.firstBytesReceived=new Mr;this.lastConnectionType$=new vd(void 0);this.lastConnectionReused$=new vd(void 0);this.lastRequestFirstBytes$=new vd(void 0);this.recoverableError$=new Mr;this.error$=new Mr;this.abortAllController=new te;this.subscription=new IB;this.fetchManifest=za(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Lo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Do);return r?(t.log("success",$r({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",$r({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=za(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var q,G,H;let d=e,c=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(d,yB().location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),d=E.toString();break}default:NT(t)}this.requestQuic&&(d=Zt(d));let h=this.abortAllController.signal,m;if(n){let E=new te;if(m=TB(FT(this.abortAllController.signal,"abort"),FT(n,"abort")).subscribe(()=>{try{E.abort()}catch(P){Do(P)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(P){Do(P)}h=E.signal}let f=0,v=Ya();p.log("startRequest",$r({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.firstBytesRequested.next();let g=yield this.doFetch(d,{priority:s,headers:c,signal:h}),S=Ya();if(!g)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((q=this.throughputEstimator)==null||q.addRawRtt(S-v),!g.ok||!g.body){m==null||m.unsubscribe();let E=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:E}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){m==null||m.unsubscribe();let E=Ya(),P={requestStartedAt:v,requestEndedAt:E,duration:E-v};return p.log("endRequest",$r(P)),p.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),(G=this.throughputEstimator)==null||G.trackStream(E,u)}let y=T.getReader(),w,R=parseInt((H=g.headers.get("content-length"))!=null?H:"",10);Number.isFinite(R)&&(w=R),!w&&i&&(w=i.to-i.from+1);let L=w?new Uint8Array(w):new Uint8Array(0),$=!1,D=E=>{m==null||m.unsubscribe(),$=!0,Do(E)},A=za(h,async function*({done:E,value:P}){if(f===0&&(this.lastRequestFirstBytes$.next(Ya()-v),this.firstBytesReceived.next()),h.aborted){m==null||m.unsubscribe();return}if(!E&&P){if(l&&w)L.set(P,f),f+=P.byteLength;else{let I=new Uint8Array(L.length+P.length);I.set(L),I.set(P,L.length),L=I,f+=P.byteLength}r==null||r(new DataView(L.buffer),f),yield y==null?void 0:y.read().then(A,D)}}.bind(this));yield y==null?void 0:y.read().then(A,D),m==null||m.unsubscribe();let V=Ya(),M={failed:$,requestStartedAt:v,requestEndedAt:V,duration:V-v};return $?(p.error("endRequest",$r(M)),p.end(),null):(p.log("endRequest",$r(M)),p.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=za(this.abortAllController.signal,async function*(e,t,i){var g;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),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 p=new DataView(c,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(g=e.indexRange)!=null?g:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=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;f=new DataView(S)}let v=t.parseSegments(f,h,m).map(S=>({networkStatus:"none",bufferStatus:"none",status:"none",time:S.time,byte:S.byte}));return{initMetadata:h,initDataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=za(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});if(!r)return null;let s=e.segments.map(n=>({...n,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:s}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Co(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=this.fetchTemplateRepresentation(e,i))!=null?n:null;default:NT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Je(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ga.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ga.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ga.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ga.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ga.FATAL})}}},Do=a=>{if(!ot(a))throw a};var Pd=_(lI(),1),MI=_(zt(),1),CI=_(xI(),1),LI=_(Ke(),1),kd=_(Ei(),1);var PI=_(De(),1),xd=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,PI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as I0,isNullable as RI}from"@vkontakte/videoplayer-shared/es2018";var kI=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var AI=a=>{var e;try{let t=T0(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function T0(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
172
172
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
173
173
|
(-(?<script>[a-z]{4}))?
|
|
174
174
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
175
175
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
176
176
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
177
177
|
(?:-(?<privateuse>(?:${e})))?
|
|
178
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var FE=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},it=(a,e)=>{let t=a;t=(0,vp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,UE.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,vp.default)(t,n,(o,u)=>NE(s)?o:NE(u)?s:(0,qE.default)(s,parseInt(u,10),"0"))}return t},ls=(a,e)=>{var L,M,B,D,N,z,W,I,w,x,k,_,U,wt,xt,X,we,xe,Pe,Je,Vt,_t,Mi,vr,yr,Oh,Nh,Fh,Uh,qh,jh,Hh,Wh,zh,Qh,Gh,Yh,Kh,Xh,Jh,Zh,ef,tf,rf,sf,af,nf,of,uf,lf,cf,df,pf,hf,ff,mf,bf,gf,Sf,vf,yf;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(pt=>{var te,Li;return(Li=(te=pt.textContent)==null?void 0:te.trim())!=null?Li:""}),o=(L=(0,jE.default)(n,0))!=null?L:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],p=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let b,v=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],y=T.reduce((pt,te)=>({...pt,[te.id]:te.children}),{}),E=T.reduce((pt,te)=>({...pt,[te.id]:te.getAttribute("duration")}),{});v?b=FE(v):(0,yp.default)(E).filter(pt=>pt).length&&!u?b=(0,yp.default)(E).reduce((pt,te)=>{var Li;return pt+((Li=FE(te))!=null?Li:0)},0):m&&(b=parseInt(m,10));let P=0,$=(B=(M=s.getAttribute("profiles"))==null?void 0:M.split(","))!=null?B:[];for(let pt of T.map(te=>te.id))for(let te of y[pt]){let Li=(D=te.getAttribute("id"))!=null?D:"id"+(P++).toString(10),Ls=(N=te.getAttribute("mimeType"))!=null?N:"",gl=(z=te.getAttribute("codecs"))!=null?z:"",Sl=(W=te.getAttribute("contentType"))!=null?W:Ls==null?void 0:Ls.split("/")[0],Zx=(w=(I=te.getAttribute("profiles"))==null?void 0:I.split(","))!=null?w:[],Tf=(k=OE((x=te.getAttribute("lang"))!=null?x:""))!=null?k:{},zn=(wt=(U=(_=te.querySelector("Label"))==null?void 0:_.textContent)==null?void 0:U.trim())!=null?wt:void 0,eP=te.querySelectorAll("Representation"),tP=te.querySelector("SegmentTemplate"),iP=(X=(xt=te.querySelector("Role"))==null?void 0:xt.getAttribute("value"))!=null?X:void 0,Tr=Sl,ce={id:Li,language:Tf.language,isDefault:iP==="main",label:zn,codecs:gl,hdr:Tr==="video"&&Sp(gl),mime:Ls,representations:[]};for(let ee of eP){let ii=(we=ee.getAttribute("lang"))!=null?we:void 0,Qn=(Pe=(xe=zn!=null?zn:te.getAttribute("label"))!=null?xe:ee.getAttribute("label"))!=null?Pe:void 0,Gn=(_t=(Vt=(Je=ee.querySelector("BaseURL"))==null?void 0:Je.textContent)==null?void 0:Vt.trim())!=null?_t:"",Di=new URL(Gn||o,e).toString(),ri=(Mi=ee.getAttribute("mimeType"))!=null?Mi:Ls,Yn=(yr=(vr=ee.getAttribute("codecs"))!=null?vr:gl)!=null?yr:"",Kn;if(Sl==="text"){let si=ee.getAttribute("id")||"",Xn=((Oh=Tf.privateuse)==null?void 0:Oh.includes("x-auto"))||si.includes("_auto"),Bi=ee.querySelector("SegmentTemplate");if(Bi){let Ds={representationId:(Nh=ee.getAttribute("id"))!=null?Nh:void 0,bandwidth:(Fh=ee.getAttribute("bandwidth"))!=null?Fh:void 0},Jn=parseInt((Uh=ee.getAttribute("bandwidth"))!=null?Uh:"",10)/1e3,Zn=(jh=parseInt((qh=Bi.getAttribute("startNumber"))!=null?qh:"",10))!=null?jh:1,Ir=parseInt((Hh=Bi.getAttribute("timescale"))!=null?Hh:"",10),vl=(Wh=Bi.querySelectorAll("SegmentTimeline S"))!=null?Wh:[],Er=Bi.getAttribute("media");if(!Er)continue;let eo=[],to=0,io="",wr=0,Bs=Zn,_e=0;for(let ht of vl){let Ci=parseInt((zh=ht.getAttribute("d"))!=null?zh:"",10),nt=parseInt((Qh=ht.getAttribute("r"))!=null?Qh:"",10)||0,ai=parseInt((Gh=ht.getAttribute("t"))!=null?Gh:"",10);_e=Number.isFinite(ai)?ai:_e;let Vi=Ci/Ir*1e3,ni=_e/Ir*1e3;for(let Pt=0;Pt<nt+1;Pt++){let oi=it(Er,{...Ds,segmentNumber:Bs.toString(10),segmentTime:(_e+Pt*Ci).toString(10)}),xr=(ni!=null?ni:0)+Pt*Vi,Vs=xr+Vi;Bs++,eo.push({time:{from:xr,to:Vs},url:oi})}_e+=(nt+1)*Ci,to+=(nt+1)*Vi}wr=_e/Ir*1e3,io=it(Er,{...Ds,segmentNumber:Bs.toString(10),segmentTime:_e.toString(10)});let Cs={time:{from:wr,to:1/0},url:io},Ot={type:"template",baseUrl:Di,segmentTemplateUrl:Er,initUrl:"",totalSegmentsDurationMs:to,segments:eo,nextSegmentBeyondManifest:Cs,timescale:Ir};Kn={id:si,kind:"text",segmentReference:Ot,profiles:[],duration:b,bitrate:Jn,mime:"",codecs:"",width:0,height:0,isAuto:Xn}}else Kn={id:si,isAuto:Xn,kind:"text",url:Di}}else{let si=(Kh=(Yh=ee.getAttribute("contentType"))!=null?Yh:ri==null?void 0:ri.split("/")[0])!=null?Kh:Sl,Xn=(Jh=(Xh=te.getAttribute("profiles"))==null?void 0:Xh.split(","))!=null?Jh:[],Bi=parseInt((Zh=ee.getAttribute("width"))!=null?Zh:"",10),Ds=parseInt((ef=ee.getAttribute("height"))!=null?ef:"",10),Jn=parseInt((tf=ee.getAttribute("bandwidth"))!=null?tf:"",10)/1e3,Zn=(rf=ee.getAttribute("frameRate"))!=null?rf:"",Ir=(sf=ee.getAttribute("quality"))!=null?sf:void 0,vl=Zn?_E(Zn):void 0,Er=(af=ee.getAttribute("id"))!=null?af:"id"+(P++).toString(10),eo=si==="video"?`${Ds}p`:si==="audio"?`${Jn}Kbps`:Yn,to=`${Er}@${eo}`,io=[...$,...Zx,...Xn],wr,Bs=ee.querySelector("SegmentBase"),_e=(nf=ee.querySelector("SegmentTemplate"))!=null?nf:tP;if(Bs){let Ot=(uf=(of=ee.querySelector("SegmentBase Initialization"))==null?void 0:of.getAttribute("range"))!=null?uf:"",[ht,Ci]=Ot.split("-").map(oi=>parseInt(oi,10)),nt={from:ht,to:Ci},ai=(lf=ee.querySelector("SegmentBase"))==null?void 0:lf.getAttribute("indexRange"),[Vi,ni]=ai?ai.split("-").map(oi=>parseInt(oi,10)):[],Pt=ai?{from:Vi,to:ni}:void 0;wr={type:"byteRange",url:Di,initRange:nt,indexRange:Pt}}else if(_e){let Ot={representationId:(cf=ee.getAttribute("id"))!=null?cf:void 0,bandwidth:(df=ee.getAttribute("bandwidth"))!=null?df:void 0},ht=parseInt((pf=_e.getAttribute("timescale"))!=null?pf:"",10),Ci=(hf=_e.getAttribute("initialization"))!=null?hf:"",nt=_e.getAttribute("media"),ai=(mf=parseInt((ff=_e.getAttribute("startNumber"))!=null?ff:"",10))!=null?mf:1,Vi=it(Ci,Ot);if(!nt)throw new ReferenceError("No media attribute in SegmentTemplate");let ni=(bf=_e.querySelectorAll("SegmentTimeline S"))!=null?bf:[],Pt=[],oi=0,xr="",Vs=0;if(ni.length){let ro=ai,ft=0;for(let Pr of ni){let kt=parseInt((gf=Pr.getAttribute("d"))!=null?gf:"",10),_i=parseInt((Sf=Pr.getAttribute("r"))!=null?Sf:"",10)||0,so=parseInt((vf=Pr.getAttribute("t"))!=null?vf:"",10);ft=Number.isFinite(so)?so:ft;let yl=kt/ht*1e3,Tl=ft/ht*1e3;for(let ao=0;ao<_i+1;ao++){let sP=it(nt,{...Ot,segmentNumber:ro.toString(10),segmentTime:(ft+ao*kt).toString(10)}),If=(Tl!=null?Tl:0)+ao*yl,aP=If+yl;ro++,Pt.push({time:{from:If,to:aP},url:sP})}ft+=(_i+1)*kt,oi+=(_i+1)*yl}Vs=ft/ht*1e3,xr=it(nt,{...Ot,segmentNumber:ro.toString(10),segmentTime:ft.toString(10)})}else if(t_(b)){let ft=parseInt((yf=_e.getAttribute("duration"))!=null?yf:"",10)/ht*1e3,Pr=Math.ceil(b/ft),kt=0;for(let _i=1;_i<Pr;_i++){let so=it(nt,{...Ot,segmentNumber:_i.toString(10),segmentTime:kt.toString(10)});Pt.push({time:{from:kt,to:kt+ft},url:so}),kt+=ft}Vs=kt,xr=it(nt,{...Ot,segmentNumber:Pr.toString(10),segmentTime:kt.toString(10)})}let rP={time:{from:Vs,to:1/0},url:xr};wr={type:"template",baseUrl:Di,segmentTemplateUrl:nt,initUrl:Vi,totalSegmentsDurationMs:oi,segments:Pt,nextSegmentBeyondManifest:rP,timescale:ht}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!si||!ri)continue;let Cs={video:"video",audio:"audio",text:"text"}[si];if(!Cs)continue;Tr||(Tr=Cs),Kn={id:to,kind:Cs,segmentReference:wr,profiles:io,duration:b,bitrate:Jn,mime:ri,codecs:Yn,width:Bi,height:Ds,fps:vl,quality:Ir}}ce.language||(ce.language=ii),ce.label||(ce.label=Qn),ce.mime||(ce.mime=ri),ce.codecs||(ce.codecs=Yn),ce.hdr||(ce.hdr=Tr==="video"&&Sp(Yn)),ce.representations.push(Kn)}if(Tr){let ee=r[Tr].find(ii=>ii.id===ce.id);if(ee&&ce.representations.every(ii=>ii.segmentReference.type==="template"))for(let ii of ee.representations){let Qn=ce.representations.find(ri=>ri.id===ii.id);if(!Qn)continue;let Gn=Qn.segmentReference,Di=ii.segmentReference;Di.segments.push(...Gn.segments),Di.nextSegmentBeyondManifest=Gn.nextSegmentBeyondManifest}else r[Tr].push(ce)}}return{duration:b,streams:r,baseUrls:n,live:g}};var Pu=O(Ye(),1),Tp=O(Re(),1);import{assertNever as ku}from"@vkontakte/videoplayer-shared/es2018";var xu=a=>{let{webmDecodingInfo:e}=C.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:ku(a)}},HE=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...xu(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(C.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...xu(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...xu(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...xu(a),...s,"HLS","HLS_ONDEMAND"];default:ku(e)}if(C.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:ku(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},WE=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=C.device.isMac&&C.browser.isSafari;if(C.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:ku(a)}else C.video.nativeHlsSupported&&!u&&!C.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Ip=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],cs=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Pu.default)(t.value.split("."),0)}for(let t of a){let i=(0,Pu.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Pu.default)(e.value.split("."),0)},ds=a=>{let e=a.map(i=>vi(i)),{codecs:t}=C.video;return a_().filter(i=>{if((0,Tp.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})},ps=a=>{let e=a.map(i=>vi(i)),{codecs:t}=C.video;return n_().filter(i=>{if((0,Tp.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},vi=a=>a.split(".")[0].replace("0",""),a_=()=>["av1","vp9","hev1","avc1"],n_=()=>["opus","mp4a"];var aw=O(Ye(),1);var o_=(a,e={})=>{let i=e.timeout||1,r=performance.now();return he.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},u_=a=>he.clearTimeout(a),zE=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),QE=!zE(he.requestIdleCallback)||!zE(he.cancelIdleCallback),Dt=QE?o_:he.requestIdleCallback,lt=QE?u_:he.cancelIdleCallback;import{abortable as Ap,assertNonNullable as Bt,ErrorCategory as R_,fromEvent as $_,getExponentialDelay as M_,getWindow as sw,isHigher as L_,isNonNullable as de,isNullable as Ie,once as D_,Subject as B_,Subscription as C_,ValueSubject as an}from"@vkontakte/videoplayer-shared/es2018";var GE=O(Ye(),1);var Au=a=>a.valid,Y=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var hs=class extends Y{};import{assertNever as l_}from"@vkontakte/videoplayer-shared/es2018";var La=class extends Y{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:l_(e)}}};var Da=class extends Y{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Ba=class extends Y{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ie=class extends Y{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 Ca=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var Va=class extends Y{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _a=class extends Y{constructor(e,t){super(e,t),this.data=this.content}};var ar=class extends ie{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var Oa=class extends Y{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Na=class extends Y{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fa=class extends ie{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ua=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var qa=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var ja=class extends Y{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ha=class extends ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Wa=class extends Y{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var za=class extends Y{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Qa=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ga=class extends Y{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends ie{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ka=class extends ie{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Xa=class extends ie{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Ja=class extends Y{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var en=class extends Y{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var d_={ftyp:Da,moov:Ba,mvhd:Ca,moof:Va,mdat:_a,sidx:ar,trak:Oa,mdia:ja,mfhd:Qa,tkhd:Ha,traf:Ga,tfhd:Ya,tfdt:Ka,trun:Xa,minf:Wa,sv3d:Na,st3d:Fa,prhd:Ua,proj:za,equi:qa,uuid:La,stbl:Ja,stsd:Za,avc1:en,unknown:hs},zt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!Au(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=d_[e];return i?new i(t,new a):new hs(t,new a)}};var yi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;Au(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var h_=new TextDecoder("ascii"),f_=a=>h_.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",m_=a=>{let e=new ar(a,new zt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},b_=(a,e)=>{let i=new zt().parse(a),r=new yi(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},g_=a=>{let t=new zt().parse(a),i=new yi(t),r={},s=i.findAll("uuid"),n=(0,GE.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},S_=a=>{var r;let t=new zt().parse(a);return(r=new yi(t).find("sidx"))==null?void 0:r.timescale},v_=(a,e)=>{let i=new zt().parse(a),s=new yi(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},y_=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new zt().parse(a),r=new yi(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},YE={validateData:f_,parseInit:y_,getIndexRange:()=>{},parseSegments:m_,parseFeedableSegmentChunk:b_,getChunkEndTime:v_,getServerLatencyTimestamps:g_,getTimescaleFromIndex:S_};var rn=O(Re(),1);import{assertNonNullable as Ep,isNonNullable as ZE,isNullable as I_}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as T_}from"@vkontakte/videoplayer-shared/es2018";var KE={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"}},XE=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=tn(a,t),r=i in KE,s=r?KE[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,d=tn(u),c=l*2**((o-1)*8)+d,p=t+o,h;return p+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},tn=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},It=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return tn(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:T_(e)}},nr=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=XE(i);if(!e(r))return;r.type==="master"&&nr(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},JE=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=XE(a);return nr(r.value,({tag:s,type:n,value:o})=>(s===17143?e=It(o,n):s===17026?t=It(o,n):s===17029&&(i=It(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var ew=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],E_=[231,22612,22743,167,171,163,160,175],w_=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return nr(a,({tag:p,type:h,value:f,valueSize:m})=>{if(p===21419){let g=It(f,h);l=tn(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+m):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=It(f,h):p===17545?r=It(f,h):p===21420&&l===475249515?u=It(f,h):p===374648427?nr(f,({tag:g,type:b,value:v})=>g===30321?(d=It(v,b)===1,!1):!0):s&&n&&(0,rn.default)(ew,p)&&(o=!0),!o}),Ep(e,"Failed to parse webm Segment start"),Ep(t,"Failed to parse webm Segment end"),Ep(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},x_=a=>{if(I_(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},P_=(a,e)=>{let t=!1,i=!1,r=o=>ZE(o.time)&&ZE(o.position),s=[],n;return nr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=It(l,u));break;case 183:break;case 241:n&&(n.position=It(l,u));break;default:t&&(0,rn.default)(ew,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},k_=a=>{let e=0,t=!1;try{nr(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,rn.default)(E_,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,rn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},tw={validateData:JE,parseInit:w_,getIndexRange:x_,parseSegments:P_,parseFeedableSegmentChunk:k_};var ct=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return tw;case"mp4":return YE}}throw new ReferenceError(`Unsupported mime type ${a}`)};var wp=O(Ye(),1);import{videoSizeToQuality as A_}from"@vkontakte/videoplayer-shared/es2018";var Ti=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Lt(s):void 0)!=null?u:A_({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},sn=({id:a,bitrate:e})=>({id:a,bitrate:e}),iw=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),rw=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),xp=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,wp.default)(i.split("."),0),isDefault:r}),Pp=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,wp.default)(r.split("."),0)}),kp=a=>"url"in a,rt=a=>a.type==="template";var fs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,manifest:o}){this.error$=new B_;this.playingRepresentation$=new an(void 0);this.playingRepresentationInit$=new an(void 0);this.currentSegmentLength$=new an(0);this.onLastSegment$=new an(!1);this.fullyBuffered$=new an(!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 Q;this.downloadAbortController=new Q;this.subscription=new C_;this.startWith=Ap(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Bt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=ct(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Bt(i,"No init buffer for starting representation"),Bt(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=Ap(this.destroyAbortController.signal,async function*(e,t=!0){var c;if(Ie(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);Bt(r,`No such representation ${e}`),Bt(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),n=this.segments.get(r.id);Bt(s,"No init buffer for switching representation"),Bt(n,"No segments for switching representation");let o=(c=this.getCurrentPosition())!=null?c:0,u=p=>p.segment.networkStatus!=="downloaded"||p.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,l=p=>{let h=this.representations.get(p.representationId);return Bt(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},d=p=>t?u(p)&&l(p):u(p);this.bufferPlaybackQueue.filter(d).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!d(p)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=Ap(this.downloadAbortController.signal,async function*(){let e=M_(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=sw();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add($_(i,"online").pipe(D_()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));var u;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=(u=o==null?void 0:o.baseUrls)!=null?u:[],this.representations=new Map(i.map(l=>[l.id,l]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){Ie(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return de(t)&&de(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){var s,n;let t=(n=(s=this.downloadingRepresentationId)!=null?s:this.playingRepresentationId)!=null?n:"",i=this.segments.get(t),r=i==null?void 0:i.find(o=>o.time.from<=e&&o.time.to>=e);return r==null?void 0:r.time.from}getRepresentationInitialTime(){var t;if(Ie(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return((t=e==null?void 0:e[0].time.from)!=null?t:0)/1e3}calculateDurationFromSegments(){var t;if(Ie(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,aw.default)(e,-1))==null?void 0:t.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=sw();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_g5ech8n8e64)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_g5ech8n8e64(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=Ti(e),s=Ti(t);i=de(r)&&de(s)&&L_(s.quality,r.quality)}else if(this.kind==="audio"){let r=sn(e),s=sn(t);i=de(r==null?void 0:r.bitrate)&&de(s==null?void 0:s.bitrate)&&s.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 Q,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,Dt(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():de(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){var r;try{let s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s);this.initDataPromises.set(e.id,n);let{initMetadata:o,initDataView:u,segments:l}=(r=await n)!=null?r:{};if(this.initDataPromises.delete(e.id),Ie(u)||Ie(l))return;o&&this.parsedInitData.set(e.id,o);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d),this.segments.set(e.id,l),this.failedDownloads=0}catch(s){i&&this.error$.next({id:"LoadInits",category:R_.WTF,message:"loadInit threw",thrown:s})}}async maintainNativeBuffer(){var o;let e=this.getCurrentPosition();if(Ie(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(u=>this.withinInterval(e,u.segment.time)),i=this.bufferPlaybackQueue.find(u=>u.segment.bufferStatus!=="fed"),r=this.initData.get((o=i==null?void 0:i.representationId)!=null?o:""),s=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;de(r)&&de(i)&&de(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)),de(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)),de(s)&&this.withinRemoveInterval(e,s.segment.time)&&await this.removeSegment(s,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Bt(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(Ie(t)||Ie(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);de(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let s=this.selectItemsToLoad();await this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if(Ie(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];Ie(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){Bt(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;de(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&s>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;s-=u-o,r++}return n}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 de(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return de(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 de(e)?e-i>t:!1}async appendSegmentFully(e,t){if(Ie(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(Ie(e.segment.data)||Ie(e.segment.loadedBytes)||Ie(e.segment.feedingBytes)||Ie(e.segment.fedBytes)||Ie(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s!=null&&s.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,await this.nativeBufferManager.append(s,t)&&(e.segment.fedBytes+=s.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,s=(r-i)/4;await this.nativeBufferManager.remove(0,r-s,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||de(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let s=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)de(o.size)&&s>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())de(o.size)&&s>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size)}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as V_,isNonNullable as __,isNullable as nw,now as ow}from"@vkontakte/videoplayer-shared/es2018";var Ru=class extends fs{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:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(s,{...n,priority:i}),this.lastDataObtainedTimestampMs=ow(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Ce(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=s);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(je(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=ow(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:V_.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:s,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||nw(o)||nw(r)||n.aborted))for(let u of e){let{segment:l}=u,d=l.byte.from-r,c=l.byte.to-r,p=c-d+1,h=d<s,f=c<=s;l.size=p,h&&(l.networkStatus==="downloading"&&l.bufferStatus==="none"&&f?(l.data=new DataView(t.buffer,t.byteOffset+d,p),this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u),l.loadedBytes=Math.min(p,s-d),await this.onDownloadItem(u)):__(l.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&l.networkStatus==="downloading"&&(l.loadedBytes=Math.min(p,s-d),f&&(this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u)),l.loadedBytes>l.feedingBytes&&(l.data=new DataView(t.buffer,t.byteOffset+d,l.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(je(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as O_,isNullable as Rp,now as uw}from"@vkontakte/videoplayer-shared/es2018";var ms=class extends fs{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:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(s,{...n,priority:i});if(this.lastDataObtainedTimestampMs=uw(),Rp(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(),Ce(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=uw(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:O_.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!je(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:s}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||Rp(u)||Rp(o.feedingBytes)||o.networkStatus!=="downloading"||s.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(!je(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var $p=O(rr(),1),cw=O(Ye(),1);import{assertNonNullable as N_,ErrorCategory as F_,isNullable as Qt,ValueSubject as lw}from"@vkontakte/videoplayer-shared/es2018";var $u=class extends ms{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new lw(0);this.currentLowLatencySegmentLength$=new lw(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){var r,s,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,$p.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if(Qt(o)||!je(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(s=(0,cw.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>c>=h.time.from+l&&c<=h.time.to+l);if(p===-1){let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...d,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;N_(t);let i=this.segments.get(t);if(i!=null&&i.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t==null?void 0:t.streams[this.kind],r=(0,$p.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if(Qt(r))return;let s=this.segments.get(r.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){var r;if(Qt(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return Qt(t)||!je(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),Qt(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);s&&n&&this.currentLiveSegmentServerLatency$.next(n-s),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){var n;let i=t.segment.data,r=(n=this.representations.get(t.representationId))==null?void 0:n.segmentReference;if(Qt(t.segment.data)||Qt(r)||!je(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=s.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let s of this.representations.values()){let n=s.segmentReference;if(!je(n))return;let o=(r=this.segments.get(s.id))!=null?r:[],u=o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.from));if(u!=null&&u.isCurrentLowLatency&&(u.time.to=t.segment.time.to,i=u.time.to-u.time.from,u.isCurrentLowLatency=!1),!!!o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let d=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),c=it(n.segmentTemplateUrl,{segmentTime:d});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:c,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){var s;try{let n=this.tuning.dash.useFetchPriorityHints?i:"auto",o=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,n);this.initDataPromises.set(t.id,o);let{initMetadata:u,initDataView:l,segments:d}=(s=await o)!=null?s:{};if(this.initDataPromises.delete(t.id),Qt(l)||Qt(d))return;u&&this.parsedInitData.set(t.id,u);let c=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,c);let p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(t.id,p),this.failedDownloads=0}catch(n){r&&this.error$.next({id:"LoadInits",category:F_.WTF,message:"loadInit threw",thrown:n})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[],n=0,o=i.length-1;do s.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[s[0]]:s}};var nn=class{static getBufferManager(e,t,i,r){var s;return(s=r.manifest)!=null&&s.live?new $u(e,t,i,r):je(i[0].segmentReference)?new ms(e,t,i,r):new Ru(e,t,i,r)}};import{ErrorCategory as j_,fromEvent as H_,isNullable as bs,Subject as W_,Subscription as z_}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as U_,ErrorCategory as dw,Subject as pw}from"@vkontakte/videoplayer-shared/es2018";var q_=18,hw=!1;try{hw=C.browser.isSafari&&!!C.browser.safariVersion&&C.browser.safariVersion<=q_}catch(a){console.error(a)}var Mp=class{constructor(e,t=!1){this.bufferFull$=new pw;this.error$=new pw;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:dw.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};hw&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:dw.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:U_(t)}}},fw=Mp;var me=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var on=class{constructor(e){this.error$=new W_;this.subscription=new z_;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new fw(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add(H_(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:j_.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(bs(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&(i=await this.sourceBufferTaskQueue.remove(r.from,r.to,e));return i}warmUpMediaSource(){!bs(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(bs(this.sourceBuffer)||!F(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 bs(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||bs(e)?0:me(this.sourceBuffer.buffered,e)}async abortBuffer(e){return bs(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){var e;if(this.subscription.unsubscribe(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null}};var J_=["timeupdate","progress","play","seeked","stalled","waiting"],gw=["timeupdate","progress","loadeddata","playing","seeked"],Lu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new bw;this.subscriptionRemovable=new X_;this.representationSubscription=new bw;this.forceEnded$=new Ei;this.destroyController=new Q;this.state$=new j("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new Ei;this.manifestRequested=new Ei;this.manifestReceived=new Ei;this.firstBytesRequested=new Ei;this.firstBytesReceived=new Ei;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.isActiveLive$=new re(!1);this.isLowLatency$=new re(!1);this.liveDuration$=new re(0);this.liveSeekableDuration$=new re(0);this.liveAvailabilityStartTime$=new re(0);this.liveStreamStatus$=new re(void 0);this.currentBuffer$=new re({from:0,to:0});this.bufferLength$=new re(0);this.nativeBufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.fetcherRecoverableError$=new Ei;this.fetcherError$=new Ei;this.initRepresentations=mw(this.destroyController.signal,async function*(e,t,i){var s;this.tracer.log("initRepresentationsStart",Mu({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(),Gt(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?(s=this.audioBufferManager)==null?void 0:s.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=mw(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){ln(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:or.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 Eu({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){var r;this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:or.PARSER,message:"No playable video representations"})}initBuffer(){var t,i;Gt(this.element),this.state$.setState("running"),this.subscription.add(cn(...J_.map(r=>ur(this.element,r)),ur(un(),"online")).subscribe(()=>this.tick(),r=>this.error$.next({id:"DashVKPlayer",category:or.WTF,message:"Internal logic error",thrown:r})));let e=[...(i=(t=this.source)==null?void 0:t.activeSourceBuffers)!=null?i:[]];this.subscription.add(cn(...e.map(r=>ur(r,"updateend"))).subscribe(r=>this.reinitDecoderIfNeeded())),this.subscription.add(ur(this.element,"waiting").subscribe(r=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Y_(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),s=>this.error$.next({id:"StallWatchdogCallback",category:or.NETWORK,message:"Can't restore DASH after stall.",thrown:s})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}async seek(e,t=!1){var r,s,n,o;Gt(this.element),Gt(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await((o=this.audioBufferManager)==null?void 0:o.seek(i)),this.tracer.log("seek",Mu({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){Ii(this.element)&&Ii(this.source)&&Ii(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(i=>i.warmUpMediaSource())}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(r=>r.destroy()),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&un().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),Ii(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){var e;return((e=this.source)==null?void 0:e.readyState)!=="open"}async reinitDecoderIfNeeded(e=!1){var r,s;let t=(s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[];if(ln(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(n=>i>=n.from&&i<=n.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){Gt(this.element),Gt(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",Mu(i))}isStallExceeded(e){var p,h,f,m,g,b,v,T;let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=K_(),s=100,n=(h=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?h:0;this.videoLastDataObtainedTimestamp$.next(n);let o=(m=(f=this.audioBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0,u=(b=(g=this.videoBufferManager)==null?void 0:g.getForwardPlaybackBufferDuration())!=null?b:0,l=(T=(v=this.audioBufferManager)==null?void 0:v.getForwardPlaybackBufferDuration())!=null?T:0,d=Ii(this.videoBufferManager)&&u<s&&r-n>i,c=Ii(this.audioBufferManager)&&l<s&&r-o>i;return(d||c)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(ln(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",Mu(i)),i}parseManifest(e){var t;try{return ls(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=is(e))!=null?t:{id:"ManifestParsing",category:or.PARSER,message:"Failed to parse MPD manifest",thrown:i};this.error$.next(r)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,l)=>{var d,c,p,h;return!!((c=(d=this.element)==null?void 0:d.canPlayType)!=null&&c.call(d,u)&&((h=(p=Oe())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${l}"`))||o==="text")},r,s;for(let o of["video","audio"]){let l=e.streams[o].filter(({mime:c,codecs:p})=>i(o,c,p));t[o]=l;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:p})=>p);o==="audio"&&(s=ps(c),d=s[0]),o==="video"&&(r=ds(c),this.forceVideoCodec&&(0,Sw.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=l.filter(({codecs:p})=>vi(p)===d))}else{let c=new Set(l.map(({codecs:p})=>p));d=cs(c),d&&(t[o]=l.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let c=this.tuning.preferHDR,p=t.video.some(f=>f.hdr),h=t.video.some(f=>!f.hdr);C.display.isHDR&&c&&p?t.video=t.video.filter(f=>f.hdr):h&&(t.video=t.video.filter(f=>!f.hdr))}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:s}),n}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){Gt(this.manifest),Gt(this.element);let s=l=>{this.representationSubscription.add(ur(l,"error").pipe(Lp(d=>{var c;return!!((c=this.element)!=null&&c.played.length)})).subscribe(d=>{this.error$.next({id:"VideoSource",category:or.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Br();let n=un().document,o=n.createElement("source");if(s(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),di())if(r){let l=n.createElement("source");s(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,d)=>[...l,...d.representations],[]);if(this.videoNativeBufferManager=new on(this.source),this.videoBufferManager=nn.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],Ii(i)){this.audioNativeBufferManager=new on(this.source);let l=this.manifest.streams.audio.reduce((d,c)=>[...d,...c.representations],[]);this.audioBufferManager=nn.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=>{var i;e&&(this.timeoutSourceOpenId=un().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:or.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(i=this.source)==null||i.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&un().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(cn(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),Gt(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(cn(...gw.map(e=>ur(this.element,e))).pipe(Dp(e=>{var t;return(t=this.videoBufferManager)==null?void 0:t.getPlaybackBufferState()}),Lp(Ii),Dp(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(cn(...gw.map(e=>ur(this.element,e))).pipe(Dp(e=>{var t,i,r,s;return Math.max((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(s=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?s:0)}),Q_()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Lp(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=G_(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){var r,s,n;if(ln(this.element)||ln(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[]).find(o=>e>=o.from&&e<=o.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await((n=this.audioBufferManager)==null?void 0:n.maintain(e))}};import{assertNonNullable as Du,combine as Z_,ErrorCategory as eO,filter as Bp,filterChanged as tO,fromEvent as iO,isNonNullable as rO,map as Cp,merge as dn}from"@vkontakte/videoplayer-shared/es2018";var Bu=class extends Lu{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;Du(this.manifest),Du(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,Vp.default)((0,Vp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),je(i.segmentReference)&&i.segmentReference.totalSegmentsDurationMs&&r.push(i.segmentReference.totalSegmentsDurationMs),r})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){var i,r;Du(this.element);let t=this.element.currentTime*1e3;await Promise.all([(i=this.videoBufferManager)==null?void 0:i.maintain(t),(r=this.audioBufferManager)==null?void 0:r.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){Du(this.element);let e=dn(iO(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(Bp(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(dn(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=dn(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe(Cp(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=dn(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe(Cp(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=Z_({allBuffersFull:e,someBufferEnded:t}).pipe(tO(),Cp(({allBuffersFull:s,someBufferEnded:n})=>s&&n),Bp(s=>s)),r=()=>{var s;try{(s=this.source)==null||s.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:eO.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add(dn(this.forceEnded$,i).pipe(Bp(s=>rO(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var gs=class extends xa{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(sO()).subscribe(s=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:c}])=>c.id===s);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(fu(u));let d=this.player.calculateDurationFromSegments();d&&this.params.output.duration$.next(d/1e3)},r))}getPlayer(){return new Bu({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)}};import{assertNever as RO,assertNonNullable as $O,combine as MO,debounce as LO,ErrorCategory as Mw,filter as zp,filterChanged as yn,fromEvent as DO,isNonNullable as Lw,isNullable as BO,map as Tn,merge as In,observableFrom as zu,once as Dw,Subscription as CO,throttle as VO}from"@vkontakte/videoplayer-shared/es2018";var $w=O(Re(),1),Hp=O(rr(),1);var Ve=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Up,assertNonNullable as Is,combine as Es,ErrorCategory as dt,filter as ju,filterChanged as gn,flattenObject as Sn,fromEvent as Xt,getTraceSubscriptionMethod as gO,interval as qp,isNonNullable as vn,isNullable as kw,map as ws,merge as dr,now as jp,Subject as Jt,Subscription as Aw,SubscriptionRemovable as SO,tap as vO,throttle as yO,ValueSubject as se}from"@vkontakte/videoplayer-shared/es2018";var Vu=O(Re(),1),cr=O(Ye(),1),_u=O(rr(),1);var Ew=O(Yo(),1);import{assertNever as aO,ErrorCategory as vw,Subject as yw}from"@vkontakte/videoplayer-shared/es2018";var nO=18,Tw=!1;try{Tw=C.browser.isSafari&&!!C.browser.safariVersion&&C.browser.safariVersion<=nO}catch(a){console.error(a)}var _p=class{constructor(e,t=!1){this.bufferFull$=new yw;this.error$=new yw;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:vw.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Tw&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:vw.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:aO(t)}}},Iw=_p;var Ss=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as wi,assertNonNullable as He,ErrorCategory as Yt,fromEvent as Op,getExponentialDelay as Np,isHigher as oO,isNonNullable as xi,isNullable as be,now as Cu,once as uO,Subject as lO,Subscription as cO,ValueSubject as lr}from"@vkontakte/videoplayer-shared/es2018";var pn=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new lr(0);this.currentLowLatencySegmentLength$=new lr(0);this.currentSegmentLength$=new lr(0);this.onLastSegment$=new lr(!1);this.fullyBuffered$=new lr(!1);this.playingRepresentation$=new lr(void 0);this.playingRepresentationInit$=new lr(void 0);this.error$=new lO;this.gaps=[];this.subscription=new cO;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Q;this.switchAbortController=new Q;this.destroyAbortController=new Q;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=wi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);He(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Iw(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(Op(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Yt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Yt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Op(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Yt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!F(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ss(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).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),s=this.parsedInitData.get(t.id);He(i,"No init buffer for starting representation"),He(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=wi(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(be(s)||be(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),He(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();xi(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=wi(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(be(s)||be(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),He(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();xi(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=wi(this.destroyAbortController.signal,async function*(e){var u;let t=(0,_u.default)(e,l=>l.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let l of this.representations.keys()){let d=t.find(h=>h.id===l);d&&this.representations.set(l,d);let c=this.representations.get(l);if(!c||!rt(c.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);He(r,`Representation not found by id ${i}`);let s=this.segments.get(i);He(s,"No segments for starting representation");let n=this.initData.get(i);if(He(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Q,wi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);He(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(be(o)||be(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),He(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!F(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();xi(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(){!be(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 Q,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var p;if(be(e)||be(this.downloadingRepresentationId)||be(this.playingRepresentationId)||be(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||xi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(He(t,`No such representation ${this.downloadingRepresentationId}`),He(i,`No such representation ${this.playingRepresentationId}`),be(r)||be(s))return;let n=r.find(h=>e>=h.time.from&&e<h.time.to);xi(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=this.getForwardBufferDuration(e),f=Ti(i),m=Ti(t),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&xi(f)&&xi(m)&&oO(f.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(g||b?o+=Math.min(h,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(p=[...this.segments.entries()].map(([y,E])=>{let P=E.find($=>e>=$.time.from&&e<$.time.to);return{representationId:y,status:P==null?void 0:P.status}}).find(y=>y.status==="fed"))==null?void 0:p.representationId;T&&(this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Ss(this.sourceBuffer.buffered)>=this.bufferLimit){let h=this.getForwardBufferDuration(e),f=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<f).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Vu.default)(d,n))h="high";else{let f=(0,cr.default)(d,0);f&&f.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(d,t,h).catch(f=>{this.handleAsyncError(f,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.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 s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;xi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,_u.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,s;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,_u.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!rt(n.segmentReference))return;let o=n.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),u=100,l=(i=this.segments.get(n.id))!=null?i:[],d=(s=(r=(0,cr.default)(l,-1))==null?void 0:r.time.to)!=null?s:0,c=o==null?void 0:o.findIndex(p=>d>=p.time.from+u&&d<=p.time.to+u);if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(c+1);this.segments.set(n.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;He(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,cr.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!rt(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),d=it(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&<&<(this.gapDetectionIdleCallback),this.initLoadIdleCallback&<&<(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:p,time:{from:h,to:f}},m)=>{let g=h<=i&&f>=i,b=h>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(p==="none"||p==="partially_ejected"&&b&&T&&this.sourceBuffer&&F(this.mediaSource,this.sourceBuffer)&&!(Ve(this.sourceBuffer.buffered,h)&&Ve(this.sourceBuffer.buffered,f)))&&b&&T});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=d||u<=c);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){rt(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:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await wi(o,async function*(){let d=Np(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Cu(),!d)return;let c=new DataView(d),p=ct(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ce(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())rt(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:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await wi(n,async function*(){let u=Np(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Op(window,"online").pipe(uO()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Cu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ce(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(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:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Cu(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Yt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Cu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Yt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Vu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!F(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(s.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),d=ct(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!F(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(s.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<r,f=c<=r;if(!h)continue;let m=ct(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===p?g:m.parseFeedableSegmentChunk(g);b!=null&&b.byteLength&&(l.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(be(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer))){!this.isLive&&C.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ve(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ve(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Yt.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",kp(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Dt(()=>(0,Ew.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?wi(this.destroyAbortController.signal,async function*(){let u=Np(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ct(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async u=>{if(!u)return;let{init:l,dataView:d,segments:c}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=c;this.isLive&&rt(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=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Yt.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||!F(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||be(e))return!1;let r=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=kp(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)(0,Vu.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!F(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||!F(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||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||be(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let o=s.start(n)*1e3,u=s.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Dt(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:Yt.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(be(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||be(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Yt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as hn,assertNever as ww,fromEvent as xw,merge as dO,now as fn,Subject as vs,ValueSubject as Fp,flattenObject as ys,ErrorCategory as mn,SubscriptionRemovable as pO}from"@vkontakte/videoplayer-shared/es2018";var Nu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new vs;this.firstBytesManifest$=new vs;this.firstBytesRequested$=new vs;this.firstBytesReceived$=new vs;this.lastConnectionType$=new Fp(void 0);this.lastConnectionReused$=new Fp(void 0);this.lastRequestFirstBytes$=new Fp(void 0);this.recoverableError$=new vs;this.error$=new vs;this.abortAllController=new Q;this.subscription=new pO;this.fetchManifest=hn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ss(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ou);return r?(t.log("success",ys({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",ys({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=hn(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1,ignoreNetworkErrors:d=!1}={}){var z,W,I;let c=e,p=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let w=new URL(c,location.href);w.searchParams.append("bytes",`${i.from}-${i.to}`),c=w.toString();break}default:ww(t)}this.requestQuic&&(c=Tt(c));let f=this.abortAllController.signal,m;if(n){let w=new Q;if(m=dO(xw(this.abortAllController.signal,"abort"),xw(n,"abort")).subscribe(()=>{try{w.abort()}catch(x){Ou(x)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{w.abort()}catch(x){Ou(x)}f=w.signal}let g=0,b=fn();h.log("startRequest",ys({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:b})),this.firstBytesRequested$.next();let v=yield this.doFetch(c,{priority:s,headers:p,signal:f},{ignoreNetworkErrors:d}),T=fn();if(!v)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(m),null;if((z=this.throughputEstimator)==null||z.addRawRtt(T-b),!v.ok||!v.body){this.unsubscribeAbortSubscription(m);let w=`Fetch error ${v.status}: ${v.statusText}`;return h.error("error",{message:w}),h.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!o){this.unsubscribeAbortSubscription(m);let w=fn(),x={requestStartedAt:b,requestEndedAt:w,duration:w-b};return h.log("endRequest",ys(x)),h.end(),v.arrayBuffer()}let y=v.body;if(o){let w;[y,w]=v.body.tee(),(W=this.throughputEstimator)==null||W.trackStream(w,u)}let E=y.getReader(),P,$=parseInt((I=v.headers.get("content-length"))!=null?I:"",10);Number.isFinite($)&&(P=$),!P&&i&&(P=i.to-i.from+1);let A=P?new Uint8Array(P):new Uint8Array(0),L=!1,M=w=>{this.unsubscribeAbortSubscription(m),L=!0,Ou(w)},B=hn(f,async function*({done:w,value:x}){if(g===0&&(this.lastRequestFirstBytes$.next(fn()-b),this.firstBytesReceived$.next()),f.aborted){this.unsubscribeAbortSubscription(m);return}if(!w&&x){if(l&&P)A.set(x,g),g+=x.byteLength;else{let k=new Uint8Array(A.length+x.length);k.set(A),k.set(x,A.length),A=k,g+=x.byteLength}r==null||r(new DataView(A.buffer),g),yield E==null?void 0:E.read().then(B,M)}}.bind(this));yield E==null?void 0:E.read().then(B,M),this.unsubscribeAbortSubscription(m);let D=fn(),N={failed:L,requestStartedAt:b,requestEndedAt:D,duration:D-b};return L?(h.error("endRequest",ys(N)),h.end(),null):(h.log("endRequest",ys(N)),h.end(),A.buffer)}.bind(this));this.fetchByteRangeRepresentation=hn(this.abortAllController.signal,async function*(e,t,i){var b;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),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 p=new DataView(c,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(b=e.indexRange)!=null?b:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=hn(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=s}onHeadersReceived(e){let{type:t,reused:i}=rs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:ww(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await Xe(e,t);if(r.ok)return r;if(i!=null&&i.ignoreNetworkErrors)return;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:mn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:mn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:mn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:mn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:mn.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Ou=a=>{if(!Ce(a))throw a};import{isNullable as hO,ValueSubject as Pw}from"@vkontakte/videoplayer-shared/es2018";var Pi=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Pw(e.initial),this.debounced$=new Pw(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ue(`raw_${t}`),this.smoothedSeries$=new Ue(`smoothed_${t}`),this.reportedSeries$=new Ue(`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),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(hO(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 Fu=class extends Pi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ht(this.slow,e,this.params.emaAlphaSlow),this.fast=Ht(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Uu=class extends Pi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Yd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ht(this.emaSmoothed,e,this.params.emaAlpha);let i=ZT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var qu=class extends Pi{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?Ht(this.smoothed,t,this.params.emaAlpha):t}};var Kt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Fu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Uu({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 qu({initial:e,label:"liveEdgeDelay",...t})}};var Ts=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as fO,ValueSubject as mO}from"@vkontakte/videoplayer-shared/es2018";var bn=class a{constructor(e,t){this.currentRepresentation$=new mO(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!fO(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var TO=["timeupdate","progress","play","seeked","stalled","waiting"],IO=["timeupdate","progress","loadeddata","playing","seeked"];var Hu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Aw;this.subscriptionRemovable=new SO;this.representationSubscription=new Aw;this.state$=new j("none");this.currentVideoRepresentation$=new se(void 0);this.currentVideoRepresentationInit$=new se(void 0);this.currentAudioRepresentation$=new se(void 0);this.currentVideoSegmentLength$=new se(0);this.currentAudioSegmentLength$=new se(0);this.error$=new Jt;this.manifestRequested$=new Jt;this.firstBytesManifest$=new Jt;this.manifestReceived$=new Jt;this.firstBytesRequested$=new Jt;this.firstBytesReceived$=new Jt;this.lastConnectionType$=new se(void 0);this.lastConnectionReused$=new se(void 0);this.lastRequestFirstBytes$=new se(void 0);this.currentLiveTextRepresentation$=new se(null);this.isLive$=new se(!1);this.isActiveLive$=new se(!1);this.isLowLatency$=new se(!1);this.liveDuration$=new se(0);this.liveSeekableDuration$=new se(0);this.liveAvailabilityStartTime$=new se(0);this.liveStreamStatus$=new se(void 0);this.bufferLength$=new se(0);this.liveLatency$=new se(void 0);this.liveLoadBufferLength$=new se(0);this.livePositionFromPlayer$=new se(0);this.currentStallDuration$=new se(0);this.videoLastDataObtainedTimestamp$=new se(0);this.fetcherRecoverableError$=new Jt;this.fetcherError$=new Jt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Jt;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new Q;this.initManifest=Up(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:dt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Up(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:dt.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=ls(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(d){let c=(u=is(e))!=null?u:{id:"ManifestParsing",category:dt.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(c)}if(!t)return null;let i=(d,c,p)=>{var h,f,m,g;return!!((f=(h=this.element)==null?void 0:h.canPlayType)!=null&&f.call(h,c)&&((g=(m=Oe())==null?void 0:m.isTypeSupported)!=null&&g.call(m,`${c}; codecs="${p}"`))||d==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:d,latestSegmentPublishTime:c,streamIsUnpublished:p,streamIsAlive:h}=t.live,f=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((c-d)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";if(h||(m=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m),h&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let g=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(g).catch(b=>{this.error$.next({id:"updateManifest",category:dt.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:b})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let d of["video","audio"]){let p=t.streams[d].filter(({mime:f,codecs:m})=>i(d,f,m));r[d]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let f=p.map(({codecs:m})=>m);d==="audio"&&(n=ps(f),h=n[0]),d==="video"&&(s=ds(f),this.forceVideoCodec&&(0,$w.default)(s,this.forceVideoCodec)?h=this.forceVideoCodec:h=s[0]),h&&(r[d]=p.filter(({codecs:m})=>vi(m)===h))}else{let f=new Set(p.map(({codecs:m})=>m));h=cs(f),h&&(r[d]=p.filter(({codecs:m})=>m.startsWith(h)))}if(d==="video"){let f=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),g=r.video.some(b=>!b.hdr);C.display.isHDR&&f&&m?r.video=r.video.filter(b=>b.hdr):g&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Sn(o)),o}.bind(this));this.initRepresentations=Up(this.destroyController.signal,async function*(e,t,i){var c;this.tracer.log("initRepresentationsStart",Sn({initialVideo:e,initialAudio:t,sourceHls:i})),Is(this.manifest),Is(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Xt(p,"error").pipe(ju(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Br();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),di())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new pn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],vn(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new pn("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(bn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new bn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(dr(...IO.map(p=>Xt(this.element,p))).pipe(ws(p=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),gn(),vO(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(dr(Xt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(gn()).subscribe(h=>this.liveStreamEndTimestamp=jp())),this.subscription.add(Xt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:h}=this.tuning.dash;this.livePauseWatchdogSubscription=qp(h).subscribe(f=>{let m=ci(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+h,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Xt(this.element,"play").subscribe(h=>{var f;return(f=this.livePauseWatchdogSubscription)==null?void 0:f.unsubscribe()})),this.representationSubscription.add(Es({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ws(({isActiveLive:h,isLowLatency:f})=>h&&f),gn()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Ts(this.element,1)})),this.representationSubscription.add(Es({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ju(({bufferLength:h,isActiveLive:f,isLowLatency:m})=>f&&m&&!!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 f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Es({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ju(({isLive:h})=>h),gn((h,f)=>f.bufferLength<h.bufferLength),ws(({rtt:h,bufferLength:f,segmentServerLatency:m})=>{let g=ci(this.manifestUrlString,2);return(h/2+f+m+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Es({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:m})=>{if(!m||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-g;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>b&&(y=1+Math.sign(T)*v),Ts(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var m,g;let f=0;if(h){let b=((g=(m=this.element)==null?void 0:m.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(T=>{var y,E;return(E=(y=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?E:b}))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Es({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(yO(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,g=ci(this.manifestUrlString,2),b=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(b,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,E=isFinite(h)?h:f,P=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=b<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let A="none";if(P?A="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(L=>L.proceedLowLatencyLive()),A="active_low_latency"):g!==0&&E<v?A="live_forward_buffering":E<v+y&&(A="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),A==="live_forward_buffering"||A==="live_with_target_offset"){let L=p-(v+T),M=this.normalizeLiveOffset(Math.trunc(g+L/m)),B=Math.abs(M-g),D=0;!h||B<=this.tuning.dashCmafLive.offsetCalculationError?D=g:M>0&&B>this.tuning.dashCmafLive.offsetCalculationError&&(D=M),this.manifestUrlString=le(this.manifestUrlString,D,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:dt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let u=dr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ws(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=dr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ws(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Es({allBuffersFull:u,someBufferEnded:l}).pipe(gn(),ws(({allBuffersFull:p,someBufferEnded:h})=>p&&h),ju(p=>p));if(this.representationSubscription.add(dr(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(dr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var f;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var m;if(((m=this.source)==null?void 0:m.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(f=this.source)==null||f.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(c=this.manifest.duration)!=null?c:0,...(0,Hp.default)((0,Hp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),rt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&vn(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=qp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:dt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Nu({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=Kt.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){Is(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"?jp()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){var t,i,r;await((t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio)),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){Is(this.element),this.state$.setState("running"),this.subscription.add(dr(...TO.map(e=>Xt(this.element,e)),Xt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Xt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Xt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Ve(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var y,E,P,$,A,L,M,B,D,N,z;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||((y=this.source)==null?void 0:y.readyState)!=="open")return;let d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let c={timeInWaiting:d},p=jp(),h=100,f=(P=(E=this.videoBufferManager)==null?void 0:E.lastDataObtainedTimestamp)!=null?P:0;this.videoLastDataObtainedTimestamp$.next(f);let m=(A=($=this.audioBufferManager)==null?void 0:$.lastDataObtainedTimestamp)!=null?A:0,g=(M=(L=this.videoBufferManager)==null?void 0:L.getForwardBufferDuration())!=null?M:0,b=(D=(B=this.audioBufferManager)==null?void 0:B.getForwardBufferDuration())!=null?D:0,v=g<h&&p-f>r,T=this.audioBufferManager&&b<h&&p-m>r;if((!t||l)&&((v||T)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%s===0){let W=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(W),this.updateManifest()):this.seekLive(W).catch(I=>{this.error$.next({id:"stallIntervalCallback",category:dt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:I})}),c.liveLastOffset=W}else{let W=this.element.currentTime*1e3;(N=this.videoBufferManager)==null||N.maintain(W),(z=this.audioBufferManager)==null||z.maintain(W),c.position=W}this.tracer.log("stallIntervalCallback",Sn(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=qp(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:dt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;Is(this.element),Is(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ve(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(kw(this.element)||kw(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Sn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;vn(this.element)&&vn(this.source)&&vn(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=gO(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=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<=s&&l.to+o>s&&(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",Sn(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};import{combine as EO,map as wO,observeElementSize as xO,Subscription as PO,ValueSubject as Wp,noop as kO}from"@vkontakte/videoplayer-shared/es2018";var Wu=class{constructor(){this.subscription=new PO;this.pipSize$=new Wp(void 0);this.videoSize$=new Wp(void 0);this.elementSize$=new Wp(void 0);this.pictureInPictureWindowRemoveEventListener=kO}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(xO(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(EO({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(wO(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var pr=class{constructor(e){this.subscription=new CO;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new mi;this.stallsManager=new es;this.elementSizeManager=new Wu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(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"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return RO(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new gi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ge(e.source.url),this.params=e,this.video=$e(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(fe(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 Hu({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;BO(this.observableVideo)&&(this.observableVideo=De(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Mw.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(zp(c=>!!c.length),Dw()).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(Tn(c=>c.to.state!=="none"),yn());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(zp(Lw),Dw()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Tn(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(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Si({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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"),R(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 p=this.player.getStreams(),h=this.player.getCodecs();if($O(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of p.audio){m.push(xp(g));let b=[];for(let v of g.representations){let T=sn(v);b.push(T),this.audioTracksMap.set(T,{stream:g,representation:v})}this.audioStreamsMap.set(g,b)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of p.video){f.push(Pp(m));let g=[];for(let b of m.representations){let v=Ti({...b,streamId:m.id});v&&(g.push(v),this.videoTracksMap.set(v,{stream:m,representation:b}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(f);for(let m of p.text)for(let g of m.representations){let b=iw(m,g);this.textTracksMap.set(b,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=In(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$,DO(this.video,"progress")).pipe(zp(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(VO(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[f,m]=h,g=[...this.videoTracksMap.keys()].find(v=>{var T;return((T=this.videoTracksMap.get(v))==null?void 0:T.representation.id)===f.id});Lw(g)&&(this.stallsManager.lastVideoTrackSelected=g);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")await this.player.initRepresentations(f.id,m==null?void 0:m.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),m){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add(MO({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:In(zu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Tn(c=>c.to)))}).pipe(Tn(({videoState:c,autoVideoTrackState:p})=>c.to!=="stopped"&&p),yn()).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(yn()).subscribe(c=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=p,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Pp(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(yn()).subscribe(c=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=p,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(xp(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Tn(({to:c})=>c==="ready"),yn());this.subscription.add(In(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,zu(["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(In(l,this.player.state$.stateChangeEnded$,zu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=In(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zu(["init"])).pipe(LO(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var A,L,M,B,D,N,z,W,I,w,x,k,_;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ir:tr,t=this.params.tuning.useNewAutoSelectVideoTrack?Jr:Xr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Kr,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(A=r.videoTrack.getState())==null?void 0:A.id,u=[...this.videoTracksMap.keys()].find(({id:U})=>U===o),l=s.currentVideoTrack$.getValue(),d=((B=(M=r.videoStream.getState())!=null?M:u&&((L=this.videoTracksMap.get(u))==null?void 0:L.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=[...this.videoStreamsMap.keys()].find(({id:U})=>U===d.id),p=c&&this.videoStreamsMap.get(c);if(!p)return;let h=me(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(h/Math.min(f,m||1/0),1),b=(D=r.audioStream.getState())!=null?D:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(N=[...this.audioStreamsMap.keys()].find(({id:U})=>U===(b==null?void 0:b.id)))!=null?N:this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let U=e(u,p,(z=this.audioStreamsMap.get(v))!=null?z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(W=U==null?void 0:U.bitrate)!=null?W:-1/0)}if(l){let U=e(l,p,(I=this.audioStreamsMap.get(v))!=null?I:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(w=U==null?void 0:U.bitrate)!=null?w:-1/0)}}let y=u;(n||!y)&&(y=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:g,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 E=v&&t(y,p,(x=this.audioStreamsMap.get(v))!=null?x:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=(k=this.videoTracksMap.get(y))==null?void 0:k.representation,$=E&&((_=this.audioTracksMap.get(E))==null?void 0:_.representation);if(P&&$)return[P,$];if(P&&!$&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Mw.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),Me(this.video),this.tracer.end()}};var En=class extends pr{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)}};import{combine as Qp,merge as Bw,filter as Cw,filterChanged as Vw,isNullable as Gp,map as _w,ValueSubject as Yp,isNonNullable as _O}from"@vkontakte/videoplayer-shared/es2018";var wn=class extends pr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Yp(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(Vw()).subscribe(u=>{let l=i.position$.getValue(),d=i.volume$.getValue(),c=!d.volume||d.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(s.isLowLatency.stateChangeEnded$.pipe(_w(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Qp({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(_w(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u*1e3+l+t:void 0)).subscribe(i.liveTime$)).add(Qp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Bw(r.playbackRateState$,new Yp(1))}).pipe(Cw(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let d=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-p||this.video.paused||Gp(d)||(t=u-d)})).add(Qp({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Bw(r.playbackRateState$,new Yp(1))}).pipe(Vw((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:d})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&d>=1-p||Gp(u)||Gp(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=rw(u);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(Cw(u=>_O(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)})}};import{assertNever as dN,assertNonNullable as pN,combine as hN,debounce as fN,ErrorCategory as ex,filter as dh,filterChanged as Bn,fromEvent as mN,isNonNullable as tx,isNullable as bN,map as Cn,merge as Vn,observableFrom as rl,once as ix,Subscription as gN}from"@vkontakte/videoplayer-shared/es2018";var Zw=O(Re(),1),lh=O(rr(),1);import{abortable as ah,assertNonNullable as ks,combine as As,ErrorCategory as Et,filter as el,filterChanged as Mn,flattenObject as Ln,fromEvent as Ct,getTraceSubscriptionMethod as eN,interval as nh,isNonNullable as Dn,isNullable as Xw,map as Rs,merge as gr,now as oh,Subject as Zt,Subscription as uh,SubscriptionRemovable as tN,tap as iN,throttle as Jw,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var Ku=O(Re(),1),br=O(Ye(),1),Xu=O(rr(),1);var Qw=O(Yo(),1);import{assertNever as OO,ErrorCategory as Ow,Subject as Nw}from"@vkontakte/videoplayer-shared/es2018";var NO=18,Fw=!1;try{Fw=C.browser.isSafari&&!!C.browser.safariVersion&&C.browser.safariVersion<=NO}catch(a){console.error(a)}var Kp=class{constructor(e,t=!1){this.bufferFull$=new Nw;this.error$=new Nw;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Ow.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Fw&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ow.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:OO(t)}}},Uw=Kp;import{abortable as ki,assertNonNullable as We,ErrorCategory as fr,fromEvent as th,getExponentialDelay as ih,isHigher as HO,isNonNullable as Ai,isNullable as ge,now as Yu,once as WO,Subject as zO,Subscription as QO,ValueSubject as mr}from"@vkontakte/videoplayer-shared/es2018";var Xp=O(Ye(),1);import{videoSizeToQuality as FO,throttleFn as UO}from"@vkontakte/videoplayer-shared/es2018";var xn=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Lt(s):void 0)!=null?u:FO({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},qw=({id:a,bitrate:e})=>({id:a,bitrate:e}),jw=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Hw=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Jp=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Xp.default)(i.split("."),0),isDefault:r}),Zp=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Xp.default)(r.split("."),0)}),eh=a=>"url"in a,st=a=>a.type==="template";var Ww=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},hr=(a,e)=>{for(let t of a)if(e(t))return t;return null},zw=a=>{let e=!1,t=UO(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as qO,Subscription as jO}from"@vkontakte/videoplayer-shared/es2018";var Qu=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var Gu=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new jO;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(qO(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!F(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Qu(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],s=e[i+1],n=t[i],o=t[i+1];if(n>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Pn=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new mr(0);this.currentLowLatencySegmentLength$=new mr(0);this.currentSegmentLength$=new mr(0);this.onLastSegment$=new mr(!1);this.fullyBuffered$=new mr(!1);this.playingRepresentation$=new mr(void 0);this.playingRepresentationInit$=new mr(void 0);this.error$=new zO;this.gaps=[];this.subscription=new QO;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Q;this.switchAbortController=new Q;this.destroyAbortController=new Q;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=ki(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);We(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Uw(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.sourceBufferBufferedDiff=new Gu(this.mediaSource,this.sourceBuffer),this.subscription.add(th(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(th(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:fr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!F(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ss(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=me(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).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),s=this.parsedInitData.get(t.id);We(i,"No init buffer for starting representation"),We(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=ki(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);We(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ge(s)||ge(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),We(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Ai(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=ki(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);We(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ge(s)||ge(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),We(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Ai(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=ki(this.destroyAbortController.signal,async function*(e){var u;let t=(0,Xu.default)(e,l=>l.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let l of this.representations.keys()){let d=t.find(h=>h.id===l);d&&this.representations.set(l,d);let c=this.representations.get(l);if(!c||!st(c.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);We(r,`Representation not found by id ${i}`);let s=this.segments.get(i);We(s,"No segments for starting representation");let n=this.initData.get(i);if(We(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Q,ki(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);We(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ge(o)||ge(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),We(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!F(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();Ai(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(){!ge(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 Q,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var p;if(ge(e)||ge(this.downloadingRepresentationId)||ge(this.playingRepresentationId)||ge(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||Ai(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(We(t,`No such representation ${this.downloadingRepresentationId}`),We(i,`No such representation ${this.playingRepresentationId}`),ge(r)||ge(s))return;let n=r.find(h=>e>=h.time.from&&e<h.time.to);Ai(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=this.getForwardBufferDuration(e),f=xn(i),m=xn(t),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Ai(f)&&Ai(m)&&HO(f.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(g||b?o+=Math.min(h,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(p=[...this.segments.entries()].map(([y,E])=>{let P=E.find($=>e>=$.time.from&&e<$.time.to);return{representationId:y,status:P==null?void 0:P.status}}).find(y=>y.status==="fed"))==null?void 0:p.representationId;T&&(this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Ss(this.sourceBuffer.buffered)>=this.bufferLimit){let h=me(this.sourceBuffer.buffered,e),f=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<f).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let d=null;if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d!=null&&d.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Ku.default)(d,n))h="high";else{let f=(0,br.default)(d,0);f&&f.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(d,t,h).catch(f=>{this.handleAsyncError(f,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!(d!=null&&d.length)&&me(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,br.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-me(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 s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Ai(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,Xu.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,s,n;if(!e||[...this.segments.values()].every(o=>!o.length))return;let t=(i=(0,Xu.default)(e.streams[this.kind],o=>o.representations))!=null?i:[];for(let o of t){if(!o||!st(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(s=(0,br.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>c>=h.time.from+l&&c<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...d,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;We(e);let t=this.segments.get(e);if(t!=null&&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(!st(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.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),!!!s.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});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&<&<(this.gapDetectionIdleCallback),this.initLoadIdleCallback&<&<(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:p,time:{from:h,to:f}},m)=>{let g=h<=i&&f>=i,b=h>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(p==="none"||p==="partially_ejected"&&b&&T&&this.sourceBuffer&&F(this.mediaSource,this.sourceBuffer)&&!(Ve(this.sourceBuffer.buffered,h)&&Ve(this.sourceBuffer.buffered,f)))&&b&&T});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=d||u<=c);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){st(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:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ki(o,async function*(){let d=ih(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Yu(),!d)return;let c=new DataView(d),p=ct(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ce(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())st(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:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ki(n,async function*(){let u=ih(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),th(window,"online").pipe(WO()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Yu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ce(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(st(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,br.default)(e,0).byte.from,to:(0,br.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Yu(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:fr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!st(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Yu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:fr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Ku.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!F(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(s.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),d=ct(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!F(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(s.aborted){await n();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<r,f=c<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(m,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?m:ct(o.mime).parseFeedableSegmentChunk(m);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(ge(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer))){!this.isLive&&C.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ve(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ve(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:fr.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",eh(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 s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.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,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Dt(()=>(0,Qw.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?ki(this.destroyAbortController.signal,async function*(){let o=ih(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ct(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&st(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),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:fr.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||!F(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ge(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{var l;if(s>=t)return;r.push({...o.time});let u=eh(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&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,d=0;for(let c of this.segments.values())for(let p of c)(0,Ku.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(u)&&Math.round(p.time.to)>=Math.round(l)&&d++;if(d===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=Ww(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||!F(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||!F(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||!F(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||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ge(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!F(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 s=0;s<i.length;s++){let n=i.start(s)*1e3,o=i.end(s)*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(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let s=Math.round(r.from),n=Math.round(r.to);for(let o=0;o<i.length;o++)if(s>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Dt(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:fr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ge(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||ge(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Qu(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],p=e[d+1];u||(u=c-t<=n&&p+t>=o),(n>=c&&n<p-t||o>c+t&&o<=p)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:fr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,br.default)(e,-1))==null?void 0:t.time.to:0)||0}};import{abortable as kn,assertNever as Gw,fromEvent as Yw,merge as GO,now as An,Subject as xs,ValueSubject as rh,flattenObject as Ps,ErrorCategory as Rn,SubscriptionRemovable as YO}from"@vkontakte/videoplayer-shared/es2018";var Zu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new xs;this.firstBytesManifest$=new xs;this.firstBytesRequested$=new xs;this.firstBytesReceived$=new xs;this.lastConnectionType$=new rh(void 0);this.lastConnectionReused$=new rh(void 0);this.lastRequestFirstBytes$=new rh(void 0);this.recoverableError$=new xs;this.error$=new xs;this.abortAllController=new Q;this.subscription=new YO;this.fetchManifest=kn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ss(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ju);return r?(t.log("success",Ps({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",Ps({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=kn(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var N,z,W;let d=e,c=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(d,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),d=I.toString();break}default:Gw(t)}this.requestQuic&&(d=Tt(d));let h=this.abortAllController.signal,f;if(n){let I=new Q;if(f=GO(Yw(this.abortAllController.signal,"abort"),Yw(n,"abort")).subscribe(()=>{try{I.abort()}catch(w){Ju(w)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(w){Ju(w)}h=I.signal}let m=0,g=An();p.log("startRequest",Ps({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested$.next();let b=yield this.doFetch(d,{priority:s,headers:c,signal:h}),v=An();if(!b)return p.error("error",{message:"No response in request"}),p.end(),this.unsubscribeAbortSubscription(f),null;if((N=this.throughputEstimator)==null||N.addRawRtt(v-g),!b.ok||!b.body){this.unsubscribeAbortSubscription(f);let I=`Fetch error ${b.status}: ${b.statusText}`;return p.error("error",{message:I}),p.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let I=An(),w={requestStartedAt:g,requestEndedAt:I,duration:I-g};return p.log("endRequest",Ps(w)),p.end(),b.arrayBuffer()}let T=b.body;if(o){let I;[T,I]=b.body.tee(),(z=this.throughputEstimator)==null||z.trackStream(I,u)}let y=T.getReader(),E,P=parseInt((W=b.headers.get("content-length"))!=null?W:"",10);Number.isFinite(P)&&(E=P),!E&&i&&(E=i.to-i.from+1);let $=E?new Uint8Array(E):new Uint8Array(0),A=!1,L=I=>{this.unsubscribeAbortSubscription(f),A=!0,Ju(I)},M=kn(h,async function*({done:I,value:w}){if(m===0&&(this.lastRequestFirstBytes$.next(An()-g),this.firstBytesReceived$.next()),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!I&&w){if(l&&E)$.set(w,m),m+=w.byteLength;else{let x=new Uint8Array($.length+w.length);x.set($),x.set(w,$.length),$=x,m+=w.byteLength}r==null||r(new DataView($.buffer),m),yield y==null?void 0:y.read().then(M,L)}}.bind(this));yield y==null?void 0:y.read().then(M,L),this.unsubscribeAbortSubscription(f);let B=An(),D={failed:A,requestStartedAt:g,requestEndedAt:B,duration:B-g};return A?(p.error("endRequest",Ps(D)),p.end(),null):(p.log("endRequest",Ps(D)),p.end(),$.buffer)}.bind(this));this.fetchByteRangeRepresentation=kn(this.abortAllController.signal,async function*(e,t,i){var b;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),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 p=new DataView(c,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(b=e.indexRange)!=null?b:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=kn(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=s}onHeadersReceived(e){let{type:t,reused:i}=rs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:Gw(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Xe(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Rn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Rn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Rn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Rn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Rn.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Ju=a=>{if(!Ce(a))throw a};import{isNullable as KO,ValueSubject as XO}from"@vkontakte/videoplayer-shared/es2018";var $n=class a{constructor(e,t){this.currentRepresentation$=new XO(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!KO(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&st(t.segmentReference))}};var rN=["progress","play","seeked","stalled","waiting"],sN=["timeupdate","progress","loadeddata","playing","seeked"];var tl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new uh;this.subscriptionRemovable=new tN;this.representationSubscription=new uh;this.state$=new j("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new Zt;this.manifestRequested$=new Zt;this.firstBytesManifest$=new Zt;this.manifestReceived$=new Zt;this.firstBytesRequested$=new Zt;this.firstBytesReceived$=new Zt;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.currentLiveTextRepresentation$=new ae(null);this.isLive$=new ae(!1);this.isActiveLive$=new ae(!1);this.isLowLatency$=new ae(!1);this.liveDuration$=new ae(0);this.liveSeekableDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(0);this.liveStreamStatus$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLatency$=new ae(void 0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.currentStallDuration$=new ae(0);this.videoLastDataObtainedTimestamp$=new ae(0);this.fetcherRecoverableError$=new Zt;this.fetcherError$=new Zt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Zt;this.gapWatchdogActive=!1;this.destroyController=new Q;this.initManifest=ah(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Et.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=ah(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Et.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=ls(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(d){let c=(u=is(e))!=null?u:{id:"ManifestParsing",category:Et.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(c)}if(!t)return null;let i=(d,c,p)=>{var h,f,m,g;return!!((f=(h=this.element)==null?void 0:h.canPlayType)!=null&&f.call(h,c)&&((g=(m=Oe())==null?void 0:m.isTypeSupported)!=null&&g.call(m,`${c}; codecs="${p}"`))||d==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:d,latestSegmentPublishTime:c,streamIsUnpublished:p,streamIsAlive:h}=t.live,f=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((c-d)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";h||(m=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let d of["video","audio"]){let p=t.streams[d].filter(({mime:f,codecs:m})=>i(d,f,m));r[d]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let f=p.map(({codecs:m})=>m);d==="audio"&&(n=ps(f),h=n[0]),d==="video"&&(s=ds(f),this.forceVideoCodec&&(0,Zw.default)(s,this.forceVideoCodec)?h=this.forceVideoCodec:h=s[0]),h&&(r[d]=p.filter(({codecs:m})=>vi(m)===h))}else{let f=new Set(p.map(({codecs:m})=>m));h=cs(f),h&&(r[d]=p.filter(({codecs:m})=>m.startsWith(h)))}if(d==="video"){let f=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),g=r.video.some(b=>!b.hdr);C.display.isHDR&&f&&m?r.video=r.video.filter(b=>b.hdr):g&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Ln(o)),o}.bind(this));this.initRepresentations=ah(this.destroyController.signal,async function*(e,t,i){var p;this.tracer.log("initRepresentationsStart",Ln({initialVideo:e,initialAudio:t,sourceHls:i})),ks(this.manifest),ks(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new uh,this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add(Ct(h,"error").pipe(el(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Et.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=Br();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),di())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}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((h,f)=>[...h,...f.representations],[]);if(this.videoBufferManager=new Pn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Dn(t)){let h=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new Pn("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}$n.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new $n(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(gr(...sN.map(h=>Ct(this.element,h))).pipe(Rs(h=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),Mn(),iN(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(gr(Ct(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Mn()).subscribe(f=>this.liveStreamEndTimestamp=oh())),this.subscription.add(Ct(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=nh(1e3).subscribe(f=>{let m=ci(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ct(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(As({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Rs(({isActiveLive:f,isLowLatency:m})=>f&&m),Mn()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||Ts(this.element,1)})),this.representationSubscription.add(As({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(el(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(As({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(el(({isLive:f})=>f),Mn((f,m)=>m.bufferLength<f.bufferLength),Rs(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let b=ci(this.manifestUrlString,2);return(f/2+m+g+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(As({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=f-b;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(y)>v&&(E=1+Math.sign(y)*T),Ts(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,b;let m=0;if(f){let v=((b=(g=this.element)==null?void 0:g.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var E,P;return(P=(E=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?P:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let h=0;this.representationSubscription.add(As({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Jw(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,b=ci(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,P=isFinite(f)?f:m,$=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let L="none";if($?L="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(M=>M.proceedLowLatencyLive()),L="active_low_latency"):b!==0&&P<T?L="live_forward_buffering":P<T+E&&(L="live_with_target_offset"),isFinite(f)&&(h=f>h?f:h),L==="live_forward_buffering"||L==="live_with_target_offset"){let M=h-(T+y),B=this.normolizeLiveOffset(Math.trunc(b+M/g)),D=Math.abs(B-b),N=0;!f||D<=this.tuning.dashCmafLive.offsetCalculationError?N=b:B>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(N=B),this.manifestUrlString=le(this.manifestUrlString,N,2)}(L==="live_with_target_offset"||L==="live_forward_buffering")&&(h=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Et.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=gr(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(Rs(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=gr(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(Rs(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue()))),c=As({allBuffersFull:l,someBufferEnded:d}).pipe(Mn(),Rs(({allBuffersFull:h,someBufferEnded:f})=>h&&f),el(h=>h));if(this.representationSubscription.add(gr(this.forceEnded$,c).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(h=this.source)==null||h.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Et.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(gr(...this.bufferManagers.map(h=>h.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 h=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;h&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:Et.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let h=[(p=this.manifest.duration)!=null?p:0,...(0,lh.default)((0,lh.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),st(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...h)/1e3}this.audioBufferManager&&Dn(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=nh(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Et.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Zu({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=Kt.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){var r,s,n;ks(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?oh()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){ks(this.element),this.state$.setState("running");let e=Ct(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(Jw(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(gr(...rN.map(t=>Ct(this.element,t)),Ct(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Et.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Ct(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(Ct(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ve(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,f,m,g,b,v,T,y,E,P,$;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=oh(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(b=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?b:0,l=(T=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?T:0,d=(E=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?E:0,c=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&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 A=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(A).catch(L=>{this.error$.next({id:"stallIntervalCallback",category:Et.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:L})}),r.liveLastOffset=A}else{let A=this.element.currentTime*1e3;(P=this.videoBufferManager)==null||P.maintain(A),($=this.audioBufferManager)==null||$.maintain(A),r.position=A}this.tracer.log("stallIntervalCallback",Ln(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=nh(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Et.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==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;ks(this.element),ks(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ve(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(Xw(this.element)||Xw(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ln({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Dn(this.element)&&Dn(this.source)&&Dn(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=eN(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(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.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 s=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<=s&&l.to+o>s&&(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",Ln({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};import{combine as aN,map as nN,observeElementSize as oN,Subscription as uN,ValueSubject as ch,noop as lN}from"@vkontakte/videoplayer-shared/es2018";var il=class{constructor(){this.subscription=new uN;this.pipSize$=new ch(void 0);this.videoSize$=new ch(void 0);this.elementSize$=new ch(void 0);this.pictureInPictureWindowRemoveEventListener=lN}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(oN(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(aN({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(nN(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Sr=class{constructor(e){this.subscription=new gN;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new mi;this.stallsManager=new es;this.elementSizeManager=new il;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(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"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return dN(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new gi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ge(e.source.url),this.params=e,this.video=$e(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(fe(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 tl({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;bN(this.observableVideo)&&(this.observableVideo=De(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:ex.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(dh(c=>!!c.length),ix()).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(Cn(c=>c.to.state!=="none"),Bn());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(dh(tx),ix()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Cn(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(ot(this.video,t.isLooped,r)),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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"),R(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 p=this.player.getStreams(),h=this.player.getCodecs();if(pN(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of p.audio){m.push(Jp(g));let b=[];for(let v of g.representations){let T=qw(v);b.push(T),this.audioTracksMap.set(T,{stream:g,representation:v})}this.audioStreamsMap.set(g,b)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of p.video){f.push(Zp(m));let g=[];for(let b of m.representations){let v=xn({...b,streamId:m.id});v&&(g.push(v),this.videoTracksMap.set(v,{stream:m,representation:b}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(f);for(let m of p.text)for(let g of m.representations){let b=jw(m,g);this.textTracksMap.set(b,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&zw(o)||null;this.subscription.add(Vn(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$,mN(this.video,"progress")).pipe(dh(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||p||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let m=hr(this.videoTracksMap.keys(),b=>{var v;return((v=this.videoTracksMap.get(b))==null?void 0:v.representation.id)===h.id});tx(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,b)}},r)),this.subscription.add(hN({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Vn(rl([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Cn(c=>c.to)))}).pipe(Cn(({videoState:c,autoVideoTrackState:p})=>c.to!=="stopped"&&p),Bn()).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(Bn()).subscribe(c=>{let p=hr(this.videoTracksMap.entries(),([,{representation:b}])=>b.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=p,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Zp(f));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Bn()).subscribe(c=>{let p=hr(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=p,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Jp(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Cn(({to:c})=>c==="ready"),Bn());this.subscription.add(Vn(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,rl(["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(Vn(l,this.player.state$.stateChangeEnded$,rl(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Vn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,rl(["init"])).pipe(fN(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var A,L,M,B,D,N,z,W,I,w,x,k;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ir:tr,t=this.params.tuning.useNewAutoSelectVideoTrack?Jr:Xr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Kr,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(A=r.videoTrack.getState())==null?void 0:A.id,u=hr(this.videoTracksMap.keys(),_=>_.id===o),l=s.currentVideoTrack$.getValue(),d=((B=(M=r.videoStream.getState())!=null?M:u&&((L=this.videoTracksMap.get(u))==null?void 0:L.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=hr(this.videoStreamsMap.keys(),_=>_.id===d.id),p=c&&this.videoStreamsMap.get(c);if(!p)return;let h=me(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(h/Math.min(f,m||1/0),1),b=(D=r.audioStream.getState())!=null?D:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(b==null?void 0:b.id)&&hr(this.audioStreamsMap.keys(),_=>_.id===b.id)||this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let _=e(u,p,(N=this.audioStreamsMap.get(v))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(z=_==null?void 0:_.bitrate)!=null?z:-1/0)}if(l){let _=e(l,p,(W=this.audioStreamsMap.get(v))!=null?W:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(I=_==null?void 0:_.bitrate)!=null?I:-1/0)}}let y=u;(n||!y)&&(y=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:g,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 E=v&&t(y,p,(w=this.audioStreamsMap.get(v))!=null?w:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=(x=this.videoTracksMap.get(y))==null?void 0:x.representation,$=E&&((k=this.audioTracksMap.get(E))==null?void 0:k.representation);P&&$?(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=$):P&&!$&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ex.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),Me(this.video),this.tracer.end()}};var _n=class extends Sr{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)}};import{combine as ph,merge as rx,filter as sx,filterChanged as ax,isNullable as hh,map as nx,ValueSubject as fh,isNonNullable as SN}from"@vkontakte/videoplayer-shared/es2018";var On=class extends Sr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new fh(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(ax()).subscribe(u=>{let l=i.position$.getValue(),d=i.volume$.getValue(),c=!d.volume||d.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(s.isLowLatency.stateChangeEnded$.pipe(nx(u=>u.to)).subscribe(this.player.isLowLatency$)).add(ph({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(nx(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(sx(u=>SN(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(ph({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:rx(r.playbackRateState$,new fh(1))}).pipe(sx(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let d=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-p||this.video.paused||hh(d)||(t=u-d)})).add(ph({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:rx(r.playbackRateState$,new fh(1))}).pipe(ax((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:d})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&d>=1-p||hh(u)||hh(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=Hw(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 ox="X-Playback-Duration",mh=async a=>{var r;let e=await Xe(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(ox)?parseInt(e.headers.get(ox),10):void 0};import{assertNever as RN,combine as $N,debounce as MN,ErrorCategory as nl,filter as LN,filterChanged as DN,isNonNullable as cx,isNullable as ol,map as dx,merge as BN,observableFrom as CN,Subscription as VN,ValueSubject as Sh,VideoQuality as _N}from"@vkontakte/videoplayer-shared/es2018";var gh=O(Uc(),1);import{videoSizeToQuality as vN,getExponentialDelay as yN}from"@vkontakte/videoplayer-shared/es2018";var TN=a=>{let e=null;if(a.QUALITY&&(e=Lt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=vN({width:t,height:i})}return e!=null?e:null},IN=(a,e)=>{var s,n;let t=a.split(`
|
|
179
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,
|
|
180
|
-
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-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),s=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(wN(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 Q;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:AN.WTF,thrown:t,message:e})}};var Nn=class{constructor(e){this.subscription=new VN;this.videoState=new j("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Sh([]);this.liveOffset=new Ji;this.manifestStartTime$=new Sh(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return RN(t)}};var i;this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_N.INVARIANT,url:this.params.source.url};let t=(r,s)=>sl(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new al(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ge(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:nl.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:nl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Sh((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:nl.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=De(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(DN(),dx(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&cx(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(fe(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add($N({startTime:this.manifestStartTime$.pipe(LN(cx)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(dx(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=BN(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,CN(["init"])).pipe(MN(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Me(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(ol(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[p,h]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(p||""));h&&p&&r.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=le(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),mh(n).then(d=>{var c;if(!ol(d))this.maxSeekBackTime$.next(d);else{let p=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(ol(p)||!isFinite(p))&&Xe(n).then(h=>h.text()).then(h=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:m[1];if(f){let g=new URL(f,n).toString();mh(g).then(b=>{ol(b)||this.maxSeekBackTime$.next(b)})}}).catch(()=>{})}})}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:nl.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=le(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as ON,debounce as NN,ErrorCategory as vh,fromEvent as yh,isNonNullable as FN,isNullable as UN,map as px,merge as hx,observableFrom as fx,Subscription as qN,ValueSubject as mx,VideoQuality as jN}from"@vkontakte/videoplayer-shared/es2018";var Fn=class{constructor(e){this.subscription=new qN;this.videoState=new j("stopped");this.manifests$=new mx([]);this.unmuteAfterBrowserResetsHappened=new mx(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);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==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return ON(t)}};this.textTracksManager=new Ge(e.source.url),this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:jN.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(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),sl(le(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:vh.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:vh.WTF,message:"HlsProvider internal logic error",thrown:o})},r=De(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(px(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,r.playbackRateState$,i)),Si({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&FN(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(fe(m.url)))}let c=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(c!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(px(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!C.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(hx(yh(o,"addtrack"),yh(o,"removetrack"),yh(o,"change"),fx(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=hx(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,fx(["init"])).pipe(NN(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Me(this.video)}prepare(){var s,n;let e=this.selectManifest();if(UN(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vh.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Sx=O(pi(),1),Th=O(ji(),1),vx=O(Ye(),1);import{assertNever as HN,assertNonNullable as bx,debounce as WN,ErrorCategory as gx,isHigherOrEqual as zN,isLowerOrEqual as QN,isNonNullable as GN,merge as YN,observableFrom as KN,Subscription as XN,map as JN}from"@vkontakte/videoplayer-shared/es2018";var Un=class{constructor(e){this.subscription=new XN;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new Ge;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"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?R(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return HN(e)}};this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Sx.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Th.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:gx.WTF,message:"MpegProvider internal logic error",thrown:o})},r=De(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(JN(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),Si({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&GN(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=YN(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,KN(["init"])).pipe(WN(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),Me(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;bx(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];bx(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Tt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(fe(t))}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gx.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let p=ut(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(p)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,Th.default)(this.trackUrls).map(c=>c.track);if(!r||!s||Qr(e,n[0].quality,(d=(0,vx.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?QN(r,e.max):!0,u=e.min?zN(r,e.min):!0;o&&u||i(e)}};import{assertNever as Tx,debounce as iF,merge as Ix,observableFrom as rF,Subscription as sF,map as Ex,ValueSubject as aF,ErrorCategory as Eh,VideoQuality as nF}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as ZN}from"@vkontakte/videoplayer-shared/es2018";var yx=["stun:videostun.mycdn.me:80"],eF=1e3,tF=3,Ih=()=>null,ul=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=Ih;this.externalStopCallback=Ih;this.externalErrorCallback=Ih;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:yx}]};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:ZN.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),eF)}normalizeOptions(e={}){let t={stunServerList:yx,maxRetryNumber:tF,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var qn=class{constructor(e){this.videoState=new j("stopped");this.maxSeekBackTime$=new aF(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"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return Tx(e)}};this.subscription=new sF,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=$e(e.container,e.tuning),this.liveStreamClient=new ul(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),Me(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Eh.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(Ix(this.videoState.stateChangeStarted$.pipe(Ex(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ex(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=De(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(Ke(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Le(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 Tx(n.to)}},i)).add(Ix(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,rF(["init"])).pipe(iF(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(fe(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:nF.INVARIANT}),this.video.srcObject=e,R(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:Eh.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Eh.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var $s=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}};import{assertNever as Hn,assertNonNullable as ei,ErrorCategory as ll,filter as Rx,isNonNullable as $x,isNullable as hF,map as fF,merge as mF,once as bF,Subject as ne,Subscription as Mx,ValueSubject as H,flattenObject as wh,devNull as gF,getWindow as SF}from"@vkontakte/videoplayer-shared/es2018";import{Observable as oF,map as wx,Subscription as uF,Subject as lF}from"@vkontakte/videoplayer-shared/es2018";var xx=a=>new oF(e=>{let t=new uF,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(wx(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(wx(({type:l})=>l!==void 0)),n=new lF,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval),q({m:"hangup.set",l,id:o})})),t.add(r.subscribe(()=>{q({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(q({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval),q({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as cF,Subscription as dF,combine as pF,filter as kx,once as Ax}from"@vkontakte/videoplayer-shared/es2018";function Px(){return new(window.AudioContext||window.webkitAudioContext)}var jn=class jn{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Q;this.subscriptions=new dF;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(kx(s=>!!s.type),Ax()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){C.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(pF({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(kx(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),Ax()).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=Px();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 s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:jn.errorId,category:cF.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${jn.errorId} exception`,thrown:e})}};jn.errorId="VolumeMultiplierManager";var Ms=jn;var vF={chunkDuration:5e3,maxParallelRequests:5},Wn=class{constructor(e){this.current$=new H({type:void 0});this.providerError$=new ne;this.noAvailableProvidersError$=new ne;this.volumeMultiplierError$=new ne;this.providerOutput={position$:new H(0),duration$:new H(1/0),volume$:new H({muted:!1,volume:1}),availableVideoStreams$:new H([]),currentVideoStream$:new H(void 0),availableVideoTracks$:new H([]),currentVideoTrack$:new H(void 0),availableVideoCodecs$:new H([]),availableAudioStreams$:new H([]),currentAudioStream$:new H(void 0),availableAudioTracks$:new H([]),availableAudioCodecs$:new H([]),currentVideoSegmentLength$:new H(0),currentAudioSegmentLength$:new H(0),isAudioAvailable$:new H(!0),autoVideoTrackLimitingAvailable$:new H(!1),autoVideoTrackLimits$:new H(void 0),currentBuffer$:new H(void 0),currentNativeBuffer$:new H(void 0),isBuffering$:new H(!0),error$:new ne,fetcherError$:new ne,fetcherRecoverableError$:new ne,warning$:new ne,willSeekEvent$:new ne,soundProhibitedEvent$:new ne,seekedEvent$:new ne,loopedEvent$:new ne,endedEvent$:new ne,manifestRequested$:new ne,firstBytesManifest$:new ne,manifestReceived$:new ne,firstBytesRequested$:new ne,firstBytesReceived$:new ne,firstBytesEvent$:new ne,loadedMetadataEvent$:new ne,firstFrameEvent$:new ne,canplay$:new ne,isLive$:new H(void 0),isLiveEnded$:new H(null),canPlayLiveTailBuffer$:new H(!1),isLowLatency$:new H(!1),canChangePlaybackSpeed$:new H(!0),liveTime$:new H(void 0),liveBufferTime$:new H(void 0),liveLatency$:new H(void 0),severeStallOccurred$:new ne,availableTextTracks$:new H([]),currentTextTrack$:new H(void 0),hostname$:new H(void 0),httpConnectionType$:new H(void 0),httpConnectionReused$:new H(void 0),inPiP$:new H(!1),inFullscreen$:new H(!1),element$:new H(void 0),elementVisible$:new H(!0),availableSources$:new H(void 0),is3DVideo$:new H(!1),playbackState$:new H(""),getCurrentTime$:new H(null)};this.subscription=new Mx;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=pc([...WE(this.params.tuning),...HE(this.params.tuning)]).filter(l=>$x(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,xh.default)(r,l)),...t.filter(l=>(0,xh.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",wh(s)),this.screenFormatsIterator=new $s(s);let n=[...Ip(!0),...Ip(!1)];this.chromecastFormatsIterator=new $s(n.filter(l=>$x(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ms.isSupported()&&(this.volumeMultiplierManager=new Ms(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){q.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 $s(e))}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(hF(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:ll.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Hn(e)}}createScreenProvider(e){var u,l,d,c;let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let p=this.applyFailoverHost(t[e]),h=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ei(p),this.params.tuning.useNewDashProvider?new _n({...o,source:p,sourceHls:h,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):this.params.tuning.useDashProviderVirtual&&!C.device.isMobile?new gs({...o,source:p,sourceHls:h,forceVideoCodec:(l=this.videoCodecsIterator)==null?void 0:l.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&C.device.isMobile?new gs({...o,source:p,sourceHls:h,forceVideoCodec:(d=this.videoCodecsIterator)==null?void 0:d.getValue()}):new En({...o,source:p,sourceHls:h,forceVideoCodec:(c=this.videoCodecsIterator)==null?void 0:c.getValue()})}case"DASH_LIVE_CMAF":{let p=this.applyFailoverHost(t[e]);return ei(p),this.params.tuning.useNewDashProvider?new On({...o,source:p}):new wn({...o,source:p})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let p=this.applyFailoverHost(t[e]);return ei(p),new Fn({...o,source:p})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=this.applyFailoverHost(t[e]);return ei(p),new Nn({...o,source:p,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let p=this.applyFailoverHost(t[e]);return ei(p),new Un({...o,source:p})}case"DASH_LIVE":{let p=this.applyFailoverHost(t[e]);return ei(p),new QT({...o,source:p,config:{...vF,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let p=this.applyFailoverHost(t[e]);return ei(p),new qn({container:i,source:p,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 Hn(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o={meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof Ut){let{chromecastConnector:l}=this.params.dependencies.chromecastInitializer;return ei(l),new Xs({...o,chromecastConnector:l})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return ei(u),new ha({...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 Hn(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Hn(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 Hn(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,Lx.default)((0,Ph.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new Mx,t=!1,i=0;e.add(mF(this.providerOutput.error$.pipe(Rx(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),xx({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(fF(s=>({id:`ProviderHangup:${s}`,category:ll.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let s=this.params.desiredState.playbackState.transitionEnded$.pipe(Rx(({to:n})=>n==="playing"),bF()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=q.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&SF().console.log(`===== DASH_LIVE DEBUG START ====
|
|
178
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var $I=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ut=(a,e)=>{let t=a;t=(0,Pd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,MI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Pd.default)(t,n,(o,u)=>RI(s)?o:RI(u)?s:(0,CI.default)(s,parseInt(u,10),"0"))}return t},Oo=(a,e)=>{var D,A,V,M,q,G,H,E,P,I,x,F,O,ct,dt,Y,Se,ye,Te,Fe,It,Et,di,Gi,Yi,Ap,Rp,$p,Mp,Cp,Lp,Dp,Bp,Vp,_p,Op,Np,Fp,qp,Up,jp,Hp,Qp,Wp,zp,Gp,Yp,Kp,Xp,Jp,Zp,eh,th,ih,rh,ah,sh,nh,oh,uh,lh;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(et=>{var Z,pi;return(pi=(Z=et.textContent)==null?void 0:Z.trim())!=null?pi:""}),o=(D=(0,LI.default)(n,0))!=null?D:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],p=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let g,S=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],y=T.reduce((et,Z)=>({...et,[Z.id]:Z.children}),{}),w=T.reduce((et,Z)=>({...et,[Z.id]:Z.getAttribute("duration")}),{});S?g=$I(S):(0,kd.default)(w).filter(et=>et).length&&!u?g=(0,kd.default)(w).reduce((et,Z)=>{var pi;return et+((pi=$I(Z))!=null?pi:0)},0):f&&(g=parseInt(f,10));let R=0,L=(V=(A=s.getAttribute("profiles"))==null?void 0:A.split(","))!=null?V:[];for(let et of T.map(Z=>Z.id))for(let Z of y[et]){let pi=(M=Z.getAttribute("id"))!=null?M:"id"+(R++).toString(10),Wr=(q=Z.getAttribute("mimeType"))!=null?q:"",Eu=(G=Z.getAttribute("codecs"))!=null?G:"",wu=(H=Z.getAttribute("contentType"))!=null?H:Wr==null?void 0:Wr.split("/")[0],yw=(P=(E=Z.getAttribute("profiles"))==null?void 0:E.split(","))!=null?P:[],ch=(x=AI((I=Z.getAttribute("lang"))!=null?I:""))!=null?x:{},Ys=(ct=(O=(F=Z.querySelector("Label"))==null?void 0:F.textContent)==null?void 0:O.trim())!=null?ct:void 0,Tw=Z.querySelectorAll("Representation"),Iw=Z.querySelector("SegmentTemplate"),Ew=(Y=(dt=Z.querySelector("Role"))==null?void 0:dt.getAttribute("value"))!=null?Y:void 0,Ki=wu,ue={id:pi,language:ch.language,isDefault:Ew==="main",label:Ys,codecs:Eu,hdr:Ki==="video"&&xd(Eu),mime:Wr,representations:[]};for(let J of Tw){let Nt=(Se=J.getAttribute("lang"))!=null?Se:void 0,Ks=(Te=(ye=Ys!=null?Ys:Z.getAttribute("label"))!=null?ye:J.getAttribute("label"))!=null?Te:void 0,Xs=(Et=(It=(Fe=J.querySelector("BaseURL"))==null?void 0:Fe.textContent)==null?void 0:It.trim())!=null?Et:"",hi=new URL(Xs||o,e).toString(),Ft=(di=J.getAttribute("mimeType"))!=null?di:Wr,Js=(Yi=(Gi=J.getAttribute("codecs"))!=null?Gi:Eu)!=null?Yi:"",Zs;if(wu==="text"){let qt=J.getAttribute("id")||"",en=((Ap=ch.privateuse)==null?void 0:Ap.includes("x-auto"))||qt.includes("_auto"),mi=J.querySelector("SegmentTemplate");if(mi){let zr={representationId:(Rp=J.getAttribute("id"))!=null?Rp:void 0,bandwidth:($p=J.getAttribute("bandwidth"))!=null?$p:void 0},tn=parseInt((Mp=J.getAttribute("bandwidth"))!=null?Mp:"",10)/1e3,rn=(Lp=parseInt((Cp=mi.getAttribute("startNumber"))!=null?Cp:"",10))!=null?Lp:1,Xi=parseInt((Dp=mi.getAttribute("timescale"))!=null?Dp:"",10),xu=(Bp=mi.querySelectorAll("SegmentTimeline S"))!=null?Bp:[],Ji=mi.getAttribute("media");if(!Ji)continue;let an=[],sn=0,nn="",Zi=0,Gr=rn,xe=0;for(let tt of xu){let fi=parseInt((Vp=tt.getAttribute("d"))!=null?Vp:"",10),ze=parseInt((_p=tt.getAttribute("r"))!=null?_p:"",10)||0,Ut=parseInt((Op=tt.getAttribute("t"))!=null?Op:"",10);xe=Number.isFinite(Ut)?Ut:xe;let bi=fi/Xi*1e3,jt=xe/Xi*1e3;for(let pt=0;pt<ze+1;pt++){let Ht=ut(Ji,{...zr,segmentNumber:Gr.toString(10),segmentTime:(xe+pt*fi).toString(10)}),er=(jt!=null?jt:0)+pt*bi,Kr=er+bi;Gr++,an.push({time:{from:er,to:Kr},url:Ht})}xe+=(ze+1)*fi,sn+=(ze+1)*bi}Zi=xe/Xi*1e3,nn=ut(Ji,{...zr,segmentNumber:Gr.toString(10),segmentTime:xe.toString(10)});let Yr={time:{from:Zi,to:1/0},url:nn},wt={type:"template",baseUrl:hi,segmentTemplateUrl:Ji,initUrl:"",totalSegmentsDurationMs:sn,segments:an,nextSegmentBeyondManifest:Yr,timescale:Xi};Zs={id:qt,kind:"text",segmentReference:wt,profiles:[],duration:g,bitrate:tn,mime:"",codecs:"",width:0,height:0,isAuto:en}}else Zs={id:qt,isAuto:en,kind:"text",url:hi}}else{let qt=(Fp=(Np=J.getAttribute("contentType"))!=null?Np:Ft==null?void 0:Ft.split("/")[0])!=null?Fp:wu,en=(Up=(qp=Z.getAttribute("profiles"))==null?void 0:qp.split(","))!=null?Up:[],mi=parseInt((jp=J.getAttribute("width"))!=null?jp:"",10),zr=parseInt((Hp=J.getAttribute("height"))!=null?Hp:"",10),tn=parseInt((Qp=J.getAttribute("bandwidth"))!=null?Qp:"",10)/1e3,rn=(Wp=J.getAttribute("frameRate"))!=null?Wp:"",Xi=(zp=J.getAttribute("quality"))!=null?zp:void 0,xu=rn?kI(rn):void 0,Ji=(Gp=J.getAttribute("id"))!=null?Gp:"id"+(R++).toString(10),an=qt==="video"?`${zr}p`:qt==="audio"?`${tn}Kbps`:Js,sn=`${Ji}@${an}`,nn=[...L,...yw,...en],Zi,Gr=J.querySelector("SegmentBase"),xe=(Yp=J.querySelector("SegmentTemplate"))!=null?Yp:Iw;if(Gr){let wt=(Xp=(Kp=J.querySelector("SegmentBase Initialization"))==null?void 0:Kp.getAttribute("range"))!=null?Xp:"",[tt,fi]=wt.split("-").map(Ht=>parseInt(Ht,10)),ze={from:tt,to:fi},Ut=(Jp=J.querySelector("SegmentBase"))==null?void 0:Jp.getAttribute("indexRange"),[bi,jt]=Ut?Ut.split("-").map(Ht=>parseInt(Ht,10)):[],pt=Ut?{from:bi,to:jt}:void 0;Zi={type:"byteRange",url:hi,initRange:ze,indexRange:pt}}else if(xe){let wt={representationId:(Zp=J.getAttribute("id"))!=null?Zp:void 0,bandwidth:(eh=J.getAttribute("bandwidth"))!=null?eh:void 0},tt=parseInt((th=xe.getAttribute("timescale"))!=null?th:"",10),fi=(ih=xe.getAttribute("initialization"))!=null?ih:"",ze=xe.getAttribute("media"),Ut=(ah=parseInt((rh=xe.getAttribute("startNumber"))!=null?rh:"",10))!=null?ah:1,bi=ut(fi,wt);if(!ze)throw new ReferenceError("No media attribute in SegmentTemplate");let jt=(sh=xe.querySelectorAll("SegmentTimeline S"))!=null?sh:[],pt=[],Ht=0,er="",Kr=0;if(jt.length){let on=Ut,it=0;for(let tr of jt){let ht=parseInt((nh=tr.getAttribute("d"))!=null?nh:"",10),gi=parseInt((oh=tr.getAttribute("r"))!=null?oh:"",10)||0,un=parseInt((uh=tr.getAttribute("t"))!=null?uh:"",10);it=Number.isFinite(un)?un:it;let Pu=ht/tt*1e3,ku=it/tt*1e3;for(let ln=0;ln<gi+1;ln++){let xw=ut(ze,{...wt,segmentNumber:on.toString(10),segmentTime:(it+ln*ht).toString(10)}),dh=(ku!=null?ku:0)+ln*Pu,Pw=dh+Pu;on++,pt.push({time:{from:dh,to:Pw},url:xw})}it+=(gi+1)*ht,Ht+=(gi+1)*Pu}Kr=it/tt*1e3,er=ut(ze,{...wt,segmentNumber:on.toString(10),segmentTime:it.toString(10)})}else if(I0(g)){let it=parseInt((lh=xe.getAttribute("duration"))!=null?lh:"",10)/tt*1e3,tr=Math.ceil(g/it),ht=0;for(let gi=1;gi<tr;gi++){let un=ut(ze,{...wt,segmentNumber:gi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+it},url:un}),ht+=it}Kr=ht,er=ut(ze,{...wt,segmentNumber:tr.toString(10),segmentTime:ht.toString(10)})}let ww={time:{from:Kr,to:1/0},url:er};Zi={type:"template",baseUrl:hi,segmentTemplateUrl:ze,initUrl:bi,totalSegmentsDurationMs:Ht,segments:pt,nextSegmentBeyondManifest:ww,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!qt||!Ft)continue;let Yr={video:"video",audio:"audio",text:"text"}[qt];if(!Yr)continue;Ki||(Ki=Yr),Zs={id:sn,kind:Yr,segmentReference:Zi,profiles:nn,duration:g,bitrate:tn,mime:Ft,codecs:Js,width:mi,height:zr,fps:xu,quality:Xi}}ue.language||(ue.language=Nt),ue.label||(ue.label=Ks),ue.mime||(ue.mime=Ft),ue.codecs||(ue.codecs=Js),ue.hdr||(ue.hdr=Ki==="video"&&xd(Js)),ue.representations.push(Zs)}if(Ki){let J=r[Ki].find(Nt=>Nt.id===ue.id);if(J&&ue.representations.every(Nt=>Nt.segmentReference.type==="template"))for(let Nt of J.representations){let Ks=ue.representations.find(Ft=>Ft.id===Nt.id);if(!Ks)continue;let Xs=Ks.segmentReference,hi=Nt.segmentReference;hi.segments.push(...Xs.segments),hi.nextSegmentBeyondManifest=Xs.nextSegmentBeyondManifest}else r[Ki].push(ue)}}return{duration:g,streams:r,baseUrls:n,live:v}};var Fo=_(Ke(),1),Ad=_(De(),1);import{assertNever as qo}from"@vkontakte/videoplayer-shared/es2018";var No=a=>{let{webmDecodingInfo:e}=B.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:qo(a)}},DI=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...No(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(B.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...No(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...No(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...No(a),...s,"HLS","HLS_ONDEMAND"];default:qo(e)}if(B.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:qo(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},BI=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=B.device.isMac&&B.browser.isSafari;if(B.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:qo(a)}else B.video.nativeHlsSupported&&!u&&!B.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Rd=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Uo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Fo.default)(t.value.split("."),0)}for(let t of a){let i=(0,Fo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Fo.default)(e.value.split("."),0)},jo=a=>{let e=a.map(i=>Lr(i)),{codecs:t}=B.video;return P0().filter(i=>{if((0,Ad.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})},Ho=a=>{let e=a.map(i=>Lr(i)),{codecs:t}=B.video;return k0().filter(i=>{if((0,Ad.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Lr=a=>a.split(".")[0].replace("0",""),P0=()=>["av1","vp9","hev1","avc1"],k0=()=>["opus","mp4a"];var YI=_(Ke(),1);var A0=(a,e={})=>{let i=e.timeout||1,r=performance.now();return de.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},R0=a=>de.clearTimeout(a),VI=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),_I=!VI(de.requestIdleCallback)||!VI(de.cancelIdleCallback),Vi=_I?A0:de.requestIdleCallback,_i=_I?R0:de.cancelIdleCallback;import{abortable as Bd,assertNonNullable as Tt,ErrorCategory as K0,fromEvent as X0,getExponentialDelay as J0,getWindow as GI,isHigher as Z0,isNonNullable as le,isNullable as ge,once as eV,Subject as tV,Subscription as iV,ValueSubject as Is}from"@vkontakte/videoplayer-shared/es2018";var OI=_(Ke(),1);var Qo=a=>a.valid,W=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Dr=class extends W{};import{assertNever as $0}from"@vkontakte/videoplayer-shared/es2018";var Ka=class extends W{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(e)}}};var Xa=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Ja=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ie=class extends W{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 Za=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var es=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ts=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var Oi=class extends ie{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var is=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rs=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var as=class extends ie{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ss=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var ns=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var os=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var us=class extends ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ls=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cs=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ds=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var ps=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hs=class extends ie{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ms=class extends ie{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var fs=class extends ie{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var bs=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var gs=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var vs=class extends W{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 C0={ftyp:Xa,moov:Ja,mvhd:Za,moof:es,mdat:ts,sidx:Oi,trak:is,mdia:os,mfhd:ds,tkhd:us,traf:ps,tfhd:hs,tfdt:ms,trun:fs,minf:ls,sv3d:rs,st3d:as,prhd:ss,proj:cs,equi:ns,uuid:Ka,stbl:bs,stsd:gs,avc1:vs,unknown:Dr},Mt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!Qo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=C0[e];return i?new i(t,new a):new Dr(t,new a)}};var ei=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;Qo(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var D0=new TextDecoder("ascii"),B0=a=>D0.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",V0=a=>{let e=new Oi(a,new Mt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},_0=(a,e)=>{let i=new Mt().parse(a),r=new ei(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},O0=a=>{let t=new Mt().parse(a),i=new ei(t),r={},s=i.findAll("uuid"),n=(0,OI.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},N0=a=>{var r;let t=new Mt().parse(a);return(r=new ei(t).find("sidx"))==null?void 0:r.timescale},F0=(a,e)=>{let i=new Mt().parse(a),s=new ei(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},q0=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Mt().parse(a),r=new ei(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},NI={validateData:B0,parseInit:q0,getIndexRange:()=>{},parseSegments:V0,parseFeedableSegmentChunk:_0,getChunkEndTime:F0,getServerLatencyTimestamps:O0,getTimescaleFromIndex:N0};var ys=_(De(),1);import{assertNonNullable as $d,isNonNullable as jI,isNullable as j0}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as U0}from"@vkontakte/videoplayer-shared/es2018";var FI={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"}},qI=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ss(a,t),r=i in FI,s=r?FI[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,d=Ss(u),c=l*2**((o-1)*8)+d,p=t+o,h;return p+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Ss=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},lt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ss(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:U0(e)}},Ni=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=qI(i);if(!e(r))return;r.type==="master"&&Ni(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},UI=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=qI(a);return Ni(r.value,({tag:s,type:n,value:o})=>(s===17143?e=lt(o,n):s===17026?t=lt(o,n):s===17029&&(i=lt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var HI=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],H0=[231,22612,22743,167,171,163,160,175],Q0=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return Ni(a,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let v=lt(m,h);l=Ss(v)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=lt(m,h):p===17545?r=lt(m,h):p===21420&&l===475249515?u=lt(m,h):p===374648427?Ni(m,({tag:v,type:g,value:S})=>v===30321?(d=lt(S,g)===1,!1):!0):s&&n&&(0,ys.default)(HI,p)&&(o=!0),!o}),$d(e,"Failed to parse webm Segment start"),$d(t,"Failed to parse webm Segment end"),$d(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},W0=a=>{if(j0(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},z0=(a,e)=>{let t=!1,i=!1,r=o=>jI(o.time)&&jI(o.position),s=[],n;return Ni(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=lt(l,u));break;case 183:break;case 241:n&&(n.position=lt(l,u));break;default:t&&(0,ys.default)(HI,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},G0=a=>{let e=0,t=!1;try{Ni(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ys.default)(H0,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ys.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},QI={validateData:UI,parseInit:Q0,getIndexRange:W0,parseSegments:z0,parseFeedableSegmentChunk:G0};var Fi=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return QI;case"mp4":return NI}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Md=_(Ke(),1);import{videoSizeToQuality as Y0}from"@vkontakte/videoplayer-shared/es2018";var ti=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:Y0({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ts=({id:a,bitrate:e})=>({id:a,bitrate:e}),WI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),zI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Cd=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Md.default)(i.split("."),0),isDefault:r}),Ld=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Md.default)(r.split("."),0)}),Dd=a=>"url"in a,Qe=a=>a.type==="template";var Br=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,manifest:o}){this.error$=new tV;this.playingRepresentation$=new Is(void 0);this.playingRepresentationInit$=new Is(void 0);this.currentSegmentLength$=new Is(0);this.onLastSegment$=new Is(!1);this.fullyBuffered$=new Is(!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 te;this.downloadAbortController=new te;this.subscription=new iV;this.startWith=Bd(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Tt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=Fi(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Tt(i,"No init buffer for starting representation"),Tt(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=Bd(this.destroyAbortController.signal,async function*(e,t=!0){var c;if(ge(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);Tt(r,`No such representation ${e}`),Tt(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),n=this.segments.get(r.id);Tt(s,"No init buffer for switching representation"),Tt(n,"No segments for switching representation");let o=(c=this.getCurrentPosition())!=null?c:0,u=p=>p.segment.networkStatus!=="downloaded"||p.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,l=p=>{let h=this.representations.get(p.representationId);return Tt(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},d=p=>t?u(p)&&l(p):u(p);this.bufferPlaybackQueue.filter(d).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!d(p)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=Bd(this.downloadAbortController.signal,async function*(){let e=J0(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=GI();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add(X0(i,"online").pipe(eV()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));var u;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=(u=o==null?void 0:o.baseUrls)!=null?u:[],this.representations=new Map(i.map(l=>[l.id,l]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){ge(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return le(t)&&le(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){var s,n;let t=(n=(s=this.downloadingRepresentationId)!=null?s:this.playingRepresentationId)!=null?n:"",i=this.segments.get(t),r=i==null?void 0:i.find(o=>o.time.from<=e&&o.time.to>=e);return r==null?void 0:r.time.from}getRepresentationInitialTime(){var t;if(ge(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return((t=e==null?void 0:e[0].time.from)!=null?t:0)/1e3}calculateDurationFromSegments(){var t;if(ge(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,YI.default)(e,-1))==null?void 0:t.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=GI();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_830ehhlk400h)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_830ehhlk400h(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=ti(e),s=ti(t);i=le(r)&&le(s)&&Z0(s.quality,r.quality)}else if(this.kind==="audio"){let r=Ts(e),s=Ts(t);i=le(r==null?void 0:r.bitrate)&&le(s==null?void 0:s.bitrate)&&s.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 te,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,Vi(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():le(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){var r;try{let s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s);this.initDataPromises.set(e.id,n);let{initMetadata:o,initDataView:u,segments:l}=(r=await n)!=null?r:{};if(this.initDataPromises.delete(e.id),ge(u)||ge(l))return;o&&this.parsedInitData.set(e.id,o);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d),this.segments.set(e.id,l),this.failedDownloads=0}catch(s){i&&this.error$.next({id:"LoadInits",category:K0.WTF,message:"loadInit threw",thrown:s})}}async maintainNativeBuffer(){var o;let e=this.getCurrentPosition();if(ge(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(u=>this.withinInterval(e,u.segment.time)),i=this.bufferPlaybackQueue.find(u=>u.segment.bufferStatus!=="fed"),r=this.initData.get((o=i==null?void 0:i.representationId)!=null?o:""),s=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;le(r)&&le(i)&&le(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)),le(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)),le(s)&&this.withinRemoveInterval(e,s.segment.time)&&await this.removeSegment(s,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Tt(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(ge(t)||ge(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);le(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let s=this.selectItemsToLoad();await this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if(ge(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];ge(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){Tt(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;le(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&s>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;s-=u-o,r++}return n}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 le(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return le(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 le(e)?e-i>t:!1}async appendSegmentFully(e,t){if(ge(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(ge(e.segment.data)||ge(e.segment.loadedBytes)||ge(e.segment.feedingBytes)||ge(e.segment.fedBytes)||ge(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s!=null&&s.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,await this.nativeBufferManager.append(s,t)&&(e.segment.fedBytes+=s.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,s=(r-i)/4;await this.nativeBufferManager.remove(0,r-s,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||le(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let s=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)le(o.size)&&s>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())le(o.size)&&s>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size)}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as rV,isNonNullable as aV,isNullable as KI,now as XI}from"@vkontakte/videoplayer-shared/es2018";var Wo=class extends Br{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:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(s,{...n,priority:i}),this.lastDataObtainedTimestampMs=XI(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),ot(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=s);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(Me(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=XI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:rV.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:s,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||KI(o)||KI(r)||n.aborted))for(let u of e){let{segment:l}=u,d=l.byte.from-r,c=l.byte.to-r,p=c-d+1,h=d<s,m=c<=s;l.size=p,h&&(l.networkStatus==="downloading"&&l.bufferStatus==="none"&&m?(l.data=new DataView(t.buffer,t.byteOffset+d,p),this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u),l.loadedBytes=Math.min(p,s-d),await this.onDownloadItem(u)):aV(l.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&l.networkStatus==="downloading"&&(l.loadedBytes=Math.min(p,s-d),m&&(this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u)),l.loadedBytes>l.feedingBytes&&(l.data=new DataView(t.buffer,t.byteOffset+d,l.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(Me(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as sV,isNullable as Vd,now as JI}from"@vkontakte/videoplayer-shared/es2018";var Vr=class extends Br{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:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(s,{...n,priority:i});if(this.lastDataObtainedTimestampMs=JI(),Vd(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(),ot(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=JI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:sV.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Me(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:s}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||Vd(u)||Vd(o.feedingBytes)||o.networkStatus!=="downloading"||s.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(!Me(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var _d=_(ja(),1),eE=_(Ke(),1);import{assertNonNullable as nV,ErrorCategory as oV,isNullable as Ct,ValueSubject as ZI}from"@vkontakte/videoplayer-shared/es2018";var zo=class extends Vr{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new ZI(0);this.currentLowLatencySegmentLength$=new ZI(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){var r,s,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,_d.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if(Ct(o)||!Me(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(s=(0,eE.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>c>=h.time.from+l&&c<=h.time.to+l);if(p===-1){let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...d,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;nV(t);let i=this.segments.get(t);if(i!=null&&i.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t==null?void 0:t.streams[this.kind],r=(0,_d.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if(Ct(r))return;let s=this.segments.get(r.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){var r;if(Ct(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return Ct(t)||!Me(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),Ct(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);s&&n&&this.currentLiveSegmentServerLatency$.next(n-s),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){var n;let i=t.segment.data,r=(n=this.representations.get(t.representationId))==null?void 0:n.segmentReference;if(Ct(t.segment.data)||Ct(r)||!Me(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=s.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let s of this.representations.values()){let n=s.segmentReference;if(!Me(n))return;let o=(r=this.segments.get(s.id))!=null?r:[],u=o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.from));if(u!=null&&u.isCurrentLowLatency&&(u.time.to=t.segment.time.to,i=u.time.to-u.time.from,u.isCurrentLowLatency=!1),!!!o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let d=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),c=ut(n.segmentTemplateUrl,{segmentTime:d});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:c,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){var s;try{let n=this.tuning.dash.useFetchPriorityHints?i:"auto",o=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,n);this.initDataPromises.set(t.id,o);let{initMetadata:u,initDataView:l,segments:d}=(s=await o)!=null?s:{};if(this.initDataPromises.delete(t.id),Ct(l)||Ct(d))return;u&&this.parsedInitData.set(t.id,u);let c=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,c);let p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(t.id,p),this.failedDownloads=0}catch(n){r&&this.error$.next({id:"LoadInits",category:oV.WTF,message:"loadInit threw",thrown:n})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[],n=0,o=i.length-1;do s.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[s[0]]:s}};var Es=class{static getBufferManager(e,t,i,r){var s;return(s=r.manifest)!=null&&s.live?new zo(e,t,i,r):Me(i[0].segmentReference)?new Vr(e,t,i,r):new Wo(e,t,i,r)}};import{ErrorCategory as cV,fromEvent as dV,isNullable as _r,Subject as pV,Subscription as hV}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as uV,ErrorCategory as tE,Subject as iE}from"@vkontakte/videoplayer-shared/es2018";var lV=18,rE=!1;try{rE=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=lV}catch(a){console.error(a)}var Od=class{constructor(e,t=!1){this.bufferFull$=new iE;this.error$=new iE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:tE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};rE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:tE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:uV(t)}}},aE=Od;var ii=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var ws=class{constructor(e){this.error$=new pV;this.subscription=new hV;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new aE(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add(dV(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:cV.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(_r(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&(i=await this.sourceBufferTaskQueue.remove(r.from,r.to,e));return i}warmUpMediaSource(){!_r(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(_r(this.sourceBuffer)||!ee(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 _r(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||_r(e)?0:ii(this.sourceBuffer.buffered,e)}async abortBuffer(e){return _r(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){var e;if(this.subscription.unsubscribe(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null}};var SV=["timeupdate","progress","play","seeked","stalled","waiting"],oE=["timeupdate","progress","loadeddata","playing","seeked"],Yo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new nE;this.subscriptionRemovable=new vV;this.representationSubscription=new nE;this.forceEnded$=new ai;this.destroyController=new te;this.state$=new j("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new ai;this.manifestRequested=new ai;this.manifestReceived=new ai;this.firstBytesRequested=new ai;this.firstBytesReceived=new ai;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.isActiveLive$=new re(!1);this.isLowLatency$=new re(!1);this.liveDuration$=new re(0);this.liveSeekableDuration$=new re(0);this.liveAvailabilityStartTime$=new re(0);this.liveStreamStatus$=new re(void 0);this.currentBuffer$=new re({from:0,to:0});this.bufferLength$=new re(0);this.nativeBufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.fetcherRecoverableError$=new ai;this.fetcherError$=new ai;this.initRepresentations=sE(this.destroyController.signal,async function*(e,t,i){var s;this.tracer.log("initRepresentationsStart",Go({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(),Lt(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?(s=this.audioBufferManager)==null?void 0:s.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=sE(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Ps(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:qi.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 Bo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){var r;this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:qi.PARSER,message:"No playable video representations"})}initBuffer(){var t,i;Lt(this.element),this.state$.setState("running"),this.subscription.add(ks(...SV.map(r=>Ui(this.element,r)),Ui(xs(),"online")).subscribe(()=>this.tick(),r=>this.error$.next({id:"DashVKPlayer",category:qi.WTF,message:"Internal logic error",thrown:r})));let e=[...(i=(t=this.source)==null?void 0:t.activeSourceBuffers)!=null?i:[]];this.subscription.add(ks(...e.map(r=>Ui(r,"updateend"))).subscribe(r=>this.reinitDecoderIfNeeded())),this.subscription.add(Ui(this.element,"waiting").subscribe(r=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=bV(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),s=>this.error$.next({id:"StallWatchdogCallback",category:qi.NETWORK,message:"Can't restore DASH after stall.",thrown:s})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}async seek(e,t=!1){var r,s,n,o;Lt(this.element),Lt(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await((o=this.audioBufferManager)==null?void 0:o.seek(i)),this.tracer.log("seek",Go({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){ri(this.element)&&ri(this.source)&&ri(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(i=>i.warmUpMediaSource())}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(r=>r.destroy()),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&xs().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),ri(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){var e;return((e=this.source)==null?void 0:e.readyState)!=="open"}async reinitDecoderIfNeeded(e=!1){var r,s;let t=(s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[];if(Ps(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(n=>i>=n.from&&i<=n.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){Lt(this.element),Lt(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",Go(i))}isStallExceeded(e){var p,h,m,f,v,g,S,T;let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=gV(),s=100,n=(h=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?h:0;this.videoLastDataObtainedTimestamp$.next(n);let o=(f=(m=this.audioBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?f:0,u=(g=(v=this.videoBufferManager)==null?void 0:v.getForwardPlaybackBufferDuration())!=null?g:0,l=(T=(S=this.audioBufferManager)==null?void 0:S.getForwardPlaybackBufferDuration())!=null?T:0,d=ri(this.videoBufferManager)&&u<s&&r-n>i,c=ri(this.audioBufferManager)&&l<s&&r-o>i;return(d||c)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Ps(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",Go(i)),i}parseManifest(e){var t;try{return Oo(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=Mo(e))!=null?t:{id:"ManifestParsing",category:qi.PARSER,message:"Failed to parse MPD manifest",thrown:i};this.error$.next(r)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,l)=>{var d,c,p,h;return!!((c=(d=this.element)==null?void 0:d.canPlayType)!=null&&c.call(d,u)&&((h=(p=je())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${l}"`))||o==="text")},r,s;for(let o of["video","audio"]){let l=e.streams[o].filter(({mime:c,codecs:p})=>i(o,c,p));t[o]=l;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:p})=>p);o==="audio"&&(s=Ho(c),d=s[0]),o==="video"&&(r=jo(c),this.forceVideoCodec&&(0,uE.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=l.filter(({codecs:p})=>Lr(p)===d))}else{let c=new Set(l.map(({codecs:p})=>p));d=Uo(c),d&&(t[o]=l.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let c=this.tuning.preferHDR,p=t.video.some(m=>m.hdr),h=t.video.some(m=>!m.hdr);B.display.isHDR&&c&&p?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:s}),n}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){Lt(this.manifest),Lt(this.element);let s=l=>{this.representationSubscription.add(Ui(l,"error").pipe(Nd(d=>{var c;return!!((c=this.element)!=null&&c.played.length)})).subscribe(d=>{this.error$.next({id:"VideoSource",category:qi.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=kn();let n=xs().document,o=n.createElement("source");if(s(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),lr())if(r){let l=n.createElement("source");s(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,d)=>[...l,...d.representations],[]);if(this.videoNativeBufferManager=new ws(this.source),this.videoBufferManager=Es.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],ri(i)){this.audioNativeBufferManager=new ws(this.source);let l=this.manifest.streams.audio.reduce((d,c)=>[...d,...c.representations],[]);this.audioBufferManager=Es.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=>{var i;e&&(this.timeoutSourceOpenId=xs().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:qi.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(i=this.source)==null||i.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&xs().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(ks(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),Lt(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(ks(...oE.map(e=>Ui(this.element,e))).pipe(Fd(e=>{var t;return(t=this.videoBufferManager)==null?void 0:t.getPlaybackBufferState()}),Nd(ri),Fd(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(ks(...oE.map(e=>Ui(this.element,e))).pipe(Fd(e=>{var t,i,r,s;return Math.max((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(s=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?s:0)}),mV()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Nd(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=fV(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){var r,s,n;if(Ps(this.element)||Ps(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[]).find(o=>e>=o.from&&e<=o.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await((n=this.audioBufferManager)==null?void 0:n.maintain(e))}};import{assertNonNullable as Ko,combine as yV,ErrorCategory as TV,filter as qd,filterChanged as IV,fromEvent as EV,isNonNullable as wV,map as Ud,merge as As}from"@vkontakte/videoplayer-shared/es2018";var Xo=class extends Yo{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;Ko(this.manifest),Ko(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,jd.default)((0,jd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),Me(i.segmentReference)&&i.segmentReference.totalSegmentsDurationMs&&r.push(i.segmentReference.totalSegmentsDurationMs),r})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){var i,r;Ko(this.element);let t=this.element.currentTime*1e3;await Promise.all([(i=this.videoBufferManager)==null?void 0:i.maintain(t),(r=this.audioBufferManager)==null?void 0:r.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){Ko(this.element);let e=As(EV(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(qd(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(As(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=As(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe(Ud(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=As(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe(Ud(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=yV({allBuffersFull:e,someBufferEnded:t}).pipe(IV(),Ud(({allBuffersFull:s,someBufferEnded:n})=>s&&n),qd(s=>s)),r=()=>{var s;try{(s=this.source)==null||s.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:TV.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add(As(this.forceEnded$,i).pipe(qd(s=>wV(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var Or=class extends Ua{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(xV()).subscribe(s=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:c}])=>c.id===s);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(Io(u));let d=this.player.calculateDurationFromSegments();d&&this.params.output.duration$.next(d/1e3)},r))}getPlayer(){return new Xo({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)}};import{assertNever as XV,assertNonNullable as JV,combine as ZV,debounce as e_,ErrorCategory as yE,filter as tp,filterChanged as _s,fromEvent as t_,isNonNullable as TE,isNullable as i_,map as Os,merge as Ns,observableFrom as lu,once as IE,Subscription as r_,throttle as a_}from"@vkontakte/videoplayer-shared/es2018";var SE=_(De(),1),Zd=_(ja(),1);var si=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Kd,assertNonNullable as qr,combine as Ur,ErrorCategory as Ze,filter as nu,filterChanged as Ds,flattenObject as Bs,fromEvent as Bt,getTraceSubscriptionMethod as NV,interval as Xd,isNonNullable as Vs,isNullable as gE,map as jr,merge as Wi,now as Jd,Subject as Vt,Subscription as vE,SubscriptionRemovable as FV,tap as qV,throttle as UV,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var Zo=_(De(),1),Hi=_(Ke(),1),eu=_(ja(),1);var hE=_(Lc(),1);import{assertNever as PV,ErrorCategory as lE,Subject as cE}from"@vkontakte/videoplayer-shared/es2018";var kV=18,dE=!1;try{dE=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=kV}catch(a){console.error(a)}var Hd=class{constructor(e,t=!1){this.bufferFull$=new cE;this.error$=new cE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:lE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};dE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:lE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:PV(t)}}},pE=Hd;var Qd=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as ni,assertNonNullable as Ce,ErrorCategory as Dt,fromEvent as Wd,getExponentialDelay as zd,isHigher as AV,isNonNullable as oi,isNullable as pe,now as Jo,once as RV,Subject as $V,Subscription as MV,ValueSubject as ji}from"@vkontakte/videoplayer-shared/es2018";var Rs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ji(0);this.currentLowLatencySegmentLength$=new ji(0);this.currentSegmentLength$=new ji(0);this.onLastSegment$=new ji(!1);this.fullyBuffered$=new ji(!1);this.playingRepresentation$=new ji(void 0);this.playingRepresentationInit$=new ji(void 0);this.error$=new $V;this.gaps=[];this.subscription=new MV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new te;this.switchAbortController=new te;this.destroyAbortController=new te;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=ni(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ce(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new pE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(Wd(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Wd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Dt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ee(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Qd(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).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),s=this.parsedInitData.get(t.id);Ce(i,"No init buffer for starting representation"),Ce(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=ni(this.destroyAbortController.signal,async function*(e,t=!1){if(!ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(pe(s)||pe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();oi(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=ni(this.destroyAbortController.signal,async function*(e,t=!1){if(!ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(pe(s)||pe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();oi(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=ni(this.destroyAbortController.signal,async function*(e){var u;let t=(0,eu.default)(e,l=>l.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let l of this.representations.keys()){let d=t.find(h=>h.id===l);d&&this.representations.set(l,d);let c=this.representations.get(l);if(!c||!Qe(c.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);Ce(r,`Representation not found by id ${i}`);let s=this.segments.get(i);Ce(s,"No segments for starting representation");let n=this.initData.get(i);if(Ce(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new te,ni(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ce(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(pe(o)||pe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Ce(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ee(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();oi(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(){!pe(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 te,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var p;if(pe(e)||pe(this.downloadingRepresentationId)||pe(this.playingRepresentationId)||pe(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer)||oi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Ce(t,`No such representation ${this.downloadingRepresentationId}`),Ce(i,`No such representation ${this.playingRepresentationId}`),pe(r)||pe(s))return;let n=r.find(h=>e>=h.time.from&&e<h.time.to);oi(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=this.getForwardBufferDuration(e),m=ti(i),f=ti(t),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&oi(m)&&oi(f)&&AV(m.quality,f.quality),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(v||g?o+=Math.min(h,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(p=[...this.segments.entries()].map(([y,w])=>{let R=w.find(L=>e>=L.time.from&&e<L.time.to);return{representationId:y,status:R==null?void 0:R.status}}).find(y=>y.status==="fed"))==null?void 0:p.representationId;T&&(this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Qd(this.sourceBuffer.buffered)>=this.bufferLimit){let h=this.getForwardBufferDuration(e),m=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<m).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Zo.default)(d,n))h="high";else{let m=(0,Hi.default)(d,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(d,t,h).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Hi.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 s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;oi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,eu.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,s;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,eu.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!Qe(n.segmentReference))return;let o=n.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),u=100,l=(i=this.segments.get(n.id))!=null?i:[],d=(s=(r=(0,Hi.default)(l,-1))==null?void 0:r.time.to)!=null?s:0,c=o==null?void 0:o.findIndex(p=>d>=p.time.from+u&&d<=p.time.to+u);if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(c+1);this.segments.set(n.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ce(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,Hi.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Qe(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),d=ut(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&_i&&_i(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_i&&_i(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:p,time:{from:h,to:m}},f)=>{let v=h<=i&&m>=i,g=h>i||v||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+S||r<S&&m-h>=S||m<=i+S;return(p==="none"||p==="partially_ejected"&&g&&T&&this.sourceBuffer&&ee(this.mediaSource,this.sourceBuffer)&&!(si(this.sourceBuffer.buffered,h)&&si(this.sourceBuffer.buffered,m)))&&g&&T});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=d||u<=c);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){Qe(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:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ni(o,async function*(){let d=zd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Jo(),!d)return;let c=new DataView(d),p=Fi(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),ot(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Qe(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:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ni(n,async function*(){let u=zd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Wd(window,"online").pipe(RV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Jo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ot(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Qe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Hi.default)(e,0).byte.from,to:(0,Hi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Jo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Dt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Qe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Jo();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Dt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Zo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!ee(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(s.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),d=Fi(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ee(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(s.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<r,m=c<=r;if(!h)continue;let f=Fi(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?v:f.parseFeedableSegmentChunk(v);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(pe(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer))){!this.isLive&&B.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(si(this.sourceBuffer.buffered,e.segment.time.from,100)&&si(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Dt.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",Dd(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Vi(()=>(0,hE.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?ni(this.destroyAbortController.signal,async function*(){let u=zd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Fi(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async u=>{if(!u)return;let{init:l,dataView:d,segments:c}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=c;this.isLive&&Qe(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=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Dt.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||!ee(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||pe(e))return!1;let r=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Dd(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)(0,Zo.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ee(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||!ee(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||!ee(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||pe(e)?0:ii(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let o=s.start(n)*1e3,u=s.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Vi(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:Dt.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(pe(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer)||pe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Dt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as $s,assertNever as mE,fromEvent as fE,merge as CV,now as Ms,Subject as Nr,ValueSubject as Gd,flattenObject as Fr,ErrorCategory as Cs,SubscriptionRemovable as LV}from"@vkontakte/videoplayer-shared/es2018";var iu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new Nr;this.firstBytesManifest$=new Nr;this.firstBytesRequested$=new Nr;this.firstBytesReceived$=new Nr;this.lastConnectionType$=new Gd(void 0);this.lastConnectionReused$=new Gd(void 0);this.lastRequestFirstBytes$=new Gd(void 0);this.recoverableError$=new Nr;this.error$=new Nr;this.abortAllController=new te;this.subscription=new LV;this.fetchManifest=$s(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Lo(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(tu);return r?(t.log("success",Fr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",Fr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=$s(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1,ignoreNetworkErrors:d=!1}={}){var G,H,E;let c=e,p=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let P=new URL(c,location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),c=P.toString();break}default:mE(t)}this.requestQuic&&(c=Zt(c));let m=this.abortAllController.signal,f;if(n){let P=new te;if(f=CV(fE(this.abortAllController.signal,"abort"),fE(n,"abort")).subscribe(()=>{try{P.abort()}catch(I){tu(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(I){tu(I)}m=P.signal}let v=0,g=Ms();h.log("startRequest",Fr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested$.next();let S=yield this.doFetch(c,{priority:s,headers:p,signal:m},{ignoreNetworkErrors:d}),T=Ms();if(!S)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if((G=this.throughputEstimator)==null||G.addRawRtt(T-g),!S.ok||!S.body){this.unsubscribeAbortSubscription(f);let P=`Fetch error ${S.status}: ${S.statusText}`;return h.error("error",{message:P}),h.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let P=Ms(),I={requestStartedAt:g,requestEndedAt:P,duration:P-g};return h.log("endRequest",Fr(I)),h.end(),S.arrayBuffer()}let y=S.body;if(o){let P;[y,P]=S.body.tee(),(H=this.throughputEstimator)==null||H.trackStream(P,u)}let w=y.getReader(),R,L=parseInt((E=S.headers.get("content-length"))!=null?E:"",10);Number.isFinite(L)&&(R=L),!R&&i&&(R=i.to-i.from+1);let $=R?new Uint8Array(R):new Uint8Array(0),D=!1,A=P=>{this.unsubscribeAbortSubscription(f),D=!0,tu(P)},V=$s(m,async function*({done:P,value:I}){if(v===0&&(this.lastRequestFirstBytes$.next(Ms()-g),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(f);return}if(!P&&I){if(l&&R)$.set(I,v),v+=I.byteLength;else{let x=new Uint8Array($.length+I.length);x.set($),x.set(I,$.length),$=x,v+=I.byteLength}r==null||r(new DataView($.buffer),v),yield w==null?void 0:w.read().then(V,A)}}.bind(this));yield w==null?void 0:w.read().then(V,A),this.unsubscribeAbortSubscription(f);let M=Ms(),q={failed:D,requestStartedAt:g,requestEndedAt:M,duration:M-g};return D?(h.error("endRequest",Fr(q)),h.end(),null):(h.log("endRequest",Fr(q)),h.end(),$.buffer)}.bind(this));this.fetchByteRangeRepresentation=$s(this.abortAllController.signal,async function*(e,t,i){var g;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),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 p=new DataView(c,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(g=e.indexRange)!=null?g:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=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;f=new DataView(S)}let v=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=$s(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=s}onHeadersReceived(e){let{type:t,reused:i}=Co(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:mE(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await Je(e,t);if(r.ok)return r;if(i!=null&&i.ignoreNetworkErrors)return;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Cs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Cs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Cs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Cs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:Cs.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},tu=a=>{if(!ot(a))throw a};import{isNullable as DV,ValueSubject as bE}from"@vkontakte/videoplayer-shared/es2018";var ui=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new bE(e.initial),this.debounced$=new bE(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Re(`raw_${t}`),this.smoothedSeries$=new Re(`smoothed_${t}`),this.reportedSeries$=new Re(`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),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(DV(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 ru=class extends ui{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=$t(this.slow,e,this.params.emaAlphaSlow),this.fast=$t(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var au=class extends ui{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=id(this.pastMeasures,this.takenMeasures);this.emaSmoothed=$t(this.emaSmoothed,e,this.params.emaAlpha);let i=jy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var su=class extends ui{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?$t(this.smoothed,t,this.params.emaAlpha):t}};var Qi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new ru({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new au({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 su({initial:e,label:"liveEdgeDelay",...t})}};var Yd=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as BV,ValueSubject as VV}from"@vkontakte/videoplayer-shared/es2018";var Ls=class a{constructor(e,t){this.currentRepresentation$=new VV(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!BV(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Qe(t.segmentReference))}};var jV=["timeupdate","progress","play","seeked","stalled","waiting"],HV=["timeupdate","progress","loadeddata","playing","seeked"];var ou=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new vE;this.subscriptionRemovable=new FV;this.representationSubscription=new vE;this.state$=new j("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new Vt;this.manifestRequested$=new Vt;this.firstBytesManifest$=new Vt;this.manifestReceived$=new Vt;this.firstBytesRequested$=new Vt;this.firstBytesReceived$=new Vt;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.currentLiveTextRepresentation$=new ae(null);this.isLive$=new ae(!1);this.isActiveLive$=new ae(!1);this.isLowLatency$=new ae(!1);this.liveDuration$=new ae(0);this.liveSeekableDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(0);this.liveStreamStatus$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLatency$=new ae(void 0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.currentStallDuration$=new ae(0);this.videoLastDataObtainedTimestamp$=new ae(0);this.fetcherRecoverableError$=new Vt;this.fetcherError$=new Vt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Vt;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new te;this.initManifest=Kd(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ee(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ze.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Kd(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ze.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=Oo(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(d){let c=(u=Mo(e))!=null?u:{id:"ManifestParsing",category:Ze.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(c)}if(!t)return null;let i=(d,c,p)=>{var h,m,f,v;return!!((m=(h=this.element)==null?void 0:h.canPlayType)!=null&&m.call(h,c)&&((v=(f=je())==null?void 0:f.isTypeSupported)!=null&&v.call(f,`${c}; codecs="${p}"`))||d==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:d,latestSegmentPublishTime:c,streamIsUnpublished:p,streamIsAlive:h}=t.live,m=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((c-d)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let f="active";if(h||(f=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(f),h&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let v=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(v).catch(g=>{this.error$.next({id:"updateManifest",category:Ze.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:g})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let d of["video","audio"]){let p=t.streams[d].filter(({mime:m,codecs:f})=>i(d,m,f));r[d]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let m=p.map(({codecs:f})=>f);d==="audio"&&(n=Ho(m),h=n[0]),d==="video"&&(s=jo(m),this.forceVideoCodec&&(0,SE.default)(s,this.forceVideoCodec)?h=this.forceVideoCodec:h=s[0]),h&&(r[d]=p.filter(({codecs:f})=>Lr(f)===h))}else{let m=new Set(p.map(({codecs:f})=>f));h=Uo(m),h&&(r[d]=p.filter(({codecs:f})=>f.startsWith(h)))}if(d==="video"){let m=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),v=r.video.some(g=>!g.hdr);B.display.isHDR&&m&&f?r.video=r.video.filter(g=>g.hdr):v&&(r.video=r.video.filter(g=>!g.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Bs(o)),o}.bind(this));this.initRepresentations=Kd(this.destroyController.signal,async function*(e,t,i){var c;this.tracer.log("initRepresentationsStart",Bs({initialVideo:e,initialAudio:t,sourceHls:i})),qr(this.manifest),qr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Bt(p,"error").pipe(nu(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Ze.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=kn();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),lr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Rs("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Vs(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Rs("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(Ls.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ls(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Wi(...HV.map(p=>Bt(this.element,p))).pipe(jr(p=>this.element?ii(this.element.buffered,this.element.currentTime*1e3):0),Ds(),qV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Wi(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ds()).subscribe(h=>this.liveStreamEndTimestamp=Jd())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:h}=this.tuning.dash;this.livePauseWatchdogSubscription=Xd(h).subscribe(m=>{let f=yn(this.manifestUrlString,2);this.manifestUrlString=Ee(this.manifestUrlString,f+h,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(Ur({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(jr(({isActiveLive:h,isLowLatency:m})=>h&&m),Ds()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Yd(this.element,1)})),this.representationSubscription.add(Ur({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(nu(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!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(Ur({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(nu(({isLive:h})=>h),Ds((h,m)=>m.bufferLength<h.bufferLength),jr(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let v=yn(this.manifestUrlString,2);return(h/2+m+f+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ur({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-v;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>g&&(y=1+Math.sign(T)*S),Yd(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var f,v;let m=0;if(h){let g=((v=(f=this.element)==null?void 0:f.currentTime)!=null?v:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var y,w;return(w=(y=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?w:g}))-g}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Ur({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(UV(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,v=yn(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,w=isFinite(h)?h:m,R=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let $="none";if(R?$="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),$="active_low_latency"):v!==0&&w<S?$="live_forward_buffering":w<S+y&&($="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),$==="live_forward_buffering"||$==="live_with_target_offset"){let D=p-(S+T),A=this.normalizeLiveOffset(Math.trunc(v+D/f)),V=Math.abs(A-v),M=0;!h||V<=this.tuning.dashCmafLive.offsetCalculationError?M=v:A>0&&V>this.tuning.dashCmafLive.offsetCalculationError&&(M=A),this.manifestUrlString=Ee(this.manifestUrlString,M,2)}($==="live_with_target_offset"||$==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Ze.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let u=Wi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(jr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=Wi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(jr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Ur({allBuffersFull:u,someBufferEnded:l}).pipe(Ds(),jr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),nu(p=>p));if(this.representationSubscription.add(Wi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Ze.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Wi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var f;if(((f=this.source)==null?void 0:f.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Ze.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(c=this.manifest.duration)!=null?c:0,...(0,Zd.default)((0,Zd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Vs(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Xd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ze.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new iu({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=Qi.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){qr(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"?Jd()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ee(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){var t,i,r;await((t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio)),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){qr(this.element),this.state$.setState("running"),this.subscription.add(Wi(...jV.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ze.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Bt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&si(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var y,w,R,L,$,D,A,V,M,q,G;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||((y=this.source)==null?void 0:y.readyState)!=="open")return;let d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let c={timeInWaiting:d},p=Jd(),h=100,m=(R=(w=this.videoBufferManager)==null?void 0:w.lastDataObtainedTimestamp)!=null?R:0;this.videoLastDataObtainedTimestamp$.next(m);let f=($=(L=this.audioBufferManager)==null?void 0:L.lastDataObtainedTimestamp)!=null?$:0,v=(A=(D=this.videoBufferManager)==null?void 0:D.getForwardBufferDuration())!=null?A:0,g=(M=(V=this.audioBufferManager)==null?void 0:V.getForwardBufferDuration())!=null?M:0,S=v<h&&p-m>r,T=this.audioBufferManager&&g<h&&p-f>r;if((!t||l)&&((S||T)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%s===0){let H=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(H),this.updateManifest()):this.seekLive(H).catch(E=>{this.error$.next({id:"stallIntervalCallback",category:Ze.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:E})}),c.liveLastOffset=H}else{let H=this.element.currentTime*1e3;(q=this.videoBufferManager)==null||q.maintain(H),(G=this.audioBufferManager)==null||G.maintain(H),c.position=H}this.tracer.log("stallIntervalCallback",Bs(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Xd(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ze.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;qr(this.element),qr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),si(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(gE(this.element)||gE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Bs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Vs(this.element)&&Vs(this.source)&&Vs(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=NV(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=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<=s&&l.to+o>s&&(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",Bs(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};import{combine as QV,map as WV,observeElementSize as zV,Subscription as GV,ValueSubject as ep,noop as YV}from"@vkontakte/videoplayer-shared/es2018";var uu=class{constructor(){this.subscription=new GV;this.pipSize$=new ep(void 0);this.videoSize$=new ep(void 0);this.elementSize$=new ep(void 0);this.pictureInPictureWindowRemoveEventListener=YV}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(zV(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(QV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(WV(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var zi=class{constructor(e){this.subscription=new r_;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new Pr;this.stallsManager=new Po;this.elementSizeManager=new uu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return XV(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new kr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Be(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ou({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;i_(this.observableVideo)&&(this.observableVideo=Oe(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:yE.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(tp(c=>!!c.length),IE()).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(Os(c=>c.to.state!=="none"),_s());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(tp(TE),IE()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Os(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(gt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Ge(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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"),k(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 p=this.player.getStreams(),h=this.player.getCodecs();if(JV(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let v of p.audio){f.push(Cd(v));let g=[];for(let S of v.representations){let T=Ts(S);g.push(T),this.audioTracksMap.set(T,{stream:v,representation:S})}this.audioStreamsMap.set(v,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of p.video){m.push(Ld(f));let v=[];for(let g of f.representations){let S=ti({...g,streamId:f.id});S&&(v.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,v)}this.params.output.availableVideoStreams$.next(m);for(let f of p.text)for(let v of f.representations){let g=WI(f,v);this.textTracksMap.set(g,{stream:f,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!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=Ns(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$,t_(this.video,"progress")).pipe(tp(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(a_(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,f]=h,v=[...this.videoTracksMap.keys()].find(S=>{var T;return((T=this.videoTracksMap.get(S))==null?void 0:T.representation.id)===m.id});TE(v)&&(this.stallsManager.lastVideoTrackSelected=v);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(m.id,f==null?void 0:f.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(ZV({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Ns(lu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Os(c=>c.to)))}).pipe(Os(({videoState:c,autoVideoTrackState:p})=>c.to!=="stopped"&&p),_s()).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(_s()).subscribe(c=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Ld(m));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(_s()).subscribe(c=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Cd(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Os(({to:c})=>c==="ready"),_s());this.subscription.add(Ns(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,lu(["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(Ns(l,this.player.state$.stateChangeEnded$,lu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Ns(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,lu(["init"])).pipe(e_(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var $,D,A,V,M,q,G,H,E,P,I,x,F;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?La:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?go:bo,i=this.params.tuning.useNewAutoSelectVideoTrack?yt:fo,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=($=r.videoTrack.getState())==null?void 0:$.id,u=[...this.videoTracksMap.keys()].find(({id:O})=>O===o),l=s.currentVideoTrack$.getValue(),d=((V=(A=r.videoStream.getState())!=null?A:u&&((D=this.videoTracksMap.get(u))==null?void 0:D.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=[...this.videoStreamsMap.keys()].find(({id:O})=>O===d.id),p=c&&this.videoStreamsMap.get(c);if(!p)return;let h=ii(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 f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(h/Math.min(m,f||1/0),1),g=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(q=[...this.audioStreamsMap.keys()].find(({id:O})=>O===(g==null?void 0:g.id)))!=null?q:this.audioStreamsMap.keys().next().value,T=0;if(S){if(u&&!n){let O=e(u,p,(G=this.audioStreamsMap.get(S))!=null?G:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(H=O==null?void 0:O.bitrate)!=null?H:-1/0)}if(l){let O=e(l,p,(E=this.audioStreamsMap.get(S))!=null?E:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(P=O==null?void 0:O.bitrate)!=null?P:-1/0)}}let y=u;(n||!y)&&(y=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,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 w=S&&t(y,p,(I=this.audioStreamsMap.get(S))!=null?I:[],{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}),R=(x=this.videoTracksMap.get(y))==null?void 0:x.representation,L=w&&((F=this.audioTracksMap.get(w))==null?void 0:F.representation);if(R&&L)return[R,L];if(R&&!L&&this.audioTracksMap.size===0)return[R,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:yE.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),Ve(this.video),this.tracer.end()}};var Fs=class extends zi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ip,merge as EE,filter as wE,filterChanged as xE,isNullable as rp,map as PE,ValueSubject as ap,isNonNullable as s_}from"@vkontakte/videoplayer-shared/es2018";var qs=class extends zi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new ap(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(xE()).subscribe(u=>{let l=i.position$.getValue(),d=i.volume$.getValue(),c=!d.volume||d.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(s.isLowLatency.stateChangeEnded$.pipe(PE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(ip({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(PE(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u*1e3+l+t:void 0)).subscribe(i.liveTime$)).add(ip({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:EE(r.playbackRateState$,new ap(1))}).pipe(wE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let d=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-p||this.video.paused||rp(d)||(t=u-d)})).add(ip({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:EE(r.playbackRateState$,new ap(1))}).pipe(xE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:d})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&d>=1-p||rp(u)||rp(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=zI(u);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(wE(u=>s_(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 kE="X-Playback-Duration",sp=async a=>{var r;let e=await Je(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(kE)?parseInt(e.headers.get(kE),10):void 0};import{assertNever as b_,combine as g_,debounce as v_,ErrorCategory as pu,filter as S_,filterChanged as y_,isNonNullable as $E,isNullable as hu,map as ME,merge as T_,observableFrom as I_,Subscription as E_,ValueSubject as up,VideoQuality as w_}from"@vkontakte/videoplayer-shared/es2018";var op=_(zl(),1);import{videoSizeToQuality as n_,getExponentialDelay as o_}from"@vkontakte/videoplayer-shared/es2018";var u_=a=>{let e=null;if(a.QUALITY&&(e=Kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=n_({width:t,height:i})}return e!=null?e:null},l_=(a,e)=>{var s,n;let t=a.split(`
|
|
179
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,op.default)(l[1].split(",").map(S=>S.split("="))),p=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,h=u_(c),m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let f=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,v;if(c.RESOLUTION){let[S,T]=c.RESOLUTION.split("x").map(y=>parseInt(y,10));S&&T&&(v={width:S,height:T})}let g=new URL(t[++o],e).toString();h&&i.push({id:p,quality:h,url:g,bandwidth:m,size:v,fps:f})}if(d){let c=(0,op.default)(d[1].split(",").map(f=>{let v=f.indexOf("=");return[f.substring(0,v),f.substring(v+1)]}).map(([f,v])=>[f,v.replace(/^"|"$/g,"")])),p=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,m=c.NAME;p&&h&&r.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},c_=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),np=0,AE=async(a,e=a,t,i)=>{let s=await(await Je(a,i)).text();np+=1;try{let{qualityManifests:n,textTracks:o}=l_(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(np<=t.manifestRetryMaxCount)return await c_(o_(np-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),AE(a,e,t)}return{qualityManifests:[],textTracks:[]}},cu=AE;import{isNonNullable as d_,Subscription as p_,throttle as h_,ValueSubject as RE,Subject as m_,ErrorCategory as f_}from"@vkontakte/videoplayer-shared/es2018";var du=class{constructor(e,t,i,r,s){this.subscription=new p_;this.abortControllers={destroy:new te,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new RE(null);this.getCurrentTime$=new RE(null);this.error$=new m_;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(h_(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 Je(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
180
|
+
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-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),s=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(d_(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 te;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:f_.WTF,thrown:t,message:e})}};var Us=class{constructor(e){this.subscription=new E_;this.videoState=new j("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new up([]);this.liveOffset=new Ci;this.manifestStartTime$=new up(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return b_(t)}};var i;this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:w_.INVARIANT,url:this.params.source.url};let t=(r,s)=>cu(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new du(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:pu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:pu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new up((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:pu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ge(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(y_(),ME(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&$E(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(we(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(g_({startTime:this.manifestStartTime$.pipe(S_($E)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(ME(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=T_(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,I_(["init"])).pipe(v_(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Ve(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(hu(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[p,h]of[[d,"mq"],[c,"lq"]]){let m=String(parseFloat(p||""));h&&p&&r.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ee(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),sp(n).then(d=>{var c;if(!hu(d))this.maxSeekBackTime$.next(d);else{let p=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(hu(p)||!isFinite(p))&&Je(n).then(h=>h.text()).then(h=>{var f;let m=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(m){let v=new URL(m,n).toString();sp(v).then(g=>{hu(g)||this.maxSeekBackTime$.next(g)})}}).catch(()=>{})}})}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pu.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=Ee(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as x_,debounce as P_,ErrorCategory as lp,fromEvent as cp,isNonNullable as k_,isNullable as A_,map as CE,merge as LE,observableFrom as DE,Subscription as R_,ValueSubject as BE,VideoQuality as $_}from"@vkontakte/videoplayer-shared/es2018";var js=class{constructor(e){this.subscription=new R_;this.videoState=new j("stopped");this.manifests$=new BE([]);this.unmuteAfterBrowserResetsHappened=new BE(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);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==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return x_(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:$_.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),cu(Ee(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:lp.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:lp.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(CE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(gt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ge(this.video,t.playbackRate,r.playbackRateState$,i)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&k_(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(v=>v.id===m);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(we(f.url)))}let c=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(c!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(CE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!B.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(LE(cp(o,"addtrack"),cp(o,"removetrack"),cp(o,"change"),DE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=LE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,DE(["init"])).pipe(P_(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ve(this.video)}prepare(){var s,n;let e=this.selectManifest();if(A_(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lp.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var OE=_(zt(),1),dp=_(Ei(),1),NE=_(Ke(),1);import{assertNever as M_,assertNonNullable as VE,debounce as C_,ErrorCategory as _E,isHigherOrEqual as L_,isLowerOrEqual as D_,isNonNullable as B_,merge as V_,observableFrom as __,Subscription as O_,map as N_}from"@vkontakte/videoplayer-shared/es2018";var Hs=class{constructor(e){this.subscription=new O_;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new Ye;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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return M_(e)}};this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),(0,OE.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,dp.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:_E.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(N_(o=>o.to)),this.params.output.playbackState$),this.subscription.add(gt(this.video,t.isLooped,i)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ge(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&B_(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=V_(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,__(["init"])).pipe(C_(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),Ve(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;VE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];VE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Zt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(we(t))}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_E.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let p=yt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(p)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,dp.default)(this.trackUrls).map(c=>c.track);if(!r||!s||Ir(e,n[0].quality,(d=(0,NE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?D_(r,e.max):!0,u=e.min?L_(r,e.min):!0;o&&u||i(e)}};import{assertNever as qE,debounce as j_,merge as UE,observableFrom as H_,Subscription as Q_,map as jE,ValueSubject as W_,ErrorCategory as hp,VideoQuality as z_}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as F_}from"@vkontakte/videoplayer-shared/es2018";var FE=["stun:videostun.mycdn.me:80"],q_=1e3,U_=3,pp=()=>null,mu=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=pp;this.externalStopCallback=pp;this.externalErrorCallback=pp;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:FE}]};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:F_.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),q_)}normalizeOptions(e={}){let t={stunServerList:FE,maxRetryNumber:U_,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Qs=class{constructor(e){this.videoState=new j("stopped");this.maxSeekBackTime$=new W_(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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return qE(e)}};this.subscription=new Q_,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Be(e.container,e.tuning),this.liveStreamClient=new mu(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),Ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:hp.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(UE(this.videoState.stateChangeStarted$.pipe(jE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(jE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(Xe(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(_e(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 qE(n.to)}},i)).add(UE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,H_(["init"])).pipe(j_(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:z_.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.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:hp.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hp.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Hr=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}};import{assertNever as zs,assertNonNullable as _t,ErrorCategory as fu,filter as YE,isNonNullable as KE,isNullable as eO,map as tO,merge as iO,once as rO,Subject as se,Subscription as XE,ValueSubject as U,flattenObject as mp,devNull as aO,getWindow as sO}from"@vkontakte/videoplayer-shared/es2018";import{Observable as G_,map as HE,Subscription as Y_,Subject as K_}from"@vkontakte/videoplayer-shared/es2018";var QE=a=>new G_(e=>{let t=new Y_,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(HE(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(HE(({type:l})=>l!==void 0)),n=new K_,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval),N({m:"hangup.set",l,id:o})})),t.add(r.subscribe(()=>{N({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(N({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval),N({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as X_,Subscription as J_,combine as Z_,filter as zE,once as GE}from"@vkontakte/videoplayer-shared/es2018";function WE(){return new(window.AudioContext||window.webkitAudioContext)}var Ws=class Ws{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new te;this.subscriptions=new J_;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(zE(s=>!!s.type),GE()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){B.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(Z_({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(zE(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),GE()).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=WE();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 s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Ws.errorId,category:X_.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ws.errorId} exception`,thrown:e})}};Ws.errorId="VolumeMultiplierManager";var Qr=Ws;var nO={chunkDuration:5e3,maxParallelRequests:5},Gs=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new se;this.noAvailableProvidersError$=new se;this.volumeMultiplierError$=new se;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableVideoCodecs$:new U([]),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),availableAudioCodecs$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),currentNativeBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new se,fetcherError$:new se,fetcherRecoverableError$:new se,warning$:new se,willSeekEvent$:new se,soundProhibitedEvent$:new se,seekedEvent$:new se,loopedEvent$:new se,endedEvent$:new se,manifestRequested$:new se,firstBytesManifest$:new se,manifestReceived$:new se,firstBytesRequested$:new se,firstBytesReceived$:new se,firstBytesEvent$:new se,loadedMetadataEvent$:new se,firstFrameEvent$:new se,canplay$:new se,isLive$:new U(void 0),isLiveEnded$:new U(null),canPlayLiveTailBuffer$:new U(!1),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new se,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new XE;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=vl([...BI(this.params.tuning),...DI(this.params.tuning)]).filter(l=>KE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,fp.default)(r,l)),...t.filter(l=>(0,fp.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",mp(s)),this.screenFormatsIterator=new Hr(s);let n=[...Rd(!0),...Rd(!1)];this.chromecastFormatsIterator=new Hr(n.filter(l=>KE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Qr.isSupported()&&(this.volumeMultiplierManager=new Qr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){N.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 Hr(e))}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(eO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:fu.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return zs(e)}}createScreenProvider(e){var u,l,d;let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let c=this.applyFailoverHost(t[e]),p=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return _t(c),this.params.tuning.useDashProviderVirtual&&!B.device.isMobile?new Or({...o,source:c,sourceHls:p,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&B.device.isMobile?new Or({...o,source:c,sourceHls:p,forceVideoCodec:(l=this.videoCodecsIterator)==null?void 0:l.getValue()}):new Fs({...o,source:c,sourceHls:p,forceVideoCodec:(d=this.videoCodecsIterator)==null?void 0:d.getValue()})}case"DASH_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return _t(c),new qs({...o,source:c})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let c=this.applyFailoverHost(t[e]);return _t(c),new js({...o,source:c})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return _t(c),new Us({...o,source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let c=this.applyFailoverHost(t[e]);return _t(c),new Hs({...o,source:c})}case"DASH_LIVE":{let c=this.applyFailoverHost(t[e]);return _t(c),new _y({...o,source:c,config:{...nO,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let c=this.applyFailoverHost(t[e]);return _t(c),new Qs({container:i,source:c,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return zs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o={meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof kt){let{chromecastConnector:l}=this.params.dependencies.chromecastInitializer;return _t(l),new da({...o,chromecastConnector:l})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return _t(u),new ka({...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 zs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return zs(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 zs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,JE.default)((0,bp.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new XE,t=!1,i=0;e.add(iO(this.providerOutput.error$.pipe(YE(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),QE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(tO(s=>({id:`ProviderHangup:${s}`,category:fu.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let s=this.params.desiredState.playbackState.transitionEnded$.pipe(YE(({to:n})=>n==="playing"),rO()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=N.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&sO().console.log(`===== DASH_LIVE DEBUG START ====
|
|
181
181
|
`,s.map(({time:u,data:l,stack:d})=>`${u}: ${JSON.stringify(l)}${d?`
|
|
182
182
|
`+d:""}`).join(`
|
|
183
183
|
`),`
|
|
184
|
-
===== DASH_LIVE DEBUG END ====`),o){let u=s.reduce((l,{time:d,data:c,stack:p})=>{let h=(0,Ph.default)(c).map(([f,m])=>`${f}:${m}`).join(",");return l+=`${d}: ${h}${p?`: ${p}`:""};`,l},"");gF.push("core",{key:"vp_dash_live_debug",strings:[u]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(q({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{q({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(s=>{let n=this.current$.getValue().destination,o={error:s,currentDestination:n};if(n==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=s.category===ll.NETWORK,l=s.category===ll.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!l,p=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=d&&!l&&(u&&t||!c);o={...o,isNetworkError:u,isFatalError:l,haveFailoverHost:d,tryFailover:h,canReinitProvider:c},c?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(n!=null?n:"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",wh(o)):this.tracer.error("providerError",wh(o))})),e}};import{fromEvent as cl,once as yF,combine as TF,Subscription as Dx,ValueSubject as kh,map as Bx,filter as IF,isNonNullable as dl,now as at,safeStorage as Ah,getWindow as EF}from"@vkontakte/videoplayer-shared/es2018";var wF=5e3,Cx="one_video_throughput",Vx="one_video_rtt",$h=()=>{let{navigator:a}=EF();if(a)return a.connection},_x=()=>{var e;let a=(e=$h())==null?void 0:e.downlink;if(dl(a)&&a!==10)return a*1e3},Ox=()=>{var e;let a=(e=$h())==null?void 0:e.rtt;if(dl(a)&&a!==3e3)return a},Nx=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Rh=class a{constructor(e){this.subscription=new Dx;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(Cx)||(e.useBrowserEstimation?_x():void 0)||wF,i=(s=(r=a.load(Vx))!=null?r:e.useBrowserEstimation?Ox():void 0)!=null?s:0;if(this.throughput$=new kh(t),this.rtt$=new kh(i),this.rttAdjustedThroughput$=new kh(Nx(t,i,e.rttPenaltyRequestSize)),this.throughput=Kt.getSmoothedValue(t,-1,e),this.rtt=Kt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let l=_x();l&&this.throughput.next(l);let d=Ox();dl(d)&&this.rtt.next(d)},o=$h();o&&"onchange"in o&&this.subscription.add(cl(o,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Ah.set(Cx,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Ah.set(Vx,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(Bx(n=>Math.round(n))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(TF({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Bx(({throughput:n,rtt:o})=>Nx(n,o,e.rttPenaltyRequestSize)),IF(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=at(),r=new Dx;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(cl(e,"progress").pipe(yF()).subscribe(s=>{t=s.loaded,i=at()}));break;case 1:case 0:r.add(cl(e,"loadstart").subscribe(()=>{t=0,i=at()}));break}r.add(cl(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=at(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=at(),n=0,o=at(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,at()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=at();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,s=at()}else n+=c.byteLength;o=at()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&at()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,at()-o,this.concurrentDownloads.size),n=0,o=at());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=Ah.get(e);if(dl(t))return(i=parseInt(t,10))!=null?i:void 0}},Fx=Rh;import{fillWithDefault as xF,VideoQuality as pl}from"@vkontakte/videoplayer-shared/es2018";var PF={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:pl.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:pl.Q_720P,trafficSavingLimit:pl.Q_480P},stallsManager:{enabled:!1,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:pl.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},Ux=a=>xF(a,PF);import{assertNonNullable as Dh,combine as ti,ErrorCategory as hl,filter as Se,filterChanged as J,fromEvent as Bh,isNonNullable as Qx,isNullable as _F,Logger as OF,map as K,mapTo as Gx,merge as Ri,now as fl,once as Ee,Subject as G,Subscription as Yx,tap as Ch,ValueSubject as V,isHigher as NF,isInvariantQuality as Kx,flattenObject as $i,throttle as Vh,getTraceSubscriptionMethod as Xx,TracerFactory as FF,InternalsExposure as UF,getPlayerId as qF,devNull as ml}from"@vkontakte/videoplayer-shared/es2018";import{merge as kF,map as AF,filter as qx,isNonNullable as RF}from"@vkontakte/videoplayer-shared/es2018";var Mh=({seekState:a,position$:e})=>kF(a.stateChangeEnded$.pipe(AF(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),qx(RF)),e.pipe(qx(()=>a.getState().state==="none")));import{assertNonNullable as $F}from"@vkontakte/videoplayer-shared/es2018";var jx=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return $F(e,`Wrong container or containerId {${a.container}}`),e};import{filter as MF,once as LF}from"@vkontakte/videoplayer-shared/es2018";var Hx=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(MF(r=>r.length>0),LF()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var Wx=O(pi(),1);import{devNull as DF,getWindow as Lh}from"@vkontakte/videoplayer-shared/es2018";var zx=()=>{let a="mediaCapabilities"in Lh().navigator?BF:CF,e=Dt(async()=>{let t=await Promise.all((0,Wx.default)(VF).map(async([r,s])=>({codec:r,supported:await a(s)}))),i=[C.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return DF.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>lt(e)},BF=async a=>{if(!a)return Promise.resolve({supported:!1});let e={["channels"in a?"audio":"video"]:a};return await Lh().navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},CF=a=>{var i;if(!a)return Promise.resolve({supported:!1});let e=Lh().document,t="channels"in a?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType((i=a==null?void 0:a.contentType)!=null?i:"")==="probably"})},VF={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var bl=class{constructor(e={},t=FF.createRootTracer(!1),i){this.subscription=new Yx;this.logger=new OF;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new V(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new V(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),isLowLatency:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({x:0,y:0})};this.info={playbackState$:new V(void 0),position$:new V(0),duration$:new V(1/0),muted$:new V(!1),volume$:new V(1),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableQualities$:new V([]),availableQualitiesFps$:new V({}),currentQuality$:new V(void 0),isAutoQualityEnabled$:new V(!0),autoQualityLimitingAvailable$:new V(!1),autoQualityLimits$:new V({}),predefinedQualityLimitType$:new V("unknown"),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),isAudioAvailable$:new V(!0),currentPlaybackRate$:new V(1),currentBuffer$:new V({start:0,end:0}),currentNativeBuffer$:new V({start:0,end:0}),isBuffering$:new V(!0),isStalled$:new V(!1),isEnded$:new V(!1),isLooped$:new V(!1),isLive$:new V(void 0),isLiveEnded$:new V(null),canPlayLiveTailBuffer$:new V(!1),canChangePlaybackSpeed$:new V(void 0),atLiveEdge$:new V(void 0),atLiveDurationEdge$:new V(void 0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),currentFormat$:new V(void 0),availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),throughputEstimation$:new V(void 0),rttEstimation$:new V(void 0),videoBitrate$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),surface$:new V("none"),chromecastState$:new V("NOT_AVAILABLE"),chromecastDeviceName$:new V(void 0),intrinsicVideoSize$:new V(void 0),availableSources$:new V(void 0),is3DVideo$:new V(!1),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0)};this.events={inited$:new G,ready$:new G,started$:new G,playing$:new G,paused$:new G,stopped$:new G,willReady$:new G,willStart$:new G,willResume$:new G,willPause$:new G,willStop$:new G,willDestruct$:new G,watchCoverageRecord$:new G,watchCoverageLive$:new G,managedError$:new G,fatalError$:new G,fetcherRecoverableError$:new G,ended$:new G,looped$:new G,seeked$:new G,willSeek$:new G,autoplaySoundProhibited$:new G,manifestRequested$:new G,firstBytesManifest$:new G,manifestReceived$:new G,firstBytesRequested$:new G,firstBytesReceived$:new G,firstBytes$:new G,loadedMetadata$:new G,firstFrame$:new G,canplay$:new G,log$:new G,fetcherError$:new G,severeStallOccured$:new G};this.experimental={element$:new V(void 0),enableDebugTelemetry$:new V(!1),dumpTelemetry:mT,getCurrentTime$:new V(null)};this.initLogs(),this.tuning=Ux(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,_h.default)(this.info).forEach(s=>s.setSuppressErrors(!0)),(0,_h.default)(this.events).forEach(s=>s.setSuppressErrors(!0)));let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new Ut(r):new bo(r),this.throughputEstimator=new Fx(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new UF("core",qF(i==null?void 0:i.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i==null?void 0:i.onDevNullLog,ml.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,n,o)=>{let u=Reflect.get(s,n,o);return typeof u!="function"?u:(...l)=>{try{return u.apply(s,l)}catch(d){let c=l.map(f=>JSON.stringify(f,(m,g)=>{let b=typeof g;return(0,Jx.default)(["number","string","boolean"],b)?g:g===null?null:`<${b}>`})),p=`Player.${String(n)}`,h=`Exception calling ${p} (${c.join(", ")})`;throw this.events.fatalError$.next({id:p,category:hl.WTF,message:h,thrown:d}),d}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,d;let{container:n,...o}=e;this.tracer.log("initVideo",$i(o)),this.domContainer=jx(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Wn({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0),this.devNullLog&&this.tuning.devNullLogEnabled?(ml.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=zx())):ml.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?C.isInited$.pipe(Se(n=>!!n),Ee()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Bh(document,"visibilitychange").pipe(Ee()).subscribe(r)):r(),this}destroy(){var e,t,i;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy(),ml.destroy("core"),(i=this.collectDecodingInfoDestroyCb)==null||i.call(this)}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(Se(t=>!!t),Ee()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Ut)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Ut)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{Dh(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Se(i=>i.length>0),Ee()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",$i(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",$i(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{var t;Hx(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(_F(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Qx(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ri(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(K(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(K(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(K(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(K(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(K(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(gT(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Se(({from:e})=>e==="stopped"),Ee()).subscribe(()=>{this.initedAt=fl(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",$i(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:hl.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ee()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",$i(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(K(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(K(n=>n.destination),J()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ti({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(K(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>Kx(u)?1:Kx(l)?-1:NF(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(J()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(Se(n=>Qx(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(J((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(J((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(J()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(J()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(J()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(K(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(K(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Ch(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(ti({hasLiveOffsetByPaused:Ri(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(K(n=>n.to),J(),K(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(ti({atLiveEdge:ti({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Mh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(K(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),J(),Ch(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(K(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(ti({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(K(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),J(),Ch(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(K(n=>n.muted),J()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(K(n=>n.volume),J()).subscribe(this.info.volume$)).add(Mh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(Ri(e.providerOutput.endedEvent$.pipe(Gx(!0)),e.providerOutput.seekedEvent$.pipe(Gx(!1))).pipe(J()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(K(n=>({id:n?`No${n}`:"NoProviders",category:hl.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(Ee()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(Ee()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(Ee()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(Ee()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(Ee()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(Ee(),K(n=>n!=null?n:fl()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ee(),K(()=>fl()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ee(),K(()=>fl()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new V(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new V(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Se(({to:n})=>n==="playing"),Ee()).subscribe(()=>i.next(!1)));let r=0,s=Ri(e.providerOutput.isBuffering$,t,i).pipe(K(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),J());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Ri(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ri(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(K(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Yx;this.subscription.add(t),this.subscription.add(e.current$.pipe(J((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Se(i=>i.length>0),Ee()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=ut(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Ri(this.desiredState.videoTrack.stateChangeStarted$.pipe(K(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(K(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(K(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(K(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(K(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(K(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(K(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(K(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(K(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Dh(this.providerContainer),Dh(e),fT(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>hT(i)),this.providerContainer.current$.subscribe(({type:i})=>ga("provider",i)),e.duration$.subscribe(i=>ga("duration",i)),e.availableVideoTracks$.pipe(Se(i=>!!i.length),Ee()).subscribe(i=>ga("tracks",i)),this.events.fatalError$.subscribe(new Ue("fatalError")),this.events.managedError$.subscribe(new Ue("managedError")),e.position$.subscribe(new Ue("position")),e.currentVideoTrack$.pipe(K(i=>i==null?void 0:i.quality)).subscribe(new Ue("quality")),this.info.currentBuffer$.subscribe(new Ue("buffer")),e.isBuffering$.subscribe(new Ue("isBuffering"))].forEach(i=>this.subscription.add(i)),ga("codecs",C.video.supportedCodecs)}initTracerSubscription(){let e=Xx(this.tracer.log.bind(this.tracer)),t=Xx(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(J()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ti({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Se(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),J((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(Se(i=>i>0),J()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(Se(i=>i>0),J()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ti({currentBuffer:this.info.currentBuffer$.pipe(Se(i=>i.end>0),J((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(J())}).pipe(Vh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(J()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(J()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(J()).subscribe(e("canChangePlaybackSpeed"))).add(ti({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Se(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Vh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(J(),Se(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(J(),Se(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(J()).subscribe(e("muted"))).add(this.info.volume$.pipe(J()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(J(),Se(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ti({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Se(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Vh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(J(),Se(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:hl.DOM,message:String(r)})})};this.subscription.add(Ri(Bh(document,"visibilitychange"),Bh(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",$i({quality:t,availableTracks:$i(e),track:$i(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ia()}};import{Subscription as gne,Observable as Sne,Subject as vne,ValueSubject as yne,VideoQuality as Tne}from"@vkontakte/videoplayer-shared/es2018";var Ine=`@vkontakte/videoplayer-core@${wf}`;export{_s as ChromecastState,Il as HttpConnectionType,Sne as Observable,ke as PlaybackState,bl as Player,no as PredefinedQualityLimits,Ine as SDK_VERSION,vne as Subject,gne as Subscription,El as Surface,wf as VERSION,yne as ValueSubject,Nt as VideoFormat,Tne as VideoQuality,$R as areValidLiveRecordSources,C as clientChecker,Wi as isMobile};
|
|
184
|
+
===== DASH_LIVE DEBUG END ====`),o){let u=s.reduce((l,{time:d,data:c,stack:p})=>{let h=(0,bp.default)(c).map(([m,f])=>`${m}:${f}`).join(",");return l+=`${d}: ${h}${p?`: ${p}`:""};`,l},"");aO.push("core",{key:"vp_dash_live_debug",strings:[u]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(N({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{N({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(s=>{let n=this.current$.getValue().destination,o={error:s,currentDestination:n};if(n==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=s.category===fu.NETWORK,l=s.category===fu.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!l,p=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=d&&!l&&(u&&t||!c);o={...o,isNetworkError:u,isFatalError:l,haveFailoverHost:d,tryFailover:h,canReinitProvider:c},c?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(n!=null?n:"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",mp(o)):this.tracer.error("providerError",mp(o))})),e}};import{fromEvent as bu,once as oO,combine as uO,Subscription as ZE,ValueSubject as gp,map as ew,filter as lO,isNonNullable as gu,now as We,safeStorage as vp,getWindow as cO}from"@vkontakte/videoplayer-shared/es2018";var dO=5e3,tw="one_video_throughput",iw="one_video_rtt",yp=()=>{let{navigator:a}=cO();if(a)return a.connection},rw=()=>{var e;let a=(e=yp())==null?void 0:e.downlink;if(gu(a)&&a!==10)return a*1e3},aw=()=>{var e;let a=(e=yp())==null?void 0:e.rtt;if(gu(a)&&a!==3e3)return a},sw=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Sp=class a{constructor(e){this.subscription=new ZE;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(tw)||(e.useBrowserEstimation?rw():void 0)||dO,i=(s=(r=a.load(iw))!=null?r:e.useBrowserEstimation?aw():void 0)!=null?s:0;if(this.throughput$=new gp(t),this.rtt$=new gp(i),this.rttAdjustedThroughput$=new gp(sw(t,i,e.rttPenaltyRequestSize)),this.throughput=Qi.getSmoothedValue(t,-1,e),this.rtt=Qi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let l=rw();l&&this.throughput.next(l);let d=aw();gu(d)&&this.rtt.next(d)},o=yp();o&&"onchange"in o&&this.subscription.add(bu(o,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{vp.set(tw,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{vp.set(iw,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(ew(n=>Math.round(n))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(uO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(ew(({throughput:n,rtt:o})=>sw(n,o,e.rttPenaltyRequestSize)),lO(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=We(),r=new ZE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(bu(e,"progress").pipe(oO()).subscribe(s=>{t=s.loaded,i=We()}));break;case 1:case 0:r.add(bu(e,"loadstart").subscribe(()=>{t=0,i=We()}));break}r.add(bu(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=We(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=We(),n=0,o=We(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,We()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=We();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,s=We()}else n+=c.byteLength;o=We()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&We()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,We()-o,this.concurrentDownloads.size),n=0,o=We());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=vp.get(e);if(gu(t))return(i=parseInt(t,10))!=null?i:void 0}},nw=Sp;import{fillWithDefault as pO,VideoQuality as vu}from"@vkontakte/videoplayer-shared/es2018";var ow={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:vu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:vu.Q_720P,trafficSavingLimit:vu.Q_480P},stallsManager:{enabled:!1,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:vu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},uw=a=>{var e;return{...pO(a,ow),configName:[...(e=a.configName)!=null?e:[],...ow.configName]}};import{assertNonNullable as Ep,combine as Ot,ErrorCategory as Su,filter as he,filterChanged as K,fromEvent as wp,isNonNullable as mw,isNullable as EO,Logger as wO,map as z,mapTo as fw,merge as li,now as yu,once as ve,Subject as Q,Subscription as bw,tap as xp,ValueSubject as C,isHigher as xO,isInvariantQuality as gw,flattenObject as ci,throttle as Pp,getTraceSubscriptionMethod as vw,TracerFactory as PO,InternalsExposure as kO,getPlayerId as AO,devNull as Tu}from"@vkontakte/videoplayer-shared/es2018";import{merge as hO,map as mO,filter as lw,isNonNullable as fO}from"@vkontakte/videoplayer-shared/es2018";var Tp=({seekState:a,position$:e})=>hO(a.stateChangeEnded$.pipe(mO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),lw(fO)),e.pipe(lw(()=>a.getState().state==="none")));import{assertNonNullable as bO}from"@vkontakte/videoplayer-shared/es2018";var cw=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return bO(e,`Wrong container or containerId {${a.container}}`),e};import{filter as gO,once as vO}from"@vkontakte/videoplayer-shared/es2018";var dw=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(gO(r=>r.length>0),vO()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var pw=_(zt(),1);import{devNull as SO,getWindow as Ip}from"@vkontakte/videoplayer-shared/es2018";var hw=()=>{let a="mediaCapabilities"in Ip().navigator?yO:TO,e=Vi(async()=>{let t=await Promise.all((0,pw.default)(IO).map(async([r,s])=>({codec:r,supported:await a(s)}))),i=[B.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return SO.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>_i(e)},yO=async a=>{if(!a)return Promise.resolve({supported:!1});let e={["channels"in a?"audio":"video"]:a};return await Ip().navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},TO=a=>{var i;if(!a)return Promise.resolve({supported:!1});let e=Ip().document,t="channels"in a?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType((i=a==null?void 0:a.contentType)!=null?i:"")==="probably"})},IO={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var Iu=class{constructor(e={configName:[]},t=PO.createRootTracer(!1),i){this.subscription=new bw;this.logger=new wO;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new C(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new C(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),isLowLatency:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({x:0,y:0})};this.info={playbackState$:new C(void 0),position$:new C(0),duration$:new C(1/0),muted$:new C(!1),volume$:new C(1),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableQualities$:new C([]),availableQualitiesFps$:new C({}),currentQuality$:new C(void 0),isAutoQualityEnabled$:new C(!0),autoQualityLimitingAvailable$:new C(!1),autoQualityLimits$:new C({}),predefinedQualityLimitType$:new C("unknown"),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),isAudioAvailable$:new C(!0),currentPlaybackRate$:new C(1),currentBuffer$:new C({start:0,end:0}),currentNativeBuffer$:new C({start:0,end:0}),isBuffering$:new C(!0),isStalled$:new C(!1),isEnded$:new C(!1),isLooped$:new C(!1),isLive$:new C(void 0),isLiveEnded$:new C(null),canPlayLiveTailBuffer$:new C(!1),canChangePlaybackSpeed$:new C(void 0),atLiveEdge$:new C(void 0),atLiveDurationEdge$:new C(void 0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),liveLatency$:new C(void 0),currentFormat$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),throughputEstimation$:new C(void 0),rttEstimation$:new C(void 0),videoBitrate$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),surface$:new C("none"),chromecastState$:new C("NOT_AVAILABLE"),chromecastDeviceName$:new C(void 0),intrinsicVideoSize$:new C(void 0),availableSources$:new C(void 0),is3DVideo$:new C(!1),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0)};this.events={inited$:new Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willReady$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,fetcherRecoverableError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,autoplaySoundProhibited$:new Q,manifestRequested$:new Q,firstBytesManifest$:new Q,manifestReceived$:new Q,firstBytesRequested$:new Q,firstBytesReceived$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q,fetcherError$:new Q,severeStallOccured$:new Q};this.experimental={element$:new C(void 0),tuningConfigName$:new C([]),enableDebugTelemetry$:new C(!1),dumpTelemetry:sy,getCurrentTime$:new C(null)};this.initLogs(),this.tuning=uw(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,kp.default)(this.info).forEach(s=>s.setSuppressErrors(!0)),(0,kp.default)(this.events).forEach(s=>s.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName);let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new kt(r):new Sn(r),this.throughputEstimator=new nw(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new kO("core",AO(i==null?void 0:i.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i==null?void 0:i.onDevNullLog,Tu.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,n,o)=>{let u=Reflect.get(s,n,o);return typeof u!="function"?u:(...l)=>{try{return u.apply(s,l)}catch(d){let c=l.map(m=>JSON.stringify(m,(f,v)=>{let g=typeof v;return(0,Sw.default)(["number","string","boolean"],g)?v:v===null?null:`<${g}>`})),p=`Player.${String(n)}`,h=`Exception calling ${p} (${c.join(", ")})`;throw this.events.fatalError$.next({id:p,category:Su.WTF,message:h,thrown:d}),d}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,d;let{container:n,...o}=e;this.tracer.log("initVideo",ci(o)),this.domContainer=cw(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Gs({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0),this.devNullLog&&this.tuning.devNullLogEnabled?(Tu.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=hw())):Tu.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?B.isInited$.pipe(he(n=>!!n),ve()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),wp(document,"visibilitychange").pipe(ve()).subscribe(r)):r(),this}destroy(){var e,t,i;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy(),Tu.destroy("core"),(i=this.collectDecodingInfoDestroyCb)==null||i.call(this)}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(he(t=>!!t),ve()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof kt)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof kt)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{Ep(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(he(i=>i.length>0),ve()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",ci(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",ci(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{var t;dw(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(EO(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return mw(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(li(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(oy(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(he(({from:e})=>e==="stopped"),ve()).subscribe(()=>{this.initedAt=yu(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",ci(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Su.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ve()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",ci(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(z(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(z(n=>n.destination),K()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Ot({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(z(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>gw(u)?1:gw(l)?-1:xO(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(K()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(he(n=>mw(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(K()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(K()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(K()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(z(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(z(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(xp(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Ot({hasLiveOffsetByPaused:li(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(n=>n.to),K(),z(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Ot({atLiveEdge:Ot({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Tp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(z(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),K(),xp(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ot({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(z(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),K(),xp(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(z(n=>n.muted),K()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(z(n=>n.volume),K()).subscribe(this.info.volume$)).add(Tp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(li(e.providerOutput.endedEvent$.pipe(fw(!0)),e.providerOutput.seekedEvent$.pipe(fw(!1))).pipe(K()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(z(n=>({id:n?`No${n}`:"NoProviders",category:Su.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(ve()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(ve()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(ve()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(ve()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(ve()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(ve(),z(n=>n!=null?n:yu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ve(),z(()=>yu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ve(),z(()=>yu()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new C(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new C(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(he(({to:n})=>n==="playing"),ve()).subscribe(()=>i.next(!1)));let r=0,s=li(e.providerOutput.isBuffering$,t,i).pipe(z(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),K());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(li(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(li(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(z(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new bw;this.subscription.add(t),this.subscription.add(e.current$.pipe(K((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(he(i=>i.length>0),ve()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=yt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(li(this.desiredState.videoTrack.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(z(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Ep(this.providerContainer),Ep(e),ay(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>ry(i)),this.providerContainer.current$.subscribe(({type:i})=>Ma("provider",i)),e.duration$.subscribe(i=>Ma("duration",i)),e.availableVideoTracks$.pipe(he(i=>!!i.length),ve()).subscribe(i=>Ma("tracks",i)),this.events.fatalError$.subscribe(new Re("fatalError")),this.events.managedError$.subscribe(new Re("managedError")),e.position$.subscribe(new Re("position")),e.currentVideoTrack$.pipe(z(i=>i==null?void 0:i.quality)).subscribe(new Re("quality")),this.info.currentBuffer$.subscribe(new Re("buffer")),e.isBuffering$.subscribe(new Re("isBuffering"))].forEach(i=>this.subscription.add(i)),Ma("codecs",B.video.supportedCodecs)}initTracerSubscription(){let e=vw(this.tracer.log.bind(this.tracer)),t=vw(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(K()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Ot({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(he(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),K((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(he(i=>i>0),K()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(he(i=>i>0),K()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Ot({currentBuffer:this.info.currentBuffer$.pipe(he(i=>i.end>0),K((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(K())}).pipe(Pp(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(K()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(K()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(K()).subscribe(e("canChangePlaybackSpeed"))).add(Ot({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(he(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Pp(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(K(),he(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(K(),he(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(K()).subscribe(e("muted"))).add(this.info.volume$.pipe(K()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(K(),he(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ot({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(he(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Pp(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(K(),he(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Su.DOM,message:String(r)})})};this.subscription.add(li(wp(document,"visibilitychange"),wp(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",ci({quality:t,availableTracks:ci(e),track:ci(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Oa()}};import{Subscription as $ee,Observable as Mee,Subject as Cee,ValueSubject as Lee,VideoQuality as Dee}from"@vkontakte/videoplayer-shared/es2018";var Bee=`@vkontakte/videoplayer-core@${hh}`;export{Xr as ChromecastState,Au as HttpConnectionType,Mee as Observable,Pe as PlaybackState,Iu as Player,cn as PredefinedQualityLimits,Bee as SDK_VERSION,Cee as Subject,$ee as Subscription,Ru as Surface,hh as VERSION,Lee as ValueSubject,xt as VideoFormat,Dee as VideoQuality,Xk as areValidLiveRecordSources,B as clientChecker,xi as isMobile};
|