@vkontakte/videoplayer-core 2.0.140-dev.4c27f703.0 → 2.0.140-dev.7b3cdcf7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +39 -39
- package/es2015.esm.js +43 -43
- package/es2018.cjs.js +38 -38
- package/es2018.esm.js +35 -35
- package/es2024.cjs.js +47 -47
- package/es2024.esm.js +44 -44
- package/esnext.cjs.js +47 -47
- package/esnext.esm.js +44 -44
- package/evergreen.esm.js +48 -48
- package/package.json +2 -2
- package/types/player/Player.d.ts +2 -1
- package/types/providers/DashProvider/baseDashProvider.d.ts +1 -0
- package/types/providers/DashProvider/lib/buffer.d.ts +11 -0
- package/types/providers/DashProvider/lib/player.d.ts +1 -0
- package/types/providers/DashProviderNew/lib/buffer.d.ts +2 -0
- package/types/providers/DashProviderNew/lib/player.d.ts +1 -0
- package/types/providers/HlsProvider/index.d.ts +1 -0
- package/types/utils/playerOptions.d.ts +3 -0
- package/types/utils/qualityLimits.d.ts +0 -1
- package/types/utils/tuningConfig.d.ts +6 -1
package/es2018.esm.js
CHANGED
|
@@ -1,85 +1,85 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.140-dev.
|
|
3
|
-
* Tue,
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.140-dev.7b3cdcf7.0
|
|
3
|
+
* Tue, 09 Sep 2025 14:28:38 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-140/doc/
|
|
5
5
|
*/
|
|
6
|
-
var zE=Object.create;var Qp=Object.defineProperty;var YE=Object.getOwnPropertyDescriptor;var KE=Object.getOwnPropertyNames;var XE=Object.getPrototypeOf,JE=Object.prototype.hasOwnProperty;var g=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var ZE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of KE(e))!JE.call(s,r)&&r!==t&&Qp(s,r,{get:()=>e[r],enumerable:!(i=YE(e,r))||i.enumerable});return s};var O=(s,e,t)=>(t=s!=null?zE(XE(s)):{},ZE(e||!s||!s.__esModule?Qp(t,"default",{value:s,enumerable:!0}):t,s));var oe=g((Su,Gp)=>{"use strict";var Zr=function(s){return s&&s.Math===Math&&s};Gp.exports=Zr(typeof globalThis=="object"&&globalThis)||Zr(typeof window=="object"&&window)||Zr(typeof self=="object"&&self)||Zr(typeof global=="object"&&global)||Zr(typeof Su=="object"&&Su)||function(){return this}()||Function("return this")()});var he=g((t_,zp)=>{"use strict";zp.exports=function(s){try{return!!s()}catch(e){return!0}}});var es=g((i_,Yp)=>{"use strict";var ex=he();Yp.exports=!ex(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var yu=g((r_,Zp)=>{"use strict";var tx=es(),Jp=Function.prototype,Kp=Jp.apply,Xp=Jp.call;Zp.exports=typeof Reflect=="object"&&Reflect.apply||(tx?Xp.bind(Kp):function(){return Xp.apply(Kp,arguments)})});var fe=g((s_,ih)=>{"use strict";var eh=es(),th=Function.prototype,Tu=th.call,ix=eh&&th.bind.bind(Tu,Tu);ih.exports=eh?ix:function(s){return function(){return Tu.apply(s,arguments)}}});var mi=g((a_,sh)=>{"use strict";var rh=fe(),rx=rh({}.toString),sx=rh("".slice);sh.exports=function(s){return sx(rx(s),8,-1)}});var Iu=g((n_,ah)=>{"use strict";var ax=mi(),nx=fe();ah.exports=function(s){if(ax(s)==="Function")return nx(s)}});var ue=g((o_,nh)=>{"use strict";var Eu=typeof document=="object"&&document.all;nh.exports=typeof Eu=="undefined"&&Eu!==void 0?function(s){return typeof s=="function"||s===Eu}:function(s){return typeof s=="function"}});var Ue=g((u_,oh)=>{"use strict";var ox=he();oh.exports=!ox(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var He=g((l_,uh)=>{"use strict";var ux=es(),rn=Function.prototype.call;uh.exports=ux?rn.bind(rn):function(){return rn.apply(rn,arguments)}});var xu=g(dh=>{"use strict";var lh={}.propertyIsEnumerable,ch=Object.getOwnPropertyDescriptor,lx=ch&&!lh.call({1:2},1);dh.f=lx?function(e){var t=ch(this,e);return!!t&&t.enumerable}:lh});var ts=g((d_,ph)=>{"use strict";ph.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var fh=g((p_,hh)=>{"use strict";var cx=fe(),dx=he(),px=mi(),wu=Object,hx=cx("".split);hh.exports=dx(function(){return!wu("z").propertyIsEnumerable(0)})?function(s){return px(s)==="String"?hx(s,""):wu(s)}:wu});var is=g((h_,mh)=>{"use strict";mh.exports=function(s){return s==null}});var Qt=g((f_,bh)=>{"use strict";var fx=is(),mx=TypeError;bh.exports=function(s){if(fx(s))throw new mx("Can't call method on "+s);return s}});var bi=g((m_,gh)=>{"use strict";var bx=fh(),gx=Qt();gh.exports=function(s){return bx(gx(s))}});var Me=g((b_,vh)=>{"use strict";var vx=ue();vh.exports=function(s){return typeof s=="object"?s!==null:vx(s)}});var gi=g((g_,Sh)=>{"use strict";Sh.exports={}});var Pt=g((v_,Th)=>{"use strict";var Au=gi(),Pu=oe(),Sx=ue(),yh=function(s){return Sx(s)?s:void 0};Th.exports=function(s,e){return arguments.length<2?yh(Au[s])||yh(Pu[s]):Au[s]&&Au[s][e]||Pu[s]&&Pu[s][e]}});var rs=g((S_,Ih)=>{"use strict";var yx=fe();Ih.exports=yx({}.isPrototypeOf)});var vi=g((y_,wh)=>{"use strict";var Tx=oe(),Eh=Tx.navigator,xh=Eh&&Eh.userAgent;wh.exports=xh?String(xh):""});var ku=g((T_,$h)=>{"use strict";var Lh=oe(),Ru=vi(),Ah=Lh.process,Ph=Lh.Deno,Rh=Ah&&Ah.versions||Ph&&Ph.version,kh=Rh&&Rh.v8,rt,sn;kh&&(rt=kh.split("."),sn=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!sn&&Ru&&(rt=Ru.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Ru.match(/Chrome\/(\d+)/),rt&&(sn=+rt[1])));$h.exports=sn});var Lu=g((I_,Dh)=>{"use strict";var Mh=ku(),Ix=he(),Ex=oe(),xx=Ex.String;Dh.exports=!!Object.getOwnPropertySymbols&&!Ix(function(){var s=Symbol("symbol detection");return!xx(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Mh&&Mh<41})});var $u=g((E_,Ch)=>{"use strict";var wx=Lu();Ch.exports=wx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Mu=g((x_,Bh)=>{"use strict";var Ax=Pt(),Px=ue(),Rx=rs(),kx=$u(),Lx=Object;Bh.exports=kx?function(s){return typeof s=="symbol"}:function(s){var e=Ax("Symbol");return Px(e)&&Rx(e.prototype,Lx(s))}});var ss=g((w_,Vh)=>{"use strict";var $x=String;Vh.exports=function(s){try{return $x(s)}catch(e){return"Object"}}});var ft=g((A_,_h)=>{"use strict";var Mx=ue(),Dx=ss(),Cx=TypeError;_h.exports=function(s){if(Mx(s))return s;throw new Cx(Dx(s)+" is not a function")}});var as=g((P_,Oh)=>{"use strict";var Bx=ft(),Vx=is();Oh.exports=function(s,e){var t=s[e];return Vx(t)?void 0:Bx(t)}});var Nh=g((R_,Fh)=>{"use strict";var Du=He(),Cu=ue(),Bu=Me(),_x=TypeError;Fh.exports=function(s,e){var t,i;if(e==="string"&&Cu(t=s.toString)&&!Bu(i=Du(t,s))||Cu(t=s.valueOf)&&!Bu(i=Du(t,s))||e!=="string"&&Cu(t=s.toString)&&!Bu(i=Du(t,s)))return i;throw new _x("Can't convert object to primitive value")}});var st=g((k_,qh)=>{"use strict";qh.exports=!0});var jh=g((L_,Hh)=>{"use strict";var Uh=oe(),Ox=Object.defineProperty;Hh.exports=function(s,e){try{Ox(Uh,s,{value:e,configurable:!0,writable:!0})}catch(t){Uh[s]=e}return e}});var ns=g(($_,Gh)=>{"use strict";var Fx=st(),Nx=oe(),qx=jh(),Qh="__core-js_shared__",Wh=Gh.exports=Nx[Qh]||qx(Qh,{});(Wh.versions||(Wh.versions=[])).push({version:"3.43.0",mode:Fx?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Vu=g((M_,Yh)=>{"use strict";var zh=ns();Yh.exports=function(s,e){return zh[s]||(zh[s]=e||{})}});var Ki=g((D_,Kh)=>{"use strict";var Ux=Qt(),Hx=Object;Kh.exports=function(s){return Hx(Ux(s))}});var at=g((C_,Xh)=>{"use strict";var jx=fe(),Qx=Ki(),Wx=jx({}.hasOwnProperty);Xh.exports=Object.hasOwn||function(e,t){return Wx(Qx(e),t)}});var _u=g((B_,Jh)=>{"use strict";var Gx=fe(),zx=0,Yx=Math.random(),Kx=Gx(1.1.toString);Jh.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Kx(++zx+Yx,36)}});var ye=g((V_,ef)=>{"use strict";var Xx=oe(),Jx=Vu(),Zh=at(),Zx=_u(),ew=Lu(),tw=$u(),Xi=Xx.Symbol,Ou=Jx("wks"),iw=tw?Xi.for||Xi:Xi&&Xi.withoutSetter||Zx;ef.exports=function(s){return Zh(Ou,s)||(Ou[s]=ew&&Zh(Xi,s)?Xi[s]:iw("Symbol."+s)),Ou[s]}});var af=g((__,sf)=>{"use strict";var rw=He(),tf=Me(),rf=Mu(),sw=as(),aw=Nh(),nw=ye(),ow=TypeError,uw=nw("toPrimitive");sf.exports=function(s,e){if(!tf(s)||rf(s))return s;var t=sw(s,uw),i;if(t){if(e===void 0&&(e="default"),i=rw(t,s,e),!tf(i)||rf(i))return i;throw new ow("Can't convert object to primitive value")}return e===void 0&&(e="number"),aw(s,e)}});var Fu=g((O_,nf)=>{"use strict";var lw=af(),cw=Mu();nf.exports=function(s){var e=lw(s,"string");return cw(e)?e:e+""}});var an=g((F_,uf)=>{"use strict";var dw=oe(),of=Me(),Nu=dw.document,pw=of(Nu)&&of(Nu.createElement);uf.exports=function(s){return pw?Nu.createElement(s):{}}});var qu=g((N_,lf)=>{"use strict";var hw=Ue(),fw=he(),mw=an();lf.exports=!hw&&!fw(function(){return Object.defineProperty(mw("div"),"a",{get:function(){return 7}}).a!==7})});var pf=g(df=>{"use strict";var bw=Ue(),gw=He(),vw=xu(),Sw=ts(),yw=bi(),Tw=Fu(),Iw=at(),Ew=qu(),cf=Object.getOwnPropertyDescriptor;df.f=bw?cf:function(e,t){if(e=yw(e),t=Tw(t),Ew)try{return cf(e,t)}catch(i){}if(Iw(e,t))return Sw(!gw(vw.f,e,t),e[t])}});var Uu=g((U_,hf)=>{"use strict";var xw=he(),ww=ue(),Aw=/#|\.prototype\./,os=function(s,e){var t=Rw[Pw(s)];return t===Lw?!0:t===kw?!1:ww(e)?xw(e):!!e},Pw=os.normalize=function(s){return String(s).replace(Aw,".").toLowerCase()},Rw=os.data={},kw=os.NATIVE="N",Lw=os.POLYFILL="P";hf.exports=os});var Ji=g((H_,mf)=>{"use strict";var ff=Iu(),$w=ft(),Mw=es(),Dw=ff(ff.bind);mf.exports=function(s,e){return $w(s),e===void 0?s:Mw?Dw(s,e):function(){return s.apply(e,arguments)}}});var Hu=g((j_,bf)=>{"use strict";var Cw=Ue(),Bw=he();bf.exports=Cw&&Bw(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=g((Q_,gf)=>{"use strict";var Vw=Me(),_w=String,Ow=TypeError;gf.exports=function(s){if(Vw(s))return s;throw new Ow(_w(s)+" is not an object")}});var Si=g(Sf=>{"use strict";var Fw=Ue(),Nw=qu(),qw=Hu(),nn=mt(),vf=Fu(),Uw=TypeError,ju=Object.defineProperty,Hw=Object.getOwnPropertyDescriptor,Qu="enumerable",Wu="configurable",Gu="writable";Sf.f=Fw?qw?function(e,t,i){if(nn(e),t=vf(t),nn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Gu in i&&!i[Gu]){var r=Hw(e,t);r&&r[Gu]&&(e[t]=i.value,i={configurable:Wu in i?i[Wu]:r[Wu],enumerable:Qu in i?i[Qu]:r[Qu],writable:!1})}return ju(e,t,i)}:ju:function(e,t,i){if(nn(e),t=vf(t),nn(i),Nw)try{return ju(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Uw("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Zi=g((G_,yf)=>{"use strict";var jw=Ue(),Qw=Si(),Ww=ts();yf.exports=jw?function(s,e,t){return Qw.f(s,e,Ww(1,t))}:function(s,e,t){return s[e]=t,s}});var pe=g((z_,If)=>{"use strict";var us=oe(),Gw=yu(),zw=Iu(),Yw=ue(),Kw=pf().f,Xw=Uu(),er=gi(),Jw=Ji(),tr=Zi(),Tf=at();ns();var Zw=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Gw(s,this,arguments)};return e.prototype=s.prototype,e};If.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?us:r?us[t]:us[t]&&us[t].prototype,o=i?er:er[t]||tr(er,t,{})[t],u=o.prototype,l,c,d,f,p,h,m,v,b;for(f in e)l=Xw(i?f:t+(r?".":"#")+f,s.forced),c=!l&&n&&Tf(n,f),h=o[f],c&&(s.dontCallGetSet?(b=Kw(n,f),m=b&&b.value):m=n[f]),p=c&&m?m:e[f],!(!l&&!a&&typeof h==typeof p)&&(s.bind&&c?v=Jw(p,us):s.wrap&&c?v=Zw(p):a&&Yw(p)?v=zw(p):v=p,(s.sham||p&&p.sham||h&&h.sham)&&tr(v,"sham",!0),tr(o,f,v),a&&(d=t+"Prototype",Tf(er,d)||tr(er,d,{}),tr(er[d],f,p),s.real&&u&&(l||!u[f])&&tr(u,f,p)))}});var on=g((Y_,xf)=>{"use strict";var eA=Vu(),tA=_u(),Ef=eA("keys");xf.exports=function(s){return Ef[s]||(Ef[s]=tA(s))}});var Af=g((K_,wf)=>{"use strict";var iA=he();wf.exports=!iA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var un=g((X_,Rf)=>{"use strict";var rA=at(),sA=ue(),aA=Ki(),nA=on(),oA=Af(),Pf=nA("IE_PROTO"),zu=Object,uA=zu.prototype;Rf.exports=oA?zu.getPrototypeOf:function(s){var e=aA(s);if(rA(e,Pf))return e[Pf];var t=e.constructor;return sA(t)&&e instanceof t?t.prototype:e instanceof zu?uA:null}});var Lf=g((J_,kf)=>{"use strict";var lA=Math.ceil,cA=Math.floor;kf.exports=Math.trunc||function(e){var t=+e;return(t>0?cA:lA)(t)}});var ls=g((Z_,$f)=>{"use strict";var dA=Lf();$f.exports=function(s){var e=+s;return e!==e||e===0?0:dA(e)}});var Df=g((eO,Mf)=>{"use strict";var pA=ls(),hA=Math.max,fA=Math.min;Mf.exports=function(s,e){var t=pA(s);return t<0?hA(t+e,0):fA(t,e)}});var Yu=g((tO,Cf)=>{"use strict";var mA=ls(),bA=Math.min;Cf.exports=function(s){var e=mA(s);return e>0?bA(e,9007199254740991):0}});var ir=g((iO,Bf)=>{"use strict";var gA=Yu();Bf.exports=function(s){return gA(s.length)}});var Ku=g((rO,_f)=>{"use strict";var vA=bi(),SA=Df(),yA=ir(),Vf=function(s){return function(e,t,i){var r=vA(e),a=yA(r);if(a===0)return!s&&-1;var n=SA(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};_f.exports={includes:Vf(!0),indexOf:Vf(!1)}});var ln=g((sO,Of)=>{"use strict";Of.exports={}});var qf=g((aO,Nf)=>{"use strict";var TA=fe(),Xu=at(),IA=bi(),EA=Ku().indexOf,xA=ln(),Ff=TA([].push);Nf.exports=function(s,e){var t=IA(s),i=0,r=[],a;for(a in t)!Xu(xA,a)&&Xu(t,a)&&Ff(r,a);for(;e.length>i;)Xu(t,a=e[i++])&&(~EA(r,a)||Ff(r,a));return r}});var Ju=g((nO,Uf)=>{"use strict";Uf.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Zu=g((oO,Hf)=>{"use strict";var wA=qf(),AA=Ju();Hf.exports=Object.keys||function(e){return wA(e,AA)}});var el=g((uO,zf)=>{"use strict";var Qf=Ue(),PA=he(),Wf=fe(),RA=un(),kA=Zu(),LA=bi(),$A=xu().f,Gf=Wf($A),MA=Wf([].push),DA=Qf&&PA(function(){var s=Object.create(null);return s[2]=2,!Gf(s,2)}),jf=function(s){return function(e){for(var t=LA(e),i=kA(t),r=DA&&RA(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Qf||(r?u in t:Gf(t,u)))&&MA(o,s?[u,t[u]]:t[u]);return o}};zf.exports={entries:jf(!0),values:jf(!1)}});var Yf=g(()=>{"use strict";var CA=pe(),BA=el().values;CA({target:"Object",stat:!0},{values:function(e){return BA(e)}})});var Xf=g((dO,Kf)=>{"use strict";Yf();var VA=gi();Kf.exports=VA.Object.values});var Zf=g((pO,Jf)=>{"use strict";var _A=Xf();Jf.exports=_A});var yi=g((hO,em)=>{"use strict";var OA=Zf();em.exports=OA});var cs=g((fO,tm)=>{"use strict";tm.exports=function(){}});var im=g(()=>{"use strict";var FA=pe(),NA=Ku().includes,qA=he(),UA=cs(),HA=qA(function(){return!Array(1).includes()});FA({target:"Array",proto:!0,forced:HA},{includes:function(e){return NA(this,e,arguments.length>1?arguments[1]:void 0)}});UA("includes")});var Wt=g((gO,rm)=>{"use strict";var jA=Pt();rm.exports=jA});var am=g((vO,sm)=>{"use strict";im();var QA=Wt();sm.exports=QA("Array","includes")});var om=g((SO,nm)=>{"use strict";var WA=am();nm.exports=WA});var Ae=g((yO,um)=>{"use strict";var GA=om();um.exports=GA});var mm=g(()=>{"use strict";var tP=pe(),iP=el().entries;tP({target:"Object",stat:!0},{entries:function(e){return iP(e)}})});var gm=g((CO,bm)=>{"use strict";mm();var rP=gi();bm.exports=rP.Object.entries});var Sm=g((BO,vm)=>{"use strict";var sP=gm();vm.exports=sP});var rr=g((VO,ym)=>{"use strict";var aP=Sm();ym.exports=aP});var Ti=g((_O,Tm)=>{"use strict";Tm.exports={}});var xm=g((OO,Em)=>{"use strict";var nP=oe(),oP=ue(),Im=nP.WeakMap;Em.exports=oP(Im)&&/native code/.test(String(Im))});var nl=g((FO,Pm)=>{"use strict";var uP=xm(),Am=oe(),lP=Me(),cP=Zi(),rl=at(),sl=ns(),dP=on(),pP=ln(),wm="Object already initialized",al=Am.TypeError,hP=Am.WeakMap,pn,ds,hn,fP=function(s){return hn(s)?ds(s):pn(s,{})},mP=function(s){return function(e){var t;if(!lP(e)||(t=ds(e)).type!==s)throw new al("Incompatible receiver, "+s+" required");return t}};uP||sl.state?(nt=sl.state||(sl.state=new hP),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,pn=function(s,e){if(nt.has(s))throw new al(wm);return e.facade=s,nt.set(s,e),e},ds=function(s){return nt.get(s)||{}},hn=function(s){return nt.has(s)}):(Ii=dP("state"),pP[Ii]=!0,pn=function(s,e){if(rl(s,Ii))throw new al(wm);return e.facade=s,cP(s,Ii,e),e},ds=function(s){return rl(s,Ii)?s[Ii]:{}},hn=function(s){return rl(s,Ii)});var nt,Ii;Pm.exports={set:pn,get:ds,has:hn,enforce:fP,getterFor:mP}});var ll=g((NO,km)=>{"use strict";var ol=Ue(),bP=at(),Rm=Function.prototype,gP=ol&&Object.getOwnPropertyDescriptor,ul=bP(Rm,"name"),vP=ul&&function(){}.name==="something",SP=ul&&(!ol||ol&&gP(Rm,"name").configurable);km.exports={EXISTS:ul,PROPER:vP,CONFIGURABLE:SP}});var $m=g(Lm=>{"use strict";var yP=Ue(),TP=Hu(),IP=Si(),EP=mt(),xP=bi(),wP=Zu();Lm.f=yP&&!TP?Object.defineProperties:function(e,t){EP(e);for(var i=xP(t),r=wP(t),a=r.length,n=0,o;a>n;)IP.f(e,o=r[n++],i[o]);return e}});var cl=g((UO,Mm)=>{"use strict";var AP=Pt();Mm.exports=AP("document","documentElement")});var fl=g((HO,Fm)=>{"use strict";var PP=mt(),RP=$m(),Dm=Ju(),kP=ln(),LP=cl(),$P=an(),MP=on(),Cm=">",Bm="<",pl="prototype",hl="script",_m=MP("IE_PROTO"),dl=function(){},Om=function(s){return Bm+hl+Cm+s+Bm+"/"+hl+Cm},Vm=function(s){s.write(Om("")),s.close();var e=s.parentWindow.Object;return s=null,e},DP=function(){var s=$P("iframe"),e="java"+hl+":",t;return s.style.display="none",LP.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Om("document.F=Object")),t.close(),t.F},fn,mn=function(){try{fn=new ActiveXObject("htmlfile")}catch(e){}mn=typeof document!="undefined"?document.domain&&fn?Vm(fn):DP():Vm(fn);for(var s=Dm.length;s--;)delete mn[pl][Dm[s]];return mn()};kP[_m]=!0;Fm.exports=Object.create||function(e,t){var i;return e!==null?(dl[pl]=PP(e),i=new dl,dl[pl]=null,i[_m]=e):i=mn(),t===void 0?i:RP.f(i,t)}});var sr=g((jO,Nm)=>{"use strict";var CP=Zi();Nm.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:CP(s,e,t),s}});var vl=g((QO,Hm)=>{"use strict";var BP=he(),VP=ue(),_P=Me(),OP=fl(),qm=un(),FP=sr(),NP=ye(),qP=st(),gl=NP("iterator"),Um=!1,Rt,ml,bl;[].keys&&(bl=[].keys(),"next"in bl?(ml=qm(qm(bl)),ml!==Object.prototype&&(Rt=ml)):Um=!0);var UP=!_P(Rt)||BP(function(){var s={};return Rt[gl].call(s)!==s});UP?Rt={}:qP&&(Rt=OP(Rt));VP(Rt[gl])||FP(Rt,gl,function(){return this});Hm.exports={IteratorPrototype:Rt,BUGGY_SAFARI_ITERATORS:Um}});var bn=g((WO,Qm)=>{"use strict";var HP=ye(),jP=HP("toStringTag"),jm={};jm[jP]="z";Qm.exports=String(jm)==="[object z]"});var ps=g((GO,Wm)=>{"use strict";var QP=bn(),WP=ue(),gn=mi(),GP=ye(),zP=GP("toStringTag"),YP=Object,KP=gn(function(){return arguments}())==="Arguments",XP=function(s,e){try{return s[e]}catch(t){}};Wm.exports=QP?gn:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=XP(e=YP(s),zP))=="string"?t:KP?gn(e):(i=gn(e))==="Object"&&WP(e.callee)?"Arguments":i}});var zm=g((zO,Gm)=>{"use strict";var JP=bn(),ZP=ps();Gm.exports=JP?{}.toString:function(){return"[object "+ZP(this)+"]"}});var hs=g((YO,Km)=>{"use strict";var eR=bn(),tR=Si().f,iR=Zi(),rR=at(),sR=zm(),aR=ye(),Ym=aR("toStringTag");Km.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(rR(r,Ym)||tR(r,Ym,{configurable:!0,value:e}),i&&!eR&&iR(r,"toString",sR))}});var Jm=g((KO,Xm)=>{"use strict";var nR=vl().IteratorPrototype,oR=fl(),uR=ts(),lR=hs(),cR=Ti(),dR=function(){return this};Xm.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=oR(nR,{next:uR(+!i,t)}),lR(s,r,!1,!0),cR[r]=dR,s}});var eb=g((XO,Zm)=>{"use strict";var pR=fe(),hR=ft();Zm.exports=function(s,e,t){try{return pR(hR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var ib=g((JO,tb)=>{"use strict";var fR=Me();tb.exports=function(s){return fR(s)||s===null}});var sb=g((ZO,rb)=>{"use strict";var mR=ib(),bR=String,gR=TypeError;rb.exports=function(s){if(mR(s))return s;throw new gR("Can't set "+bR(s)+" as a prototype")}});var Sl=g((eF,ab)=>{"use strict";var vR=eb(),SR=Me(),yR=Qt(),TR=sb();ab.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=vR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return yR(r),TR(a),SR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var bb=g((tF,mb)=>{"use strict";var IR=pe(),ER=He(),vn=st(),hb=ll(),xR=ue(),wR=Jm(),nb=un(),ob=Sl(),AR=hs(),PR=Zi(),yl=sr(),RR=ye(),ub=Ti(),fb=vl(),kR=hb.PROPER,LR=hb.CONFIGURABLE,lb=fb.IteratorPrototype,Sn=fb.BUGGY_SAFARI_ITERATORS,fs=RR("iterator"),cb="keys",ms="values",db="entries",pb=function(){return this};mb.exports=function(s,e,t,i,r,a,n){wR(t,e,i);var o=function(b){if(b===r&&f)return f;if(!Sn&&b&&b in c)return c[b];switch(b){case cb:return function(){return new t(this,b)};case ms:return function(){return new t(this,b)};case db:return function(){return new t(this,b)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=s.prototype,d=c[fs]||c["@@iterator"]||r&&c[r],f=!Sn&&d||o(r),p=e==="Array"&&c.entries||d,h,m,v;if(p&&(h=nb(p.call(new s)),h!==Object.prototype&&h.next&&(!vn&&nb(h)!==lb&&(ob?ob(h,lb):xR(h[fs])||yl(h,fs,pb)),AR(h,u,!0,!0),vn&&(ub[u]=pb))),kR&&r===ms&&d&&d.name!==ms&&(!vn&&LR?PR(c,"name",ms):(l=!0,f=function(){return ER(d,this)})),r)if(m={values:o(ms),keys:a?f:o(cb),entries:o(db)},n)for(v in m)(Sn||l||!(v in c))&&yl(c,v,m[v]);else IR({target:e,proto:!0,forced:Sn||l},m);return(!vn||n)&&c[fs]!==f&&yl(c,fs,f,{name:r}),ub[e]=f,m}});var vb=g((iF,gb)=>{"use strict";gb.exports=function(s,e){return{value:s,done:e}}});var Il=g((rF,Eb)=>{"use strict";var $R=bi(),Tl=cs(),Sb=Ti(),Tb=nl(),MR=Si().f,DR=bb(),yn=vb(),CR=st(),BR=Ue(),Ib="Array Iterator",VR=Tb.set,_R=Tb.getterFor(Ib);Eb.exports=DR(Array,"Array",function(s,e){VR(this,{type:Ib,target:$R(s),index:0,kind:e})},function(){var s=_R(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,yn(void 0,!0);switch(s.kind){case"keys":return yn(t,!1);case"values":return yn(e[t],!1)}return yn([t,e[t]],!1)},"values");var yb=Sb.Arguments=Sb.Array;Tl("keys");Tl("values");Tl("entries");if(!CR&&BR&&yb.name!=="values")try{MR(yb,"name",{value:"values"})}catch(s){}});var wb=g((sF,xb)=>{"use strict";var OR=ye(),FR=Ti(),NR=OR("iterator"),qR=Array.prototype;xb.exports=function(s){return s!==void 0&&(FR.Array===s||qR[NR]===s)}});var El=g((aF,Pb)=>{"use strict";var UR=ps(),Ab=as(),HR=is(),jR=Ti(),QR=ye(),WR=QR("iterator");Pb.exports=function(s){if(!HR(s))return Ab(s,WR)||Ab(s,"@@iterator")||jR[UR(s)]}});var kb=g((nF,Rb)=>{"use strict";var GR=He(),zR=ft(),YR=mt(),KR=ss(),XR=El(),JR=TypeError;Rb.exports=function(s,e){var t=arguments.length<2?XR(s):e;if(zR(t))return YR(GR(t,s));throw new JR(KR(s)+" is not iterable")}});var Mb=g((oF,$b)=>{"use strict";var ZR=He(),Lb=mt(),ek=as();$b.exports=function(s,e,t){var i,r;Lb(s);try{if(i=ek(s,"return"),!i){if(e==="throw")throw t;return t}i=ZR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Lb(i),t}});var In=g((uF,Vb)=>{"use strict";var tk=Ji(),ik=He(),rk=mt(),sk=ss(),ak=wb(),nk=ir(),Db=rs(),ok=kb(),uk=El(),Cb=Mb(),lk=TypeError,Tn=function(s,e){this.stopped=s,this.result=e},Bb=Tn.prototype;Vb.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=tk(e,i),l,c,d,f,p,h,m,v=function(S){return l&&Cb(l,"normal"),new Tn(!0,S)},b=function(S){return r?(rk(S),o?u(S[0],S[1],v):u(S[0],S[1])):o?u(S,v):u(S)};if(a)l=s.iterator;else if(n)l=s;else{if(c=uk(s),!c)throw new lk(sk(s)+" is not iterable");if(ak(c)){for(d=0,f=nk(s);f>d;d++)if(p=b(s[d]),p&&Db(Bb,p))return p;return new Tn(!1)}l=ok(s,c)}for(h=a?s.next:l.next;!(m=ik(h,l)).done;){try{p=b(m.value)}catch(S){Cb(l,"throw",S)}if(typeof p=="object"&&p&&Db(Bb,p))return p}return new Tn(!1)}});var Ob=g((lF,_b)=>{"use strict";var ck=Ue(),dk=Si(),pk=ts();_b.exports=function(s,e,t){ck?dk.f(s,e,pk(0,t)):s[e]=t}});var Fb=g(()=>{"use strict";var hk=pe(),fk=In(),mk=Ob();hk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return fk(e,function(i,r){mk(t,i,r)},{AS_ENTRIES:!0}),t}})});var qb=g((pF,Nb)=>{"use strict";Il();Fb();var bk=gi();Nb.exports=bk.Object.fromEntries});var Hb=g((hF,Ub)=>{"use strict";Ub.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 Qb=g(()=>{"use strict";Il();var gk=Hb(),vk=oe(),Sk=hs(),jb=Ti();for(En in gk)Sk(vk[En],En),jb[En]=jb.Array;var En});var Gb=g((bF,Wb)=>{"use strict";var yk=qb();Qb();Wb.exports=yk});var xl=g((gF,zb)=>{"use strict";var Tk=Gb();zb.exports=Tk});var Yb=g(()=>{"use strict"});var wl=g((yF,Kb)=>{"use strict";var bs=oe(),Ik=vi(),Ek=mi(),xn=function(s){return Ik.slice(0,s.length)===s};Kb.exports=function(){return xn("Bun/")?"BUN":xn("Cloudflare-Workers")?"CLOUDFLARE":xn("Deno/")?"DENO":xn("Node.js/")?"NODE":bs.Bun&&typeof Bun.version=="string"?"BUN":bs.Deno&&typeof Deno.version=="object"?"DENO":Ek(bs.process)==="process"?"NODE":bs.window&&bs.document?"BROWSER":"REST"}()});var wn=g((TF,Xb)=>{"use strict";var xk=wl();Xb.exports=xk==="NODE"});var Zb=g((IF,Jb)=>{"use strict";var wk=Si();Jb.exports=function(s,e,t){return wk.f(s,e,t)}});var ig=g((EF,tg)=>{"use strict";var Ak=Pt(),Pk=Zb(),Rk=ye(),kk=Ue(),eg=Rk("species");tg.exports=function(s){var e=Ak(s);kk&&e&&!e[eg]&&Pk(e,eg,{configurable:!0,get:function(){return this}})}});var sg=g((xF,rg)=>{"use strict";var Lk=rs(),$k=TypeError;rg.exports=function(s,e){if(Lk(e,s))return s;throw new $k("Incorrect invocation")}});var Pl=g((wF,ag)=>{"use strict";var Mk=fe(),Dk=ue(),Al=ns(),Ck=Mk(Function.toString);Dk(Al.inspectSource)||(Al.inspectSource=function(s){return Ck(s)});ag.exports=Al.inspectSource});var kl=g((AF,cg)=>{"use strict";var Bk=fe(),Vk=he(),ng=ue(),_k=ps(),Ok=Pt(),Fk=Pl(),og=function(){},ug=Ok("Reflect","construct"),Rl=/^\s*(?:class|function)\b/,Nk=Bk(Rl.exec),qk=!Rl.test(og),gs=function(e){if(!ng(e))return!1;try{return ug(og,[],e),!0}catch(t){return!1}},lg=function(e){if(!ng(e))return!1;switch(_k(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return qk||!!Nk(Rl,Fk(e))}catch(t){return!0}};lg.sham=!0;cg.exports=!ug||Vk(function(){var s;return gs(gs.call)||!gs(Object)||!gs(function(){s=!0})||s})?lg:gs});var pg=g((PF,dg)=>{"use strict";var Uk=kl(),Hk=ss(),jk=TypeError;dg.exports=function(s){if(Uk(s))return s;throw new jk(Hk(s)+" is not a constructor")}});var Ll=g((RF,fg)=>{"use strict";var hg=mt(),Qk=pg(),Wk=is(),Gk=ye(),zk=Gk("species");fg.exports=function(s,e){var t=hg(s).constructor,i;return t===void 0||Wk(i=hg(t)[zk])?e:Qk(i)}});var bg=g((kF,mg)=>{"use strict";var Yk=fe();mg.exports=Yk([].slice)});var vg=g((LF,gg)=>{"use strict";var Kk=TypeError;gg.exports=function(s,e){if(s<e)throw new Kk("Not enough arguments");return s}});var $l=g(($F,Sg)=>{"use strict";var Xk=vi();Sg.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Xk)});var Nl=g((MF,Rg)=>{"use strict";var je=oe(),Jk=yu(),Zk=Ji(),yg=ue(),eL=at(),Pg=he(),Tg=cl(),tL=bg(),Ig=an(),iL=vg(),rL=$l(),sL=wn(),_l=je.setImmediate,Ol=je.clearImmediate,aL=je.process,Ml=je.Dispatch,nL=je.Function,Eg=je.MessageChannel,oL=je.String,Dl=0,vs={},xg="onreadystatechange",Ss,Ei,Cl,Bl;Pg(function(){Ss=je.location});var Fl=function(s){if(eL(vs,s)){var e=vs[s];delete vs[s],e()}},Vl=function(s){return function(){Fl(s)}},wg=function(s){Fl(s.data)},Ag=function(s){je.postMessage(oL(s),Ss.protocol+"//"+Ss.host)};(!_l||!Ol)&&(_l=function(e){iL(arguments.length,1);var t=yg(e)?e:nL(e),i=tL(arguments,1);return vs[++Dl]=function(){Jk(t,void 0,i)},Ei(Dl),Dl},Ol=function(e){delete vs[e]},sL?Ei=function(s){aL.nextTick(Vl(s))}:Ml&&Ml.now?Ei=function(s){Ml.now(Vl(s))}:Eg&&!rL?(Cl=new Eg,Bl=Cl.port2,Cl.port1.onmessage=wg,Ei=Zk(Bl.postMessage,Bl)):je.addEventListener&&yg(je.postMessage)&&!je.importScripts&&Ss&&Ss.protocol!=="file:"&&!Pg(Ag)?(Ei=Ag,je.addEventListener("message",wg,!1)):xg in Ig("script")?Ei=function(s){Tg.appendChild(Ig("script"))[xg]=function(){Tg.removeChild(this),Fl(s)}}:Ei=function(s){setTimeout(Vl(s),0)});Rg.exports={set:_l,clear:Ol}});var $g=g((DF,Lg)=>{"use strict";var kg=oe(),uL=Ue(),lL=Object.getOwnPropertyDescriptor;Lg.exports=function(s){if(!uL)return kg[s];var e=lL(kg,s);return e&&e.value}});var ql=g((CF,Dg)=>{"use strict";var Mg=function(){this.head=null,this.tail=null};Mg.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};Dg.exports=Mg});var Bg=g((BF,Cg)=>{"use strict";var cL=vi();Cg.exports=/ipad|iphone|ipod/i.test(cL)&&typeof Pebble!="undefined"});var _g=g((VF,Vg)=>{"use strict";var dL=vi();Vg.exports=/web0s(?!.*chrome)/i.test(dL)});var jg=g((_F,Hg)=>{"use strict";var nr=oe(),pL=$g(),Og=Ji(),Ul=Nl().set,hL=ql(),fL=$l(),mL=Bg(),bL=_g(),Hl=wn(),Fg=nr.MutationObserver||nr.WebKitMutationObserver,Ng=nr.document,qg=nr.process,An=nr.Promise,Wl=pL("queueMicrotask"),ar,jl,Ql,Pn,Ug;Wl||(ys=new hL,Ts=function(){var s,e;for(Hl&&(s=qg.domain)&&s.exit();e=ys.get();)try{e()}catch(t){throw ys.head&&ar(),t}s&&s.enter()},!fL&&!Hl&&!bL&&Fg&&Ng?(jl=!0,Ql=Ng.createTextNode(""),new Fg(Ts).observe(Ql,{characterData:!0}),ar=function(){Ql.data=jl=!jl}):!mL&&An&&An.resolve?(Pn=An.resolve(void 0),Pn.constructor=An,Ug=Og(Pn.then,Pn),ar=function(){Ug(Ts)}):Hl?ar=function(){qg.nextTick(Ts)}:(Ul=Og(Ul,nr),ar=function(){Ul(Ts)}),Wl=function(s){ys.head||ar(),ys.add(s)});var ys,Ts;Hg.exports=Wl});var Wg=g((OF,Qg)=>{"use strict";Qg.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Rn=g((FF,Gg)=>{"use strict";Gg.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var xi=g((NF,zg)=>{"use strict";var gL=oe();zg.exports=gL.Promise});var or=g((qF,Jg)=>{"use strict";var vL=oe(),Is=xi(),SL=ue(),yL=Uu(),TL=Pl(),IL=ye(),Yg=wl(),EL=st(),Gl=ku(),Kg=Is&&Is.prototype,xL=IL("species"),zl=!1,Xg=SL(vL.PromiseRejectionEvent),wL=yL("Promise",function(){var s=TL(Is),e=s!==String(Is);if(!e&&Gl===66||EL&&!(Kg.catch&&Kg.finally))return!0;if(!Gl||Gl<51||!/native code/.test(s)){var t=new Is(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[xL]=i,zl=t.then(function(){})instanceof i,!zl)return!0}return!e&&(Yg==="BROWSER"||Yg==="DENO")&&!Xg});Jg.exports={CONSTRUCTOR:wL,REJECTION_EVENT:Xg,SUBCLASSING:zl}});var ur=g((UF,ev)=>{"use strict";var Zg=ft(),AL=TypeError,PL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new AL("Bad Promise constructor");e=i,t=r}),this.resolve=Zg(e),this.reject=Zg(t)};ev.exports.f=function(s){return new PL(s)}});var yv=g(()=>{"use strict";var RL=pe(),kL=st(),Mn=wn(),Gt=oe(),LL=gi(),pr=He(),tv=sr(),iv=Sl(),$L=hs(),ML=ig(),DL=ft(),$n=ue(),CL=Me(),BL=sg(),VL=Ll(),ov=Nl().set,Zl=jg(),_L=Wg(),OL=Rn(),FL=ql(),uv=nl(),Dn=xi(),ec=or(),lv=ur(),Cn="Promise",cv=ec.CONSTRUCTOR,NL=ec.REJECTION_EVENT,qL=ec.SUBCLASSING,Yl=uv.getterFor(Cn),UL=uv.set,lr=Dn&&Dn.prototype,wi=Dn,kn=lr,dv=Gt.TypeError,Kl=Gt.document,tc=Gt.process,Xl=lv.f,HL=Xl,jL=!!(Kl&&Kl.createEvent&&Gt.dispatchEvent),pv="unhandledrejection",QL="rejectionhandled",rv=0,hv=1,WL=2,ic=1,fv=2,Ln,sv,mv,av,bv=function(s){var e;return CL(s)&&$n(e=s.then)?e:!1},gv=function(s,e){var t=e.value,i=e.state===hv,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,c;try{r?(i||(e.rejection===fv&&zL(e),e.rejection=ic),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===s.promise?n(new dv("Promise-chain cycle")):(l=bv(u))?pr(l,u,a,n):a(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},vv=function(s,e){s.notified||(s.notified=!0,Zl(function(){for(var t=s.reactions,i;i=t.get();)gv(i,s);s.notified=!1,e&&!s.rejection&&GL(s)}))},Sv=function(s,e,t){var i,r;jL?(i=Kl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Gt.dispatchEvent(i)):i={promise:e,reason:t},!NL&&(r=Gt["on"+s])?r(i):s===pv&&_L("Unhandled promise rejection",t)},GL=function(s){pr(ov,Gt,function(){var e=s.facade,t=s.value,i=nv(s),r;if(i&&(r=OL(function(){Mn?tc.emit("unhandledRejection",t,e):Sv(pv,e,t)}),s.rejection=Mn||nv(s)?fv:ic,r.error))throw r.value})},nv=function(s){return s.rejection!==ic&&!s.parent},zL=function(s){pr(ov,Gt,function(){var e=s.facade;Mn?tc.emit("rejectionHandled",e):Sv(QL,e,s.value)})},cr=function(s,e,t){return function(i){s(e,i,t)}},dr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=WL,vv(s,!0))},Jl=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new dv("Promise can't be resolved itself");var i=bv(e);i?Zl(function(){var r={done:!1};try{pr(i,e,cr(Jl,r,s),cr(dr,r,s))}catch(a){dr(r,a,s)}}):(s.value=e,s.state=hv,vv(s,!1))}catch(r){dr({done:!1},r,s)}}};if(cv&&(wi=function(e){BL(this,kn),DL(e),pr(Ln,this);var t=Yl(this);try{e(cr(Jl,t),cr(dr,t))}catch(i){dr(t,i)}},kn=wi.prototype,Ln=function(e){UL(this,{type:Cn,done:!1,notified:!1,parent:!1,reactions:new FL,rejection:!1,state:rv,value:null})},Ln.prototype=tv(kn,"then",function(e,t){var i=Yl(this),r=Xl(VL(this,wi));return i.parent=!0,r.ok=$n(e)?e:!0,r.fail=$n(t)&&t,r.domain=Mn?tc.domain:void 0,i.state===rv?i.reactions.add(r):Zl(function(){gv(r,i)}),r.promise}),sv=function(){var s=new Ln,e=Yl(s);this.promise=s,this.resolve=cr(Jl,e),this.reject=cr(dr,e)},lv.f=Xl=function(s){return s===wi||s===mv?new sv(s):HL(s)},!kL&&$n(Dn)&&lr!==Object.prototype)){av=lr.then,qL||tv(lr,"then",function(e,t){var i=this;return new wi(function(r,a){pr(av,i,r,a)}).then(e,t)},{unsafe:!0});try{delete lr.constructor}catch(s){}iv&&iv(lr,kn)}RL({global:!0,constructor:!0,wrap:!0,forced:cv},{Promise:wi});mv=LL.Promise;$L(wi,Cn,!1,!0);ML(Cn)});var wv=g((QF,xv)=>{"use strict";var YL=ye(),Iv=YL("iterator"),Ev=!1;try{Tv=0,rc={next:function(){return{done:!!Tv++}},return:function(){Ev=!0}},rc[Iv]=function(){return this},Array.from(rc,function(){throw 2})}catch(s){}var Tv,rc;xv.exports=function(s,e){try{if(!e&&!Ev)return!1}catch(r){return!1}var t=!1;try{var i={};i[Iv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var sc=g((WF,Av)=>{"use strict";var KL=xi(),XL=wv(),JL=or().CONSTRUCTOR;Av.exports=JL||!XL(function(s){KL.all(s).then(void 0,function(){})})});var Pv=g(()=>{"use strict";var ZL=pe(),e$=He(),t$=ft(),i$=ur(),r$=Rn(),s$=In(),a$=sc();ZL({target:"Promise",stat:!0,forced:a$},{all:function(e){var t=this,i=i$.f(t),r=i.resolve,a=i.reject,n=r$(function(){var o=t$(t.resolve),u=[],l=0,c=1;s$(e,function(d){var f=l++,p=!1;c++,e$(o,t,d).then(function(h){p||(p=!0,u[f]=h,--c||r(u))},a)}),--c||r(u)});return n.error&&a(n.value),i.promise}})});var kv=g(()=>{"use strict";var n$=pe(),o$=st(),u$=or().CONSTRUCTOR,nc=xi(),l$=Pt(),c$=ue(),d$=sr(),Rv=nc&&nc.prototype;n$({target:"Promise",proto:!0,forced:u$,real:!0},{catch:function(s){return this.then(void 0,s)}});!o$&&c$(nc)&&(ac=l$("Promise").prototype.catch,Rv.catch!==ac&&d$(Rv,"catch",ac,{unsafe:!0}));var ac});var Lv=g(()=>{"use strict";var p$=pe(),h$=He(),f$=ft(),m$=ur(),b$=Rn(),g$=In(),v$=sc();p$({target:"Promise",stat:!0,forced:v$},{race:function(e){var t=this,i=m$.f(t),r=i.reject,a=b$(function(){var n=f$(t.resolve);g$(e,function(o){h$(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var $v=g(()=>{"use strict";var S$=pe(),y$=ur(),T$=or().CONSTRUCTOR;S$({target:"Promise",stat:!0,forced:T$},{reject:function(e){var t=y$.f(this),i=t.reject;return i(e),t.promise}})});var oc=g((tN,Mv)=>{"use strict";var I$=mt(),E$=Me(),x$=ur();Mv.exports=function(s,e){if(I$(s),E$(e)&&e.constructor===s)return e;var t=x$.f(s),i=t.resolve;return i(e),t.promise}});var Bv=g(()=>{"use strict";var w$=pe(),A$=Pt(),Dv=st(),P$=xi(),Cv=or().CONSTRUCTOR,R$=oc(),k$=A$("Promise"),L$=Dv&&!Cv;w$({target:"Promise",stat:!0,forced:Dv||Cv},{resolve:function(e){return R$(L$&&this===k$?P$:this,e)}})});var Vv=g(()=>{"use strict";yv();Pv();kv();Lv();$v();Bv()});var Nv=g(()=>{"use strict";var $$=pe(),M$=st(),Bn=xi(),D$=he(),Ov=Pt(),Fv=ue(),C$=Ll(),_v=oc(),B$=sr(),lc=Bn&&Bn.prototype,V$=!!Bn&&D$(function(){lc.finally.call({then:function(){}},function(){})});$$({target:"Promise",proto:!0,real:!0,forced:V$},{finally:function(s){var e=C$(this,Ov("Promise")),t=Fv(s);return this.then(t?function(i){return _v(e,s()).then(function(){return i})}:s,t?function(i){return _v(e,s()).then(function(){throw i})}:s)}});!M$&&Fv(Bn)&&(uc=Ov("Promise").prototype.finally,lc.finally!==uc&&B$(lc,"finally",uc,{unsafe:!0}));var uc});var Uv=g((uN,qv)=>{"use strict";Yb();Vv();Nv();var _$=Wt();qv.exports=_$("Promise","finally")});var jv=g((lN,Hv)=>{"use strict";var O$=Uv();Hv.exports=O$});var Vn=g((cN,Qv)=>{"use strict";var F$=jv();Qv.exports=F$});var yS=g(()=>{"use strict";var TM=pe(),IM=Ki(),EM=ir(),xM=ls(),wM=cs();TM({target:"Array",proto:!0},{at:function(e){var t=IM(this),i=EM(t),r=xM(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});wM("at")});var IS=g((tU,TS)=>{"use strict";yS();var AM=Wt();TS.exports=AM("Array","at")});var xS=g((iU,ES)=>{"use strict";var PM=IS();ES.exports=PM});var ot=g((rU,wS)=>{"use strict";var RM=xS();wS.exports=RM});var Cc=g((z1,ny)=>{"use strict";var uD=mi();ny.exports=Array.isArray||function(e){return uD(e)==="Array"}});var uy=g((Y1,oy)=>{"use strict";var lD=TypeError,cD=9007199254740991;oy.exports=function(s){if(s>cD)throw lD("Maximum allowed index exceeded");return s}});var dy=g((K1,cy)=>{"use strict";var dD=Cc(),pD=ir(),hD=uy(),fD=Ji(),ly=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,c=n?fD(n,o):!1,d,f;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],a>0&&dD(d)?(f=pD(d),u=ly(s,e,d,f,u,a-1)-1):(hD(u+1),s[u]=d),u++),l++;return u};cy.exports=ly});var my=g((X1,fy)=>{"use strict";var py=Cc(),mD=kl(),bD=Me(),gD=ye(),vD=gD("species"),hy=Array;fy.exports=function(s){var e;return py(s)&&(e=s.constructor,mD(e)&&(e===hy||py(e.prototype))?e=void 0:bD(e)&&(e=e[vD],e===null&&(e=void 0))),e===void 0?hy:e}});var gy=g((J1,by)=>{"use strict";var SD=my();by.exports=function(s,e){return new(SD(s))(e===0?0:e)}});var vy=g(()=>{"use strict";var yD=pe(),TD=dy(),ID=ft(),ED=Ki(),xD=ir(),wD=gy();yD({target:"Array",proto:!0},{flatMap:function(e){var t=ED(this),i=xD(t),r;return ID(e),r=wD(t,0),r.length=TD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Sy=g(()=>{"use strict";var AD=cs();AD("flatMap")});var Ty=g((rH,yy)=>{"use strict";vy();Sy();var PD=Wt();yy.exports=PD("Array","flatMap")});var Ey=g((sH,Iy)=>{"use strict";var RD=Ty();Iy.exports=RD});var Os=g((aH,xy)=>{"use strict";var kD=Ey();xy.exports=kD});var Fs=g((nH,wy)=>{"use strict";var LD=ps(),$D=String;wy.exports=function(s){if(LD(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return $D(s)}});var Bc=g((oH,Ay)=>{"use strict";Ay.exports=`
|
|
7
|
-
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var ky=g((uH,Ry)=>{"use strict";var MD=fe(),DD=Qt(),CD=Fs(),_c=Bc(),Py=MD("".replace),BD=RegExp("^["+_c+"]+"),VD=RegExp("(^|[^"+_c+"])["+_c+"]+$"),Vc=function(s){return function(e){var t=CD(DD(e));return s&1&&(t=Py(t,BD,"")),s&2&&(t=Py(t,VD,"$1")),t}};Ry.exports={start:Vc(1),end:Vc(2),trim:Vc(3)}});var Dy=g((lH,My)=>{"use strict";var _D=ll().PROPER,OD=he(),Ly=Bc(),$y="\u200B\x85\u180E";My.exports=function(s){return OD(function(){return!!Ly[s]()||$y[s]()!==$y||_D&&Ly[s].name!==s})}});var Oc=g((cH,Cy)=>{"use strict";var FD=ky().start,ND=Dy();Cy.exports=ND("trimStart")?function(){return FD(this)}:"".trimStart});var Vy=g(()=>{"use strict";var qD=pe(),By=Oc();qD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==By},{trimLeft:By})});var Oy=g(()=>{"use strict";Vy();var UD=pe(),_y=Oc();UD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==_y},{trimStart:_y})});var Ny=g((mH,Fy)=>{"use strict";Oy();var HD=Wt();Fy.exports=HD("String","trimLeft")});var Uy=g((bH,qy)=>{"use strict";var jD=Ny();qy.exports=jD});var jy=g((gH,Hy)=>{"use strict";var QD=Uy();Hy.exports=QD});var nT=g(()=>{"use strict"});var oT=g(()=>{"use strict"});var lT=g((rW,uT)=>{"use strict";var mC=Me(),bC=mi(),gC=ye(),vC=gC("match");uT.exports=function(s){var e;return mC(s)&&((e=s[vC])!==void 0?!!e:bC(s)==="RegExp")}});var pT=g((sW,dT)=>{"use strict";var SC=oe(),yC=he(),cT=SC.RegExp,TC=!yC(function(){var s=!0;try{cT(".","d")}catch(u){s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor(cT.prototype,"flags").get.call(e);return o!==i||t!==i});dT.exports={correct:TC}});var fT=g((aW,hT)=>{"use strict";var IC=mt();hT.exports=function(){var s=IC(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var gT=g((nW,bT)=>{"use strict";var EC=He(),xC=at(),wC=rs(),mT=pT(),AC=fT(),PC=RegExp.prototype;bT.exports=mT.correct?function(s){return s.flags}:function(s){return!mT.correct&&wC(PC,s)&&!xC(s,"flags")?EC(AC,s):s.flags}});var ST=g((oW,vT)=>{"use strict";var Hc=fe(),RC=Ki(),kC=Math.floor,qc=Hc("".charAt),LC=Hc("".replace),Uc=Hc("".slice),$C=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,MC=/\$([$&'`]|\d{1,2})/g;vT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=MC;return r!==void 0&&(r=RC(r),u=$C),LC(a,u,function(l,c){var d;switch(qc(c,0)){case"$":return"$";case"&":return s;case"`":return Uc(e,0,t);case"'":return Uc(e,n);case"<":d=r[Uc(c,1,-1)];break;default:var f=+c;if(f===0)return l;if(f>o){var p=kC(f/10);return p===0?l:p<=o?i[p-1]===void 0?qc(c,1):i[p-1]+qc(c,1):l}d=i[f-1]}return d===void 0?"":d})}});var IT=g(()=>{"use strict";var DC=pe(),CC=He(),Qc=fe(),yT=Qt(),BC=ue(),VC=Me(),_C=lT(),Ar=Fs(),OC=as(),FC=gT(),NC=ST(),qC=ye(),UC=st(),HC=qC("replace"),jC=TypeError,jc=Qc("".indexOf),QC=Qc("".replace),TT=Qc("".slice),WC=Math.max;DC({target:"String",proto:!0},{replaceAll:function(e,t){var i=yT(this),r,a,n,o,u,l,c,d,f,p,h=0,m="";if(VC(e)){if(r=_C(e),r&&(a=Ar(yT(FC(e))),!~jc(a,"g")))throw new jC("`.replaceAll` does not allow non-global regexes");if(n=OC(e,HC),n)return CC(n,e,i,t);if(UC&&r)return QC(Ar(i),e,t)}for(o=Ar(i),u=Ar(e),l=BC(t),l||(t=Ar(t)),c=u.length,d=WC(1,c),f=jc(o,u);f!==-1;)p=l?Ar(t(u,f,o)):NC(u,o,f,[],void 0,t),m+=TT(o,h,f)+p,h=f+c,f=f+d>o.length?-1:jc(o,u,f+d);return h<o.length&&(m+=TT(o,h)),m}})});var xT=g((cW,ET)=>{"use strict";nT();oT();IT();var GC=Wt();ET.exports=GC("String","replaceAll")});var AT=g((dW,wT)=>{"use strict";var zC=xT();wT.exports=zC});var RT=g((pW,PT)=>{"use strict";var YC=AT();PT.exports=YC});var LT=g((hW,kT)=>{"use strict";var KC=ls(),XC=Fs(),JC=Qt(),ZC=RangeError;kT.exports=function(e){var t=XC(JC(this)),i="",r=KC(e);if(r<0||r===1/0)throw new ZC("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var BT=g((fW,CT)=>{"use strict";var DT=fe(),eB=Yu(),$T=Fs(),tB=LT(),iB=Qt(),rB=DT(tB),sB=DT("".slice),aB=Math.ceil,MT=function(s){return function(e,t,i){var r=$T(iB(e)),a=eB(t),n=r.length,o=i===void 0?" ":$T(i),u,l;return a<=n||o===""?r:(u=a-n,l=rB(o,aB(u/o.length)),l.length>u&&(l=sB(l,0,u)),s?r+l:l+r)}};CT.exports={start:MT(!1),end:MT(!0)}});var _T=g((mW,VT)=>{"use strict";var nB=vi();VT.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(nB)});var OT=g(()=>{"use strict";var oB=pe(),uB=BT().start,lB=_T();oB({target:"String",proto:!0,forced:lB},{padStart:function(e){return uB(this,e,arguments.length>1?arguments[1]:void 0)}})});var NT=g((vW,FT)=>{"use strict";OT();var cB=Wt();FT.exports=cB("String","padStart")});var UT=g((SW,qT)=>{"use strict";var dB=NT();qT.exports=dB});var jT=g((yW,HT)=>{"use strict";var pB=UT();HT.exports=pB});var Wp="2.0.140-dev.4c27f703.0";var $e=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))($e||{}),At=(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))(At||{});var en=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(en||{}),gu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(gu||{});var vu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(vu||{}),tn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(tn||{});var np=O(yi(),1),NE=O(Ae(),1);import{assertNever as fm,assertNonNullable as zA,isNonNullable as cn,ValueSubject as tl,Subject as YA,Subscription as KA,merge as XA,observableFrom as JA,fromEvent as cm,map as dm,tap as pm,filterChanged as ZA,isNullable as il,ErrorCategory as hm}from"@vkontakte/videoplayer-shared/es2018";var lm=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var dn=class{constructor(e){this.connection$=new tl(void 0);this.castState$=new tl("NOT_AVAILABLE");this.errorEvent$=new YA;this.realCastState$=new tl("NOT_AVAILABLE");this.subscription=new KA;this.isDestroyed=!1;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=cn((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||lm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:hm.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){cn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();il(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();il(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(cm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return fm(r.sessionState)}})).add(XA(cm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(pm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),dm(r=>r.castState)),JA([i.getCastState()])).pipe(ZA(),dm(eP),pm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=cn(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();zA(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(il(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?cn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:hm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},eP=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return fm(s)}};var Jd=O(Ae(),1),TE=O(rr(),1),IE=O(xl(),1);var oS=O(Vn(),1);import{assertNever as Wv}from"@vkontakte/videoplayer-shared/es2018";var le=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Wv(t)}return s},zt=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:Wv(e)}};var L=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as N$,Subject as _n,merge as Gv}from"@vkontakte/videoplayer-shared/es2018";var H=class{constructor(e){this.transitionStarted$=new _n;this.transitionEnded$=new _n;this.transitionUpdated$=new _n;this.forceChanged$=new _n;this.stateChangeStarted$=Gv(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Gv(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||N$(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 eS}from"@vkontakte/videoplayer-shared/es2018";var On=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var zv=O(Ae(),1);var Es=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Fn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,zv.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Es()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Nn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var Qe=()=>window.ManagedMediaSource||window.MediaSource,hr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Yv=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},qn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var q$=document.createElement("video"),U$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',H$='video/mp4; codecs="hev1.1.6.L93.B0"',Kv='video/webm; codecs="vp09.00.10.08"',Xv='video/webm; codecs="av01.0.00M.08"',j$='audio/mp4; codecs="mp4a.40.2"',Q$='audio/webm; codecs="opus"',Jv,W$=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Xv}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Kv}})]);Jv={DASH_WEBM_AV1:e,DASH_WEBM:t}};W$().catch(s=>{console.log(q$),console.error(s)});var Un=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 Jv}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,c,d,f,p,h,m,v,b,S,T,y;this._video=document.createElement("video");try{this._protocols={mms:hr(),mse:Yv(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let E=!!((c=(l=Qe())==null?void 0:l.isTypeSupported)!=null&&c.call(l,U$)),k=!!((f=(d=Qe())==null?void 0:d.isTypeSupported)!=null&&f.call(d,H$)),M=!!((h=(p=Qe())==null?void 0:p.isTypeSupported)!=null&&h.call(p,j$));this._codecs={h264:E,h265:k,vp9:!!((v=(m=Qe())==null?void 0:m.isTypeSupported)!=null&&v.call(m,Kv)),av1:!!((S=(b=Qe())==null?void 0:b.isTypeSupported)!=null&&S.call(b,Xv)),aac:M,opus:!!((y=(T=Qe())==null?void 0:T.isTypeSupported)!=null&&y.call(T,Q$)),mpeg:(E||k)&&M},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(E){console.error(E)}try{this.destroyVideoElement()}catch(E){console.error("Error destroying video element:",E)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Zv="audio/mpeg",Hn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Zv))},this._codecs={mp3:!!((r=(i=Qe())==null?void 0:i.isTypeSupported)!=null&&r.call(i,Zv))}}catch(a){console.error(a)}try{this.destroyAudioElement()}catch(a){console.error("Error destroying audio element:",a)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as G$}from"@vkontakte/videoplayer-shared/es2018";var cc=class{constructor(){this.isInited$=new G$(!1);this._displayChecker=new Nn,this._deviceChecker=new Fn(this._displayChecker),this._browserChecker=new On,this._videoChecker=new Un(this._deviceChecker,this._browserChecker),this._audioChecker=new Hn,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(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},F=new cc;var dc=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=F.video,a=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return s.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&a;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&a||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&a;case"DASH_LIVE_CMAF":return n&&e.mp4&&a&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&a;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return eS(o)}})},pc=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return eS(s)}},z$=s=>{let t=Object.keys(s).filter(i=>!pc(i));return dc(t).length>0};import{assertNever as fr,assertNonNullable as Ai,debounce as tS,ErrorCategory as iS,fromEvent as Pi,isNonNullable as rS,map as sS,merge as aS,observableFrom as Y$,Subject as K$,Subscription as hc,timeout as X$,getHighestQuality as J$}from"@vkontakte/videoplayer-shared/es2018";var Z$=5,eM=5,tM=500,nS=7e3,xs=class{constructor(e){this.subscription=new hc;this.loadMediaTimeoutSubscription=new hc;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:fr(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:fr(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:fr(e)}break}default:fr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(pc(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 hc;this.subscription.add(e),this.subscription.add(aS(this.videoState.stateChangeStarted$.pipe(sS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(sS(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new K$;e.add(r.pipe(tS(tM)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(Pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>Z$)&&r.next(o),a=o})),e.add(Pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<eM&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),L(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:fr(n)}}),t(Pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=aS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Y$(["init"])).pipe(tS(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"),L(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),L(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),L(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"),L(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"&&L(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let c=t[e];Ai(c);let d=J$(Object.keys(c));Ai(d);let f=c[d];Ai(f),i=f,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=t[e];Ai(c),i=c.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];Ai(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Ai(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Ai(c),i=le(c.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:iS.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return fr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return rS(o)&&(n.metadata.title=o),rS(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(X$(nS).subscribe(()=>a(`timeout(${nS})`)))});(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 a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:iS.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Mc=O(Ae(),1);import{clearVideoElement as lS}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as iM}from"@vkontakte/videoplayer-shared/es2018";var uS=s=>{try{s.pause(),s.playbackRate=0,iM(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as rM,Subscription as sM}from"@vkontakte/videoplayer-shared/es2018";var fc=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)}},mc=window.WeakMap?new WeakMap:new fc,bc=window.WeakMap?new WeakMap:new Map,aM=(s,e=20)=>{let t=0;return rM(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},De=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?lS(i):(i=document.createElement("video"),s.appendChild(i)),mc.set(i,r);let a=new sM;return a.add(aM(i,e)),bc.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ce=s=>{let e=bc.get(s);e==null||e.unsubscribe(),bc.delete(s);let t=mc.get(s);mc.delete(s),t?lS(s):uS(s)};var vc=O(yi(),1);import{assertNonNullable as As,isNonNullable as gt,isNullable as uM,fromEvent as mr,merge as cS,observableFrom as dS,filterChanged as pS,map as Ps,Subject as hS,Subscription as lM,ValueSubject as cM,ErrorCategory as dM}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as gc,isNullable as nM,Subscription as oM}from"@vkontakte/videoplayer-shared/es2018";var jn=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=nM(r),l=new oM;return r&&l.add(r.subscribe(c=>{let d=s.getState();i(c,d)&&s.setState(c)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),u&&s.setState(c.to)},a)),l},bt=(s,e,t)=>jn(e,()=>s.loop,i=>{gc(i)&&(s.loop=i)},{onError:t}),Be=(s,e,t,i)=>jn(e,()=>({muted:s.muted,volume:s.volume}),r=>{gc(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Ke=(s,e,t,i)=>jn(e,()=>s.playbackRate,r=>{gc(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),ws=jn;var pM=s=>["__",s.language,s.label].join("|"),hM=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Sc=class s{constructor(e){this.available$=new hS;this.current$=new cM(void 0);this.error$=new hS;this.subscription=new lM;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:dM.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ws(t.internalTextTracks,()=>(0,vc.default)(this.internalTracks),a=>{gt(a)&&this.setInternal(a)},{equal:(a,n)=>gt(a)&>(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ps(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ws(t.externalTextTracks,()=>(0,vc.default)(this.externalTracks),a=>{gt(a)&&this.setExternal(a)},{equal:(a,n)=>gt(a)&>(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ps(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ws(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(ws(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){As(this.video);let{textTracks:e}=this.video;this.subscription.add(mr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(cS(mr(e,"addtrack"),mr(e,"removetrack"),dS(["init"])).pipe(Ps(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),pS((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(cS(mr(e,"change"),dS(["init"])).pipe(Ps(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ps(i=>i&&this.htmlTextTrackToITextTrack(i).id),pS()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(mr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,c,d,f,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((f=(d=o.target)==null?void 0:d.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(mr(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;gt(t.align)&&(r.align=t.align),gt(t.position)&&(r.position=t.position),gt(t.size)&&(r.size=t.size),gt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){As(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:pM(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){As(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(uM(e)||!hM(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){As(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){As(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)}},Xe=Sc;var Ri=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 fS=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},yc=s=>{let e=fS(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},mS=s=>{let e=fS(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as Pe,map as vt,merge as Qn,filterChanged as gS,isNonNullable as vS,Subject as mM,filter as Tc,mapTo as Ic,combine as bM,once as gM,shareReplay as Re,throttle as vM,ErrorCategory as SM,ValueSubject as SS,Subscription as yM}from"@vkontakte/videoplayer-shared/es2018";var fM=3,bS=(s,e,t=fM)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var Ve=s=>{let e=P=>Pe(s,P).pipe(Ic(void 0),Re(1)),t=new yM,i=()=>t.unsubscribe(),r=Qn(Pe(s,"progress"),Pe(s,"timeupdate")).pipe(vt(()=>bS(s.buffered,s.currentTime)),Re(1)),a=F.browser.isSafari?bM({play:e("play").pipe(gM()),playing:e("playing")}).pipe(Ic(void 0),Re(1)):e("playing"),n=Pe(s,"volumechange").pipe(vt(()=>({muted:s.muted,volume:s.volume})),Re(1)),o=Pe(s,"ratechange").pipe(vt(()=>s.playbackRate),Re(1)),u=Pe(s,"error").pipe(Tc(()=>!!(s.error||s.played.length)),vt(()=>{var V;let P=s.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:SM.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(V=s.error)!=null?V:void 0}}),Re(1)),l=Pe(s,"timeupdate").pipe(vt(()=>s.currentTime),Re(1)),c=["waiting","seeking","seeked","timeupdate"],d=new mM,f=.3,p;t.add(Qn(...c.map(P=>Pe(s,P))).subscribe(P=>{let V=s.currentTime;s.loop&&vS(p)&&vS(V)&&p>=s.duration-f&&V<=f&&d.next(p),p=V}));let h=e("pause").pipe(Tc(()=>!s.error&&p!==s.duration),Re(1)),m=Pe(s,"enterpictureinpicture").pipe(Re(1)),v=Pe(s,"leavepictureinpicture").pipe(Re(1)),b=new SS(mS(s));t.add(m.subscribe(()=>b.next(!0))),t.add(v.subscribe(()=>b.next(!1)));let S=new SS(yc(s)),T=Pe(s,"fullscreenchange").pipe(Re(1));t.add(T.pipe(vt(()=>yc(s))).subscribe(S));let y=.1,E=1e3,k=Pe(s,"timeupdate").pipe(vt(P=>s.duration-s.currentTime<y),gS(),Re(1)),M=Qn(k.pipe(Tc(P=>!s.loop&&P)),Pe(s,"ended")).pipe(vM(E),Ic(void 0),Re(1)),A=Qn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Pe(s,P)),k.pipe(vt(P=>({type:P?"ended":"unknown"})))).pipe(vt(P=>F.browser.isFirefox&&P.type==="ended"?s.readyState<2:s.readyState<3),gS(),Re(1));return{playing$:a,pause$:h,canplay$:e("canplay"),ended$:M,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Pe(s,"durationchange").pipe(vt(()=>s.duration),Re(1)),isBuffering$:A,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:b,inFullscreen$:S,enterPip$:m,leavePip$:v,destroy:i}};import{VideoQuality as Yt}from"@vkontakte/videoplayer-shared/es2018";var Kt=s=>{switch(s){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 Le=O(ot(),1),wc=O(Ae(),1),ki=O(rr(),1);import{isNonNullable as X,isNullable as Kn,now as BS,isHigher as Xn,isHigherOrEqual as gr,isInvariantQuality as Jn,isLowerOrEqual as vr,videoSizeToQuality as VS,assertNotEmptyArray as Zn,assertNonNullable as _S}from"@vkontakte/videoplayer-shared/es2018";var Ec=!1,Lt={},AS=s=>{Ec=s},PS=()=>{Lt={}},RS=s=>{s(Lt)},Rs=(s,e)=>{var t;Ec&&(Lt.meta=(t=Lt.meta)!=null?t:{},Lt.meta[s]=e)},ke=class{constructor(e){this.name=e}next(e){var i,r;if(!Ec)return;Lt.series=(i=Lt.series)!=null?i:{};let t=(r=Lt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Lt.series[this.name]=t}};import{isHigher as kM,isHigherOrEqual as lU,isLower as kS,isLowerOrEqual as cU,isNonNullable as Wn,isNullable as LM,videoHeightToQuality as Gn}from"@vkontakte/videoplayer-shared/es2018";function xc(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function zn(s,e,t){return!!s&&xc(s,e,t)==="high_quality"}function br(s,e,t){return LM(s)||Wn(s.min)&&Wn(s.max)&&kS(s.max,s.min)||Wn(s.min)&&e&&kM(s.min,e)||Wn(s.max)&&t&&kS(s.max,t)}function LS({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return br({max:s!=null&&s.max?Gn(s.max):void 0,min:s!=null&&s.min?Gn(s.min):void 0},e?Gn(e):void 0,t?Gn(t):void 0)}var OS=new ke("best_bitrate"),eo=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Sr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=BS()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},to='Assertion "ABR Tracks is empty array" failed',Yn=new WeakMap,$S=new WeakMap,MS=new WeakMap,ks=(s,e,t,i)=>{var u;let r=[...e].sort(Sr(1)),a=[...t].sort(Sr(1)),n=a.filter(l=>X(l.bitrate)&&X(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,Le.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Le.default)(a,-1);return o&&(0,wc.default)(n,o)?o:n.length?(0,Le.default)(n,-1):(0,Le.default)(a,0)},Ls=(s,e,t,i)=>{var u;let r=Yn.get(e);r||(r=[...e].sort(Sr(1)),Yn.set(e,r));let a=Yn.get(t);a||(a=[...t].sort(Sr(1)),Yn.set(t,a));let n=MS.get(s);n||(n=a.filter(l=>X(l.bitrate)&&X(s.bitrate)?s.bitrate/l.bitrate>i:!0),MS.set(s,n));let o=(u=(0,Le.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Le.default)(a,-1);return o&&(0,wc.default)(n,o)?o:n.length?(0,Le.default)(n,-1):(0,Le.default)(a,0)},DS=s=>"quality"in s,io=(s,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?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&BS()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=DS(o)?"video":"audio",l=DS(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var YE=Object.create;var Gp=Object.defineProperty;var KE=Object.getOwnPropertyDescriptor;var XE=Object.getOwnPropertyNames;var JE=Object.getPrototypeOf,ZE=Object.prototype.hasOwnProperty;var S=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var ex=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of XE(e))!ZE.call(s,r)&&r!==t&&Gp(s,r,{get:()=>e[r],enumerable:!(i=KE(e,r))||i.enumerable});return s};var O=(s,e,t)=>(t=s!=null?YE(JE(s)):{},ex(e||!s||!s.__esModule?Gp(t,"default",{value:s,enumerable:!0}):t,s));var ne=S((wu,Yp)=>{"use strict";var es=function(s){return s&&s.Math===Math&&s};Yp.exports=es(typeof globalThis=="object"&&globalThis)||es(typeof window=="object"&&window)||es(typeof self=="object"&&self)||es(typeof global=="object"&&global)||es(typeof wu=="object"&&wu)||function(){return this}()||Function("return this")()});var fe=S((u_,Kp)=>{"use strict";Kp.exports=function(s){try{return!!s()}catch(e){return!0}}});var ts=S((l_,Xp)=>{"use strict";var tx=fe();Xp.exports=!tx(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Au=S((c_,th)=>{"use strict";var ix=ts(),eh=Function.prototype,Jp=eh.apply,Zp=eh.call;th.exports=typeof Reflect=="object"&&Reflect.apply||(ix?Zp.bind(Jp):function(){return Zp.apply(Jp,arguments)})});var me=S((d_,sh)=>{"use strict";var ih=ts(),rh=Function.prototype,Ru=rh.call,rx=ih&&rh.bind.bind(Ru,Ru);sh.exports=ih?rx:function(s){return function(){return Ru.apply(s,arguments)}}});var gi=S((p_,nh)=>{"use strict";var ah=me(),sx=ah({}.toString),ax=ah("".slice);nh.exports=function(s){return ax(sx(s),8,-1)}});var Pu=S((h_,oh)=>{"use strict";var nx=gi(),ox=me();oh.exports=function(s){if(nx(s)==="Function")return ox(s)}});var oe=S((f_,uh)=>{"use strict";var ku=typeof document=="object"&&document.all;uh.exports=typeof ku=="undefined"&&ku!==void 0?function(s){return typeof s=="function"||s===ku}:function(s){return typeof s=="function"}});var Ne=S((m_,lh)=>{"use strict";var ux=fe();lh.exports=!ux(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var qe=S((b_,ch)=>{"use strict";var lx=ts(),pn=Function.prototype.call;ch.exports=lx?pn.bind(pn):function(){return pn.apply(pn,arguments)}});var Lu=S(hh=>{"use strict";var dh={}.propertyIsEnumerable,ph=Object.getOwnPropertyDescriptor,cx=ph&&!dh.call({1:2},1);hh.f=cx?function(e){var t=ph(this,e);return!!t&&t.enumerable}:dh});var is=S((S_,fh)=>{"use strict";fh.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var bh=S((v_,mh)=>{"use strict";var dx=me(),px=fe(),hx=gi(),$u=Object,fx=dx("".split);mh.exports=px(function(){return!$u("z").propertyIsEnumerable(0)})?function(s){return hx(s)==="String"?fx(s,""):$u(s)}:$u});var rs=S((y_,gh)=>{"use strict";gh.exports=function(s){return s==null}});var Qt=S((T_,Sh)=>{"use strict";var mx=rs(),bx=TypeError;Sh.exports=function(s){if(mx(s))throw new bx("Can't call method on "+s);return s}});var Si=S((I_,vh)=>{"use strict";var gx=bh(),Sx=Qt();vh.exports=function(s){return gx(Sx(s))}});var De=S((E_,yh)=>{"use strict";var vx=oe();yh.exports=function(s){return typeof s=="object"?s!==null:vx(s)}});var vi=S((x_,Th)=>{"use strict";Th.exports={}});var Rt=S((w_,Eh)=>{"use strict";var Mu=vi(),Du=ne(),yx=oe(),Ih=function(s){return yx(s)?s:void 0};Eh.exports=function(s,e){return arguments.length<2?Ih(Mu[s])||Ih(Du[s]):Mu[s]&&Mu[s][e]||Du[s]&&Du[s][e]}});var ss=S((A_,xh)=>{"use strict";var Tx=me();xh.exports=Tx({}.isPrototypeOf)});var yi=S((R_,Rh)=>{"use strict";var Ix=ne(),wh=Ix.navigator,Ah=wh&&wh.userAgent;Rh.exports=Ah?String(Ah):""});var Bu=S((P_,Dh)=>{"use strict";var Mh=ne(),Cu=yi(),Ph=Mh.process,kh=Mh.Deno,Lh=Ph&&Ph.versions||kh&&kh.version,$h=Lh&&Lh.v8,tt,hn;$h&&(tt=$h.split("."),hn=tt[0]>0&&tt[0]<4?1:+(tt[0]+tt[1]));!hn&&Cu&&(tt=Cu.match(/Edge\/(\d+)/),(!tt||tt[1]>=74)&&(tt=Cu.match(/Chrome\/(\d+)/),tt&&(hn=+tt[1])));Dh.exports=hn});var Vu=S((k_,Bh)=>{"use strict";var Ch=Bu(),Ex=fe(),xx=ne(),wx=xx.String;Bh.exports=!!Object.getOwnPropertySymbols&&!Ex(function(){var s=Symbol("symbol detection");return!wx(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ch&&Ch<41})});var _u=S((L_,Vh)=>{"use strict";var Ax=Vu();Vh.exports=Ax&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Ou=S(($_,_h)=>{"use strict";var Rx=Rt(),Px=oe(),kx=ss(),Lx=_u(),$x=Object;_h.exports=Lx?function(s){return typeof s=="symbol"}:function(s){var e=Rx("Symbol");return Px(e)&&kx(e.prototype,$x(s))}});var as=S((M_,Oh)=>{"use strict";var Mx=String;Oh.exports=function(s){try{return Mx(s)}catch(e){return"Object"}}});var ft=S((D_,Fh)=>{"use strict";var Dx=oe(),Cx=as(),Bx=TypeError;Fh.exports=function(s){if(Dx(s))return s;throw new Bx(Cx(s)+" is not a function")}});var ns=S((C_,Nh)=>{"use strict";var Vx=ft(),_x=rs();Nh.exports=function(s,e){var t=s[e];return _x(t)?void 0:Vx(t)}});var Uh=S((B_,qh)=>{"use strict";var Fu=qe(),Nu=oe(),qu=De(),Ox=TypeError;qh.exports=function(s,e){var t,i;if(e==="string"&&Nu(t=s.toString)&&!qu(i=Fu(t,s))||Nu(t=s.valueOf)&&!qu(i=Fu(t,s))||e!=="string"&&Nu(t=s.toString)&&!qu(i=Fu(t,s)))return i;throw new Ox("Can't convert object to primitive value")}});var it=S((V_,jh)=>{"use strict";jh.exports=!0});var Wh=S((__,Qh)=>{"use strict";var Hh=ne(),Fx=Object.defineProperty;Qh.exports=function(s,e){try{Fx(Hh,s,{value:e,configurable:!0,writable:!0})}catch(t){Hh[s]=e}return e}});var os=S((O_,Yh)=>{"use strict";var Nx=it(),qx=ne(),Ux=Wh(),Gh="__core-js_shared__",zh=Yh.exports=qx[Gh]||Ux(Gh,{});(zh.versions||(zh.versions=[])).push({version:"3.43.0",mode:Nx?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Uu=S((F_,Xh)=>{"use strict";var Kh=os();Xh.exports=function(s,e){return Kh[s]||(Kh[s]=e||{})}});var Zi=S((N_,Jh)=>{"use strict";var jx=Qt(),Hx=Object;Jh.exports=function(s){return Hx(jx(s))}});var rt=S((q_,Zh)=>{"use strict";var Qx=me(),Wx=Zi(),Gx=Qx({}.hasOwnProperty);Zh.exports=Object.hasOwn||function(e,t){return Gx(Wx(e),t)}});var ju=S((U_,ef)=>{"use strict";var zx=me(),Yx=0,Kx=Math.random(),Xx=zx(1.1.toString);ef.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Xx(++Yx+Kx,36)}});var ye=S((j_,rf)=>{"use strict";var Jx=ne(),Zx=Uu(),tf=rt(),ew=ju(),tw=Vu(),iw=_u(),er=Jx.Symbol,Hu=Zx("wks"),rw=iw?er.for||er:er&&er.withoutSetter||ew;rf.exports=function(s){return tf(Hu,s)||(Hu[s]=tw&&tf(er,s)?er[s]:rw("Symbol."+s)),Hu[s]}});var of=S((H_,nf)=>{"use strict";var sw=qe(),sf=De(),af=Ou(),aw=ns(),nw=Uh(),ow=ye(),uw=TypeError,lw=ow("toPrimitive");nf.exports=function(s,e){if(!sf(s)||af(s))return s;var t=aw(s,lw),i;if(t){if(e===void 0&&(e="default"),i=sw(t,s,e),!sf(i)||af(i))return i;throw new uw("Can't convert object to primitive value")}return e===void 0&&(e="number"),nw(s,e)}});var Qu=S((Q_,uf)=>{"use strict";var cw=of(),dw=Ou();uf.exports=function(s){var e=cw(s,"string");return dw(e)?e:e+""}});var fn=S((W_,cf)=>{"use strict";var pw=ne(),lf=De(),Wu=pw.document,hw=lf(Wu)&&lf(Wu.createElement);cf.exports=function(s){return hw?Wu.createElement(s):{}}});var Gu=S((G_,df)=>{"use strict";var fw=Ne(),mw=fe(),bw=fn();df.exports=!fw&&!mw(function(){return Object.defineProperty(bw("div"),"a",{get:function(){return 7}}).a!==7})});var ff=S(hf=>{"use strict";var gw=Ne(),Sw=qe(),vw=Lu(),yw=is(),Tw=Si(),Iw=Qu(),Ew=rt(),xw=Gu(),pf=Object.getOwnPropertyDescriptor;hf.f=gw?pf:function(e,t){if(e=Tw(e),t=Iw(t),xw)try{return pf(e,t)}catch(i){}if(Ew(e,t))return yw(!Sw(vw.f,e,t),e[t])}});var zu=S((Y_,mf)=>{"use strict";var ww=fe(),Aw=oe(),Rw=/#|\.prototype\./,us=function(s,e){var t=kw[Pw(s)];return t===$w?!0:t===Lw?!1:Aw(e)?ww(e):!!e},Pw=us.normalize=function(s){return String(s).replace(Rw,".").toLowerCase()},kw=us.data={},Lw=us.NATIVE="N",$w=us.POLYFILL="P";mf.exports=us});var tr=S((K_,gf)=>{"use strict";var bf=Pu(),Mw=ft(),Dw=ts(),Cw=bf(bf.bind);gf.exports=function(s,e){return Mw(s),e===void 0?s:Dw?Cw(s,e):function(){return s.apply(e,arguments)}}});var Yu=S((X_,Sf)=>{"use strict";var Bw=Ne(),Vw=fe();Sf.exports=Bw&&Vw(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=S((J_,vf)=>{"use strict";var _w=De(),Ow=String,Fw=TypeError;vf.exports=function(s){if(_w(s))return s;throw new Fw(Ow(s)+" is not an object")}});var Ti=S(Tf=>{"use strict";var Nw=Ne(),qw=Gu(),Uw=Yu(),mn=mt(),yf=Qu(),jw=TypeError,Ku=Object.defineProperty,Hw=Object.getOwnPropertyDescriptor,Xu="enumerable",Ju="configurable",Zu="writable";Tf.f=Nw?Uw?function(e,t,i){if(mn(e),t=yf(t),mn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Zu in i&&!i[Zu]){var r=Hw(e,t);r&&r[Zu]&&(e[t]=i.value,i={configurable:Ju in i?i[Ju]:r[Ju],enumerable:Xu in i?i[Xu]:r[Xu],writable:!1})}return Ku(e,t,i)}:Ku:function(e,t,i){if(mn(e),t=yf(t),mn(i),qw)try{return Ku(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new jw("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var ir=S((eO,If)=>{"use strict";var Qw=Ne(),Ww=Ti(),Gw=is();If.exports=Qw?function(s,e,t){return Ww.f(s,e,Gw(1,t))}:function(s,e,t){return s[e]=t,s}});var de=S((tO,xf)=>{"use strict";var ls=ne(),zw=Au(),Yw=Pu(),Kw=oe(),Xw=ff().f,Jw=zu(),rr=vi(),Zw=tr(),sr=ir(),Ef=rt();os();var eA=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return zw(s,this,arguments)};return e.prototype=s.prototype,e};xf.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ls:r?ls[t]:ls[t]&&ls[t].prototype,o=i?rr:rr[t]||sr(rr,t,{})[t],u=o.prototype,l,c,d,f,p,h,m,g,b;for(f in e)l=Jw(i?f:t+(r?".":"#")+f,s.forced),c=!l&&n&&Ef(n,f),h=o[f],c&&(s.dontCallGetSet?(b=Xw(n,f),m=b&&b.value):m=n[f]),p=c&&m?m:e[f],!(!l&&!a&&typeof h==typeof p)&&(s.bind&&c?g=Zw(p,ls):s.wrap&&c?g=eA(p):a&&Kw(p)?g=Yw(p):g=p,(s.sham||p&&p.sham||h&&h.sham)&&sr(g,"sham",!0),sr(o,f,g),a&&(d=t+"Prototype",Ef(rr,d)||sr(rr,d,{}),sr(rr[d],f,p),s.real&&u&&(l||!u[f])&&sr(u,f,p)))}});var bn=S((iO,Af)=>{"use strict";var tA=Uu(),iA=ju(),wf=tA("keys");Af.exports=function(s){return wf[s]||(wf[s]=iA(s))}});var Pf=S((rO,Rf)=>{"use strict";var rA=fe();Rf.exports=!rA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var gn=S((sO,Lf)=>{"use strict";var sA=rt(),aA=oe(),nA=Zi(),oA=bn(),uA=Pf(),kf=oA("IE_PROTO"),el=Object,lA=el.prototype;Lf.exports=uA?el.getPrototypeOf:function(s){var e=nA(s);if(sA(e,kf))return e[kf];var t=e.constructor;return aA(t)&&e instanceof t?t.prototype:e instanceof el?lA:null}});var Mf=S((aO,$f)=>{"use strict";var cA=Math.ceil,dA=Math.floor;$f.exports=Math.trunc||function(e){var t=+e;return(t>0?dA:cA)(t)}});var cs=S((nO,Df)=>{"use strict";var pA=Mf();Df.exports=function(s){var e=+s;return e!==e||e===0?0:pA(e)}});var Bf=S((oO,Cf)=>{"use strict";var hA=cs(),fA=Math.max,mA=Math.min;Cf.exports=function(s,e){var t=hA(s);return t<0?fA(t+e,0):mA(t,e)}});var tl=S((uO,Vf)=>{"use strict";var bA=cs(),gA=Math.min;Vf.exports=function(s){var e=bA(s);return e>0?gA(e,9007199254740991):0}});var ar=S((lO,_f)=>{"use strict";var SA=tl();_f.exports=function(s){return SA(s.length)}});var il=S((cO,Ff)=>{"use strict";var vA=Si(),yA=Bf(),TA=ar(),Of=function(s){return function(e,t,i){var r=vA(e),a=TA(r);if(a===0)return!s&&-1;var n=yA(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};Ff.exports={includes:Of(!0),indexOf:Of(!1)}});var Sn=S((dO,Nf)=>{"use strict";Nf.exports={}});var jf=S((pO,Uf)=>{"use strict";var IA=me(),rl=rt(),EA=Si(),xA=il().indexOf,wA=Sn(),qf=IA([].push);Uf.exports=function(s,e){var t=EA(s),i=0,r=[],a;for(a in t)!rl(wA,a)&&rl(t,a)&&qf(r,a);for(;e.length>i;)rl(t,a=e[i++])&&(~xA(r,a)||qf(r,a));return r}});var sl=S((hO,Hf)=>{"use strict";Hf.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var al=S((fO,Qf)=>{"use strict";var AA=jf(),RA=sl();Qf.exports=Object.keys||function(e){return AA(e,RA)}});var nl=S((mO,Kf)=>{"use strict";var Gf=Ne(),PA=fe(),zf=me(),kA=gn(),LA=al(),$A=Si(),MA=Lu().f,Yf=zf(MA),DA=zf([].push),CA=Gf&&PA(function(){var s=Object.create(null);return s[2]=2,!Yf(s,2)}),Wf=function(s){return function(e){for(var t=$A(e),i=LA(t),r=CA&&kA(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Gf||(r?u in t:Yf(t,u)))&&DA(o,s?[u,t[u]]:t[u]);return o}};Kf.exports={entries:Wf(!0),values:Wf(!1)}});var Xf=S(()=>{"use strict";var BA=de(),VA=nl().values;BA({target:"Object",stat:!0},{values:function(e){return VA(e)}})});var Zf=S((SO,Jf)=>{"use strict";Xf();var _A=vi();Jf.exports=_A.Object.values});var tm=S((vO,em)=>{"use strict";var OA=Zf();em.exports=OA});var Ii=S((yO,im)=>{"use strict";var FA=tm();im.exports=FA});var ds=S((TO,rm)=>{"use strict";rm.exports=function(){}});var sm=S(()=>{"use strict";var NA=de(),qA=il().includes,UA=fe(),jA=ds(),HA=UA(function(){return!Array(1).includes()});NA({target:"Array",proto:!0,forced:HA},{includes:function(e){return qA(this,e,arguments.length>1?arguments[1]:void 0)}});jA("includes")});var Wt=S((xO,am)=>{"use strict";var QA=Rt();am.exports=QA});var om=S((wO,nm)=>{"use strict";sm();var WA=Wt();nm.exports=WA("Array","includes")});var lm=S((AO,um)=>{"use strict";var GA=om();um.exports=GA});var Ce=S((RO,cm)=>{"use strict";var zA=lm();cm.exports=zA});var gm=S(()=>{"use strict";var iR=de(),rR=nl().entries;iR({target:"Object",stat:!0},{entries:function(e){return rR(e)}})});var vm=S((qO,Sm)=>{"use strict";gm();var sR=vi();Sm.exports=sR.Object.entries});var Tm=S((UO,ym)=>{"use strict";var aR=vm();ym.exports=aR});var nr=S((jO,Im)=>{"use strict";var nR=Tm();Im.exports=nR});var Ei=S((HO,Em)=>{"use strict";Em.exports={}});var Am=S((QO,wm)=>{"use strict";var oR=ne(),uR=oe(),xm=oR.WeakMap;wm.exports=uR(xm)&&/native code/.test(String(xm))});var pl=S((WO,km)=>{"use strict";var lR=Am(),Pm=ne(),cR=De(),dR=ir(),ll=rt(),cl=os(),pR=bn(),hR=Sn(),Rm="Object already initialized",dl=Pm.TypeError,fR=Pm.WeakMap,Tn,ps,In,mR=function(s){return In(s)?ps(s):Tn(s,{})},bR=function(s){return function(e){var t;if(!cR(e)||(t=ps(e)).type!==s)throw new dl("Incompatible receiver, "+s+" required");return t}};lR||cl.state?(st=cl.state||(cl.state=new fR),st.get=st.get,st.has=st.has,st.set=st.set,Tn=function(s,e){if(st.has(s))throw new dl(Rm);return e.facade=s,st.set(s,e),e},ps=function(s){return st.get(s)||{}},In=function(s){return st.has(s)}):(xi=pR("state"),hR[xi]=!0,Tn=function(s,e){if(ll(s,xi))throw new dl(Rm);return e.facade=s,dR(s,xi,e),e},ps=function(s){return ll(s,xi)?s[xi]:{}},In=function(s){return ll(s,xi)});var st,xi;km.exports={set:Tn,get:ps,has:In,enforce:mR,getterFor:bR}});var ml=S((GO,$m)=>{"use strict";var hl=Ne(),gR=rt(),Lm=Function.prototype,SR=hl&&Object.getOwnPropertyDescriptor,fl=gR(Lm,"name"),vR=fl&&function(){}.name==="something",yR=fl&&(!hl||hl&&SR(Lm,"name").configurable);$m.exports={EXISTS:fl,PROPER:vR,CONFIGURABLE:yR}});var Dm=S(Mm=>{"use strict";var TR=Ne(),IR=Yu(),ER=Ti(),xR=mt(),wR=Si(),AR=al();Mm.f=TR&&!IR?Object.defineProperties:function(e,t){xR(e);for(var i=wR(t),r=AR(t),a=r.length,n=0,o;a>n;)ER.f(e,o=r[n++],i[o]);return e}});var bl=S((YO,Cm)=>{"use strict";var RR=Rt();Cm.exports=RR("document","documentElement")});var yl=S((KO,qm)=>{"use strict";var PR=mt(),kR=Dm(),Bm=sl(),LR=Sn(),$R=bl(),MR=fn(),DR=bn(),Vm=">",_m="<",Sl="prototype",vl="script",Fm=DR("IE_PROTO"),gl=function(){},Nm=function(s){return _m+vl+Vm+s+_m+"/"+vl+Vm},Om=function(s){s.write(Nm("")),s.close();var e=s.parentWindow.Object;return s=null,e},CR=function(){var s=MR("iframe"),e="java"+vl+":",t;return s.style.display="none",$R.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Nm("document.F=Object")),t.close(),t.F},En,xn=function(){try{En=new ActiveXObject("htmlfile")}catch(e){}xn=typeof document!="undefined"?document.domain&&En?Om(En):CR():Om(En);for(var s=Bm.length;s--;)delete xn[Sl][Bm[s]];return xn()};LR[Fm]=!0;qm.exports=Object.create||function(e,t){var i;return e!==null?(gl[Sl]=PR(e),i=new gl,gl[Sl]=null,i[Fm]=e):i=xn(),t===void 0?i:kR.f(i,t)}});var or=S((XO,Um)=>{"use strict";var BR=ir();Um.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:BR(s,e,t),s}});var xl=S((JO,Qm)=>{"use strict";var VR=fe(),_R=oe(),OR=De(),FR=yl(),jm=gn(),NR=or(),qR=ye(),UR=it(),El=qR("iterator"),Hm=!1,Pt,Tl,Il;[].keys&&(Il=[].keys(),"next"in Il?(Tl=jm(jm(Il)),Tl!==Object.prototype&&(Pt=Tl)):Hm=!0);var jR=!OR(Pt)||VR(function(){var s={};return Pt[El].call(s)!==s});jR?Pt={}:UR&&(Pt=FR(Pt));_R(Pt[El])||NR(Pt,El,function(){return this});Qm.exports={IteratorPrototype:Pt,BUGGY_SAFARI_ITERATORS:Hm}});var wn=S((ZO,Gm)=>{"use strict";var HR=ye(),QR=HR("toStringTag"),Wm={};Wm[QR]="z";Gm.exports=String(Wm)==="[object z]"});var hs=S((eF,zm)=>{"use strict";var WR=wn(),GR=oe(),An=gi(),zR=ye(),YR=zR("toStringTag"),KR=Object,XR=An(function(){return arguments}())==="Arguments",JR=function(s,e){try{return s[e]}catch(t){}};zm.exports=WR?An:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=JR(e=KR(s),YR))=="string"?t:XR?An(e):(i=An(e))==="Object"&&GR(e.callee)?"Arguments":i}});var Km=S((tF,Ym)=>{"use strict";var ZR=wn(),eP=hs();Ym.exports=ZR?{}.toString:function(){return"[object "+eP(this)+"]"}});var fs=S((iF,Jm)=>{"use strict";var tP=wn(),iP=Ti().f,rP=ir(),sP=rt(),aP=Km(),nP=ye(),Xm=nP("toStringTag");Jm.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(sP(r,Xm)||iP(r,Xm,{configurable:!0,value:e}),i&&!tP&&rP(r,"toString",aP))}});var eb=S((rF,Zm)=>{"use strict";var oP=xl().IteratorPrototype,uP=yl(),lP=is(),cP=fs(),dP=Ei(),pP=function(){return this};Zm.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=uP(oP,{next:lP(+!i,t)}),cP(s,r,!1,!0),dP[r]=pP,s}});var ib=S((sF,tb)=>{"use strict";var hP=me(),fP=ft();tb.exports=function(s,e,t){try{return hP(fP(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var sb=S((aF,rb)=>{"use strict";var mP=De();rb.exports=function(s){return mP(s)||s===null}});var nb=S((nF,ab)=>{"use strict";var bP=sb(),gP=String,SP=TypeError;ab.exports=function(s){if(bP(s))return s;throw new SP("Can't set "+gP(s)+" as a prototype")}});var wl=S((oF,ob)=>{"use strict";var vP=ib(),yP=De(),TP=Qt(),IP=nb();ob.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=vP(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return TP(r),IP(a),yP(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Sb=S((uF,gb)=>{"use strict";var EP=de(),xP=qe(),Rn=it(),mb=ml(),wP=oe(),AP=eb(),ub=gn(),lb=wl(),RP=fs(),PP=ir(),Al=or(),kP=ye(),cb=Ei(),bb=xl(),LP=mb.PROPER,$P=mb.CONFIGURABLE,db=bb.IteratorPrototype,Pn=bb.BUGGY_SAFARI_ITERATORS,ms=kP("iterator"),pb="keys",bs="values",hb="entries",fb=function(){return this};gb.exports=function(s,e,t,i,r,a,n){AP(t,e,i);var o=function(b){if(b===r&&f)return f;if(!Pn&&b&&b in c)return c[b];switch(b){case pb:return function(){return new t(this,b)};case bs:return function(){return new t(this,b)};case hb:return function(){return new t(this,b)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=s.prototype,d=c[ms]||c["@@iterator"]||r&&c[r],f=!Pn&&d||o(r),p=e==="Array"&&c.entries||d,h,m,g;if(p&&(h=ub(p.call(new s)),h!==Object.prototype&&h.next&&(!Rn&&ub(h)!==db&&(lb?lb(h,db):wP(h[ms])||Al(h,ms,fb)),RP(h,u,!0,!0),Rn&&(cb[u]=fb))),LP&&r===bs&&d&&d.name!==bs&&(!Rn&&$P?PP(c,"name",bs):(l=!0,f=function(){return xP(d,this)})),r)if(m={values:o(bs),keys:a?f:o(pb),entries:o(hb)},n)for(g in m)(Pn||l||!(g in c))&&Al(c,g,m[g]);else EP({target:e,proto:!0,forced:Pn||l},m);return(!Rn||n)&&c[ms]!==f&&Al(c,ms,f,{name:r}),cb[e]=f,m}});var yb=S((lF,vb)=>{"use strict";vb.exports=function(s,e){return{value:s,done:e}}});var Pl=S((cF,wb)=>{"use strict";var MP=Si(),Rl=ds(),Tb=Ei(),Eb=pl(),DP=Ti().f,CP=Sb(),kn=yb(),BP=it(),VP=Ne(),xb="Array Iterator",_P=Eb.set,OP=Eb.getterFor(xb);wb.exports=CP(Array,"Array",function(s,e){_P(this,{type:xb,target:MP(s),index:0,kind:e})},function(){var s=OP(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,kn(void 0,!0);switch(s.kind){case"keys":return kn(t,!1);case"values":return kn(e[t],!1)}return kn([t,e[t]],!1)},"values");var Ib=Tb.Arguments=Tb.Array;Rl("keys");Rl("values");Rl("entries");if(!BP&&VP&&Ib.name!=="values")try{DP(Ib,"name",{value:"values"})}catch(s){}});var Rb=S((dF,Ab)=>{"use strict";var FP=ye(),NP=Ei(),qP=FP("iterator"),UP=Array.prototype;Ab.exports=function(s){return s!==void 0&&(NP.Array===s||UP[qP]===s)}});var kl=S((pF,kb)=>{"use strict";var jP=hs(),Pb=ns(),HP=rs(),QP=Ei(),WP=ye(),GP=WP("iterator");kb.exports=function(s){if(!HP(s))return Pb(s,GP)||Pb(s,"@@iterator")||QP[jP(s)]}});var $b=S((hF,Lb)=>{"use strict";var zP=qe(),YP=ft(),KP=mt(),XP=as(),JP=kl(),ZP=TypeError;Lb.exports=function(s,e){var t=arguments.length<2?JP(s):e;if(YP(t))return KP(zP(t,s));throw new ZP(XP(s)+" is not iterable")}});var Cb=S((fF,Db)=>{"use strict";var ek=qe(),Mb=mt(),tk=ns();Db.exports=function(s,e,t){var i,r;Mb(s);try{if(i=tk(s,"return"),!i){if(e==="throw")throw t;return t}i=ek(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Mb(i),t}});var $n=S((mF,Ob)=>{"use strict";var ik=tr(),rk=qe(),sk=mt(),ak=as(),nk=Rb(),ok=ar(),Bb=ss(),uk=$b(),lk=kl(),Vb=Cb(),ck=TypeError,Ln=function(s,e){this.stopped=s,this.result=e},_b=Ln.prototype;Ob.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=ik(e,i),l,c,d,f,p,h,m,g=function(v){return l&&Vb(l,"normal"),new Ln(!0,v)},b=function(v){return r?(sk(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(c=lk(s),!c)throw new ck(ak(s)+" is not iterable");if(nk(c)){for(d=0,f=ok(s);f>d;d++)if(p=b(s[d]),p&&Bb(_b,p))return p;return new Ln(!1)}l=uk(s,c)}for(h=a?s.next:l.next;!(m=rk(h,l)).done;){try{p=b(m.value)}catch(v){Vb(l,"throw",v)}if(typeof p=="object"&&p&&Bb(_b,p))return p}return new Ln(!1)}});var Nb=S((bF,Fb)=>{"use strict";var dk=Ne(),pk=Ti(),hk=is();Fb.exports=function(s,e,t){dk?pk.f(s,e,hk(0,t)):s[e]=t}});var qb=S(()=>{"use strict";var fk=de(),mk=$n(),bk=Nb();fk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return mk(e,function(i,r){bk(t,i,r)},{AS_ENTRIES:!0}),t}})});var jb=S((vF,Ub)=>{"use strict";Pl();qb();var gk=vi();Ub.exports=gk.Object.fromEntries});var Qb=S((yF,Hb)=>{"use strict";Hb.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 Gb=S(()=>{"use strict";Pl();var Sk=Qb(),vk=ne(),yk=fs(),Wb=Ei();for(Mn in Sk)yk(vk[Mn],Mn),Wb[Mn]=Wb.Array;var Mn});var Yb=S((EF,zb)=>{"use strict";var Tk=jb();Gb();zb.exports=Tk});var Ll=S((xF,Kb)=>{"use strict";var Ik=Yb();Kb.exports=Ik});var Xb=S(()=>{"use strict"});var $l=S((RF,Jb)=>{"use strict";var gs=ne(),Ek=yi(),xk=gi(),Dn=function(s){return Ek.slice(0,s.length)===s};Jb.exports=function(){return Dn("Bun/")?"BUN":Dn("Cloudflare-Workers")?"CLOUDFLARE":Dn("Deno/")?"DENO":Dn("Node.js/")?"NODE":gs.Bun&&typeof Bun.version=="string"?"BUN":gs.Deno&&typeof Deno.version=="object"?"DENO":xk(gs.process)==="process"?"NODE":gs.window&&gs.document?"BROWSER":"REST"}()});var Cn=S((PF,Zb)=>{"use strict";var wk=$l();Zb.exports=wk==="NODE"});var tg=S((kF,eg)=>{"use strict";var Ak=Ti();eg.exports=function(s,e,t){return Ak.f(s,e,t)}});var sg=S((LF,rg)=>{"use strict";var Rk=Rt(),Pk=tg(),kk=ye(),Lk=Ne(),ig=kk("species");rg.exports=function(s){var e=Rk(s);Lk&&e&&!e[ig]&&Pk(e,ig,{configurable:!0,get:function(){return this}})}});var ng=S(($F,ag)=>{"use strict";var $k=ss(),Mk=TypeError;ag.exports=function(s,e){if($k(e,s))return s;throw new Mk("Incorrect invocation")}});var Dl=S((MF,og)=>{"use strict";var Dk=me(),Ck=oe(),Ml=os(),Bk=Dk(Function.toString);Ck(Ml.inspectSource)||(Ml.inspectSource=function(s){return Bk(s)});og.exports=Ml.inspectSource});var Bl=S((DF,pg)=>{"use strict";var Vk=me(),_k=fe(),ug=oe(),Ok=hs(),Fk=Rt(),Nk=Dl(),lg=function(){},cg=Fk("Reflect","construct"),Cl=/^\s*(?:class|function)\b/,qk=Vk(Cl.exec),Uk=!Cl.test(lg),Ss=function(e){if(!ug(e))return!1;try{return cg(lg,[],e),!0}catch(t){return!1}},dg=function(e){if(!ug(e))return!1;switch(Ok(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Uk||!!qk(Cl,Nk(e))}catch(t){return!0}};dg.sham=!0;pg.exports=!cg||_k(function(){var s;return Ss(Ss.call)||!Ss(Object)||!Ss(function(){s=!0})||s})?dg:Ss});var fg=S((CF,hg)=>{"use strict";var jk=Bl(),Hk=as(),Qk=TypeError;hg.exports=function(s){if(jk(s))return s;throw new Qk(Hk(s)+" is not a constructor")}});var Vl=S((BF,bg)=>{"use strict";var mg=mt(),Wk=fg(),Gk=rs(),zk=ye(),Yk=zk("species");bg.exports=function(s,e){var t=mg(s).constructor,i;return t===void 0||Gk(i=mg(t)[Yk])?e:Wk(i)}});var Sg=S((VF,gg)=>{"use strict";var Kk=me();gg.exports=Kk([].slice)});var yg=S((_F,vg)=>{"use strict";var Xk=TypeError;vg.exports=function(s,e){if(s<e)throw new Xk("Not enough arguments");return s}});var _l=S((OF,Tg)=>{"use strict";var Jk=yi();Tg.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Jk)});var Wl=S((FF,Lg)=>{"use strict";var Ue=ne(),Zk=Au(),eL=tr(),Ig=oe(),tL=rt(),kg=fe(),Eg=bl(),iL=Sg(),xg=fn(),rL=yg(),sL=_l(),aL=Cn(),jl=Ue.setImmediate,Hl=Ue.clearImmediate,nL=Ue.process,Ol=Ue.Dispatch,oL=Ue.Function,wg=Ue.MessageChannel,uL=Ue.String,Fl=0,vs={},Ag="onreadystatechange",ys,wi,Nl,ql;kg(function(){ys=Ue.location});var Ql=function(s){if(tL(vs,s)){var e=vs[s];delete vs[s],e()}},Ul=function(s){return function(){Ql(s)}},Rg=function(s){Ql(s.data)},Pg=function(s){Ue.postMessage(uL(s),ys.protocol+"//"+ys.host)};(!jl||!Hl)&&(jl=function(e){rL(arguments.length,1);var t=Ig(e)?e:oL(e),i=iL(arguments,1);return vs[++Fl]=function(){Zk(t,void 0,i)},wi(Fl),Fl},Hl=function(e){delete vs[e]},aL?wi=function(s){nL.nextTick(Ul(s))}:Ol&&Ol.now?wi=function(s){Ol.now(Ul(s))}:wg&&!sL?(Nl=new wg,ql=Nl.port2,Nl.port1.onmessage=Rg,wi=eL(ql.postMessage,ql)):Ue.addEventListener&&Ig(Ue.postMessage)&&!Ue.importScripts&&ys&&ys.protocol!=="file:"&&!kg(Pg)?(wi=Pg,Ue.addEventListener("message",Rg,!1)):Ag in xg("script")?wi=function(s){Eg.appendChild(xg("script"))[Ag]=function(){Eg.removeChild(this),Ql(s)}}:wi=function(s){setTimeout(Ul(s),0)});Lg.exports={set:jl,clear:Hl}});var Dg=S((NF,Mg)=>{"use strict";var $g=ne(),lL=Ne(),cL=Object.getOwnPropertyDescriptor;Mg.exports=function(s){if(!lL)return $g[s];var e=cL($g,s);return e&&e.value}});var Gl=S((qF,Bg)=>{"use strict";var Cg=function(){this.head=null,this.tail=null};Cg.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};Bg.exports=Cg});var _g=S((UF,Vg)=>{"use strict";var dL=yi();Vg.exports=/ipad|iphone|ipod/i.test(dL)&&typeof Pebble!="undefined"});var Fg=S((jF,Og)=>{"use strict";var pL=yi();Og.exports=/web0s(?!.*chrome)/i.test(pL)});var Wg=S((HF,Qg)=>{"use strict";var lr=ne(),hL=Dg(),Ng=tr(),zl=Wl().set,fL=Gl(),mL=_l(),bL=_g(),gL=Fg(),Yl=Cn(),qg=lr.MutationObserver||lr.WebKitMutationObserver,Ug=lr.document,jg=lr.process,Bn=lr.Promise,Jl=hL("queueMicrotask"),ur,Kl,Xl,Vn,Hg;Jl||(Ts=new fL,Is=function(){var s,e;for(Yl&&(s=jg.domain)&&s.exit();e=Ts.get();)try{e()}catch(t){throw Ts.head&&ur(),t}s&&s.enter()},!mL&&!Yl&&!gL&&qg&&Ug?(Kl=!0,Xl=Ug.createTextNode(""),new qg(Is).observe(Xl,{characterData:!0}),ur=function(){Xl.data=Kl=!Kl}):!bL&&Bn&&Bn.resolve?(Vn=Bn.resolve(void 0),Vn.constructor=Bn,Hg=Ng(Vn.then,Vn),ur=function(){Hg(Is)}):Yl?ur=function(){jg.nextTick(Is)}:(zl=Ng(zl,lr),ur=function(){zl(Is)}),Jl=function(s){Ts.head||ur(),Ts.add(s)});var Ts,Is;Qg.exports=Jl});var zg=S((QF,Gg)=>{"use strict";Gg.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var _n=S((WF,Yg)=>{"use strict";Yg.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var Ai=S((GF,Kg)=>{"use strict";var SL=ne();Kg.exports=SL.Promise});var cr=S((zF,eS)=>{"use strict";var vL=ne(),Es=Ai(),yL=oe(),TL=zu(),IL=Dl(),EL=ye(),Xg=$l(),xL=it(),Zl=Bu(),Jg=Es&&Es.prototype,wL=EL("species"),ec=!1,Zg=yL(vL.PromiseRejectionEvent),AL=TL("Promise",function(){var s=IL(Es),e=s!==String(Es);if(!e&&Zl===66||xL&&!(Jg.catch&&Jg.finally))return!0;if(!Zl||Zl<51||!/native code/.test(s)){var t=new Es(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[wL]=i,ec=t.then(function(){})instanceof i,!ec)return!0}return!e&&(Xg==="BROWSER"||Xg==="DENO")&&!Zg});eS.exports={CONSTRUCTOR:AL,REJECTION_EVENT:Zg,SUBCLASSING:ec}});var dr=S((YF,iS)=>{"use strict";var tS=ft(),RL=TypeError,PL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new RL("Bad Promise constructor");e=i,t=r}),this.resolve=tS(e),this.reject=tS(t)};iS.exports.f=function(s){return new PL(s)}});var IS=S(()=>{"use strict";var kL=de(),LL=it(),qn=Cn(),Gt=ne(),$L=vi(),mr=qe(),rS=or(),sS=wl(),ML=fs(),DL=sg(),CL=ft(),Nn=oe(),BL=De(),VL=ng(),_L=Vl(),lS=Wl().set,ac=Wg(),OL=zg(),FL=_n(),NL=Gl(),cS=pl(),Un=Ai(),nc=cr(),dS=dr(),jn="Promise",pS=nc.CONSTRUCTOR,qL=nc.REJECTION_EVENT,UL=nc.SUBCLASSING,tc=cS.getterFor(jn),jL=cS.set,pr=Un&&Un.prototype,Ri=Un,On=pr,hS=Gt.TypeError,ic=Gt.document,oc=Gt.process,rc=dS.f,HL=rc,QL=!!(ic&&ic.createEvent&&Gt.dispatchEvent),fS="unhandledrejection",WL="rejectionhandled",aS=0,mS=1,GL=2,uc=1,bS=2,Fn,nS,gS,oS,SS=function(s){var e;return BL(s)&&Nn(e=s.then)?e:!1},vS=function(s,e){var t=e.value,i=e.state===mS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,c;try{r?(i||(e.rejection===bS&&YL(e),e.rejection=uc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===s.promise?n(new hS("Promise-chain cycle")):(l=SS(u))?mr(l,u,a,n):a(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},yS=function(s,e){s.notified||(s.notified=!0,ac(function(){for(var t=s.reactions,i;i=t.get();)vS(i,s);s.notified=!1,e&&!s.rejection&&zL(s)}))},TS=function(s,e,t){var i,r;QL?(i=ic.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Gt.dispatchEvent(i)):i={promise:e,reason:t},!qL&&(r=Gt["on"+s])?r(i):s===fS&&OL("Unhandled promise rejection",t)},zL=function(s){mr(lS,Gt,function(){var e=s.facade,t=s.value,i=uS(s),r;if(i&&(r=FL(function(){qn?oc.emit("unhandledRejection",t,e):TS(fS,e,t)}),s.rejection=qn||uS(s)?bS:uc,r.error))throw r.value})},uS=function(s){return s.rejection!==uc&&!s.parent},YL=function(s){mr(lS,Gt,function(){var e=s.facade;qn?oc.emit("rejectionHandled",e):TS(WL,e,s.value)})},hr=function(s,e,t){return function(i){s(e,i,t)}},fr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=GL,yS(s,!0))},sc=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new hS("Promise can't be resolved itself");var i=SS(e);i?ac(function(){var r={done:!1};try{mr(i,e,hr(sc,r,s),hr(fr,r,s))}catch(a){fr(r,a,s)}}):(s.value=e,s.state=mS,yS(s,!1))}catch(r){fr({done:!1},r,s)}}};if(pS&&(Ri=function(e){VL(this,On),CL(e),mr(Fn,this);var t=tc(this);try{e(hr(sc,t),hr(fr,t))}catch(i){fr(t,i)}},On=Ri.prototype,Fn=function(e){jL(this,{type:jn,done:!1,notified:!1,parent:!1,reactions:new NL,rejection:!1,state:aS,value:null})},Fn.prototype=rS(On,"then",function(e,t){var i=tc(this),r=rc(_L(this,Ri));return i.parent=!0,r.ok=Nn(e)?e:!0,r.fail=Nn(t)&&t,r.domain=qn?oc.domain:void 0,i.state===aS?i.reactions.add(r):ac(function(){vS(r,i)}),r.promise}),nS=function(){var s=new Fn,e=tc(s);this.promise=s,this.resolve=hr(sc,e),this.reject=hr(fr,e)},dS.f=rc=function(s){return s===Ri||s===gS?new nS(s):HL(s)},!LL&&Nn(Un)&&pr!==Object.prototype)){oS=pr.then,UL||rS(pr,"then",function(e,t){var i=this;return new Ri(function(r,a){mr(oS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete pr.constructor}catch(s){}sS&&sS(pr,On)}kL({global:!0,constructor:!0,wrap:!0,forced:pS},{Promise:Ri});gS=$L.Promise;ML(Ri,jn,!1,!0);DL(jn)});var RS=S((JF,AS)=>{"use strict";var KL=ye(),xS=KL("iterator"),wS=!1;try{ES=0,lc={next:function(){return{done:!!ES++}},return:function(){wS=!0}},lc[xS]=function(){return this},Array.from(lc,function(){throw 2})}catch(s){}var ES,lc;AS.exports=function(s,e){try{if(!e&&!wS)return!1}catch(r){return!1}var t=!1;try{var i={};i[xS]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var cc=S((ZF,PS)=>{"use strict";var XL=Ai(),JL=RS(),ZL=cr().CONSTRUCTOR;PS.exports=ZL||!JL(function(s){XL.all(s).then(void 0,function(){})})});var kS=S(()=>{"use strict";var e$=de(),t$=qe(),i$=ft(),r$=dr(),s$=_n(),a$=$n(),n$=cc();e$({target:"Promise",stat:!0,forced:n$},{all:function(e){var t=this,i=r$.f(t),r=i.resolve,a=i.reject,n=s$(function(){var o=i$(t.resolve),u=[],l=0,c=1;a$(e,function(d){var f=l++,p=!1;c++,t$(o,t,d).then(function(h){p||(p=!0,u[f]=h,--c||r(u))},a)}),--c||r(u)});return n.error&&a(n.value),i.promise}})});var $S=S(()=>{"use strict";var o$=de(),u$=it(),l$=cr().CONSTRUCTOR,pc=Ai(),c$=Rt(),d$=oe(),p$=or(),LS=pc&&pc.prototype;o$({target:"Promise",proto:!0,forced:l$,real:!0},{catch:function(s){return this.then(void 0,s)}});!u$&&d$(pc)&&(dc=c$("Promise").prototype.catch,LS.catch!==dc&&p$(LS,"catch",dc,{unsafe:!0}));var dc});var MS=S(()=>{"use strict";var h$=de(),f$=qe(),m$=ft(),b$=dr(),g$=_n(),S$=$n(),v$=cc();h$({target:"Promise",stat:!0,forced:v$},{race:function(e){var t=this,i=b$.f(t),r=i.reject,a=g$(function(){var n=m$(t.resolve);S$(e,function(o){f$(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var DS=S(()=>{"use strict";var y$=de(),T$=dr(),I$=cr().CONSTRUCTOR;y$({target:"Promise",stat:!0,forced:I$},{reject:function(e){var t=T$.f(this),i=t.reject;return i(e),t.promise}})});var hc=S((uN,CS)=>{"use strict";var E$=mt(),x$=De(),w$=dr();CS.exports=function(s,e){if(E$(s),x$(e)&&e.constructor===s)return e;var t=w$.f(s),i=t.resolve;return i(e),t.promise}});var _S=S(()=>{"use strict";var A$=de(),R$=Rt(),BS=it(),P$=Ai(),VS=cr().CONSTRUCTOR,k$=hc(),L$=R$("Promise"),$$=BS&&!VS;A$({target:"Promise",stat:!0,forced:BS||VS},{resolve:function(e){return k$($$&&this===L$?P$:this,e)}})});var OS=S(()=>{"use strict";IS();kS();$S();MS();DS();_S()});var US=S(()=>{"use strict";var M$=de(),D$=it(),Hn=Ai(),C$=fe(),NS=Rt(),qS=oe(),B$=Vl(),FS=hc(),V$=or(),mc=Hn&&Hn.prototype,_$=!!Hn&&C$(function(){mc.finally.call({then:function(){}},function(){})});M$({target:"Promise",proto:!0,real:!0,forced:_$},{finally:function(s){var e=B$(this,NS("Promise")),t=qS(s);return this.then(t?function(i){return FS(e,s()).then(function(){return i})}:s,t?function(i){return FS(e,s()).then(function(){throw i})}:s)}});!D$&&qS(Hn)&&(fc=NS("Promise").prototype.finally,mc.finally!==fc&&V$(mc,"finally",fc,{unsafe:!0}));var fc});var HS=S((mN,jS)=>{"use strict";Xb();OS();US();var O$=Wt();jS.exports=O$("Promise","finally")});var WS=S((bN,QS)=>{"use strict";var F$=HS();QS.exports=F$});var Qn=S((gN,GS)=>{"use strict";var N$=WS();GS.exports=N$});var Iv=S(()=>{"use strict";var IM=de(),EM=Zi(),xM=ar(),wM=cs(),AM=ds();IM({target:"Array",proto:!0},{at:function(e){var t=EM(this),i=xM(t),r=wM(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});AM("at")});var xv=S((uU,Ev)=>{"use strict";Iv();var RM=Wt();Ev.exports=RM("Array","at")});var Av=S((lU,wv)=>{"use strict";var PM=xv();wv.exports=PM});var at=S((cU,Rv)=>{"use strict";var kM=Av();Rv.exports=kM});var Fc=S((tj,ly)=>{"use strict";var lD=gi();ly.exports=Array.isArray||function(e){return lD(e)==="Array"}});var dy=S((ij,cy)=>{"use strict";var cD=TypeError,dD=9007199254740991;cy.exports=function(s){if(s>dD)throw cD("Maximum allowed index exceeded");return s}});var fy=S((rj,hy)=>{"use strict";var pD=Fc(),hD=ar(),fD=dy(),mD=tr(),py=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,c=n?mD(n,o):!1,d,f;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],a>0&&pD(d)?(f=hD(d),u=py(s,e,d,f,u,a-1)-1):(fD(u+1),s[u]=d),u++),l++;return u};hy.exports=py});var Sy=S((sj,gy)=>{"use strict";var my=Fc(),bD=Bl(),gD=De(),SD=ye(),vD=SD("species"),by=Array;gy.exports=function(s){var e;return my(s)&&(e=s.constructor,bD(e)&&(e===by||my(e.prototype))?e=void 0:gD(e)&&(e=e[vD],e===null&&(e=void 0))),e===void 0?by:e}});var yy=S((aj,vy)=>{"use strict";var yD=Sy();vy.exports=function(s,e){return new(yD(s))(e===0?0:e)}});var Ty=S(()=>{"use strict";var TD=de(),ID=fy(),ED=ft(),xD=Zi(),wD=ar(),AD=yy();TD({target:"Array",proto:!0},{flatMap:function(e){var t=xD(this),i=wD(t),r;return ED(e),r=AD(t,0),r.length=ID(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Iy=S(()=>{"use strict";var RD=ds();RD("flatMap")});var xy=S((cj,Ey)=>{"use strict";Ty();Iy();var PD=Wt();Ey.exports=PD("Array","flatMap")});var Ay=S((dj,wy)=>{"use strict";var kD=xy();wy.exports=kD});var Fs=S((pj,Ry)=>{"use strict";var LD=Ay();Ry.exports=LD});var Ns=S((hj,Py)=>{"use strict";var $D=hs(),MD=String;Py.exports=function(s){if($D(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return MD(s)}});var Nc=S((fj,ky)=>{"use strict";ky.exports=`
|
|
7
|
+
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var My=S((mj,$y)=>{"use strict";var DD=me(),CD=Qt(),BD=Ns(),Uc=Nc(),Ly=DD("".replace),VD=RegExp("^["+Uc+"]+"),_D=RegExp("(^|[^"+Uc+"])["+Uc+"]+$"),qc=function(s){return function(e){var t=BD(CD(e));return s&1&&(t=Ly(t,VD,"")),s&2&&(t=Ly(t,_D,"$1")),t}};$y.exports={start:qc(1),end:qc(2),trim:qc(3)}});var Vy=S((bj,By)=>{"use strict";var OD=ml().PROPER,FD=fe(),Dy=Nc(),Cy="\u200B\x85\u180E";By.exports=function(s){return FD(function(){return!!Dy[s]()||Cy[s]()!==Cy||OD&&Dy[s].name!==s})}});var jc=S((gj,_y)=>{"use strict";var ND=My().start,qD=Vy();_y.exports=qD("trimStart")?function(){return ND(this)}:"".trimStart});var Fy=S(()=>{"use strict";var UD=de(),Oy=jc();UD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Oy},{trimLeft:Oy})});var qy=S(()=>{"use strict";Fy();var jD=de(),Ny=jc();jD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Ny},{trimStart:Ny})});var jy=S((Ij,Uy)=>{"use strict";qy();var HD=Wt();Uy.exports=HD("String","trimLeft")});var Qy=S((Ej,Hy)=>{"use strict";var QD=jy();Hy.exports=QD});var Gy=S((xj,Wy)=>{"use strict";var WD=Qy();Wy.exports=WD});var lT=S(()=>{"use strict"});var cT=S(()=>{"use strict"});var pT=S((cW,dT)=>{"use strict";var bC=De(),gC=gi(),SC=ye(),vC=SC("match");dT.exports=function(s){var e;return bC(s)&&((e=s[vC])!==void 0?!!e:gC(s)==="RegExp")}});var mT=S((dW,fT)=>{"use strict";var yC=ne(),TC=fe(),hT=yC.RegExp,IC=!TC(function(){var s=!0;try{hT(".","d")}catch(u){s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor(hT.prototype,"flags").get.call(e);return o!==i||t!==i});fT.exports={correct:IC}});var gT=S((pW,bT)=>{"use strict";var EC=mt();bT.exports=function(){var s=EC(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var yT=S((hW,vT)=>{"use strict";var xC=qe(),wC=rt(),AC=ss(),ST=mT(),RC=gT(),PC=RegExp.prototype;vT.exports=ST.correct?function(s){return s.flags}:function(s){return!ST.correct&&AC(PC,s)&&!wC(s,"flags")?xC(RC,s):s.flags}});var IT=S((fW,TT)=>{"use strict";var zc=me(),kC=Zi(),LC=Math.floor,Wc=zc("".charAt),$C=zc("".replace),Gc=zc("".slice),MC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,DC=/\$([$&'`]|\d{1,2})/g;TT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=DC;return r!==void 0&&(r=kC(r),u=MC),$C(a,u,function(l,c){var d;switch(Wc(c,0)){case"$":return"$";case"&":return s;case"`":return Gc(e,0,t);case"'":return Gc(e,n);case"<":d=r[Gc(c,1,-1)];break;default:var f=+c;if(f===0)return l;if(f>o){var p=LC(f/10);return p===0?l:p<=o?i[p-1]===void 0?Wc(c,1):i[p-1]+Wc(c,1):l}d=i[f-1]}return d===void 0?"":d})}});var wT=S(()=>{"use strict";var CC=de(),BC=qe(),Kc=me(),ET=Qt(),VC=oe(),_C=De(),OC=pT(),Pr=Ns(),FC=ns(),NC=yT(),qC=IT(),UC=ye(),jC=it(),HC=UC("replace"),QC=TypeError,Yc=Kc("".indexOf),WC=Kc("".replace),xT=Kc("".slice),GC=Math.max;CC({target:"String",proto:!0},{replaceAll:function(e,t){var i=ET(this),r,a,n,o,u,l,c,d,f,p,h=0,m="";if(_C(e)){if(r=OC(e),r&&(a=Pr(ET(NC(e))),!~Yc(a,"g")))throw new QC("`.replaceAll` does not allow non-global regexes");if(n=FC(e,HC),n)return BC(n,e,i,t);if(jC&&r)return WC(Pr(i),e,t)}for(o=Pr(i),u=Pr(e),l=VC(t),l||(t=Pr(t)),c=u.length,d=GC(1,c),f=Yc(o,u);f!==-1;)p=l?Pr(t(u,f,o)):qC(u,o,f,[],void 0,t),m+=xT(o,h,f)+p,h=f+c,f=f+d>o.length?-1:Yc(o,u,f+d);return h<o.length&&(m+=xT(o,h)),m}})});var RT=S((gW,AT)=>{"use strict";lT();cT();wT();var zC=Wt();AT.exports=zC("String","replaceAll")});var kT=S((SW,PT)=>{"use strict";var YC=RT();PT.exports=YC});var $T=S((vW,LT)=>{"use strict";var KC=kT();LT.exports=KC});var DT=S((yW,MT)=>{"use strict";var XC=cs(),JC=Ns(),ZC=Qt(),eB=RangeError;MT.exports=function(e){var t=JC(ZC(this)),i="",r=XC(e);if(r<0||r===1/0)throw new eB("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var OT=S((TW,_T)=>{"use strict";var VT=me(),tB=tl(),CT=Ns(),iB=DT(),rB=Qt(),sB=VT(iB),aB=VT("".slice),nB=Math.ceil,BT=function(s){return function(e,t,i){var r=CT(rB(e)),a=tB(t),n=r.length,o=i===void 0?" ":CT(i),u,l;return a<=n||o===""?r:(u=a-n,l=sB(o,nB(u/o.length)),l.length>u&&(l=aB(l,0,u)),s?r+l:l+r)}};_T.exports={start:BT(!1),end:BT(!0)}});var NT=S((IW,FT)=>{"use strict";var oB=yi();FT.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(oB)});var qT=S(()=>{"use strict";var uB=de(),lB=OT().start,cB=NT();uB({target:"String",proto:!0,forced:cB},{padStart:function(e){return lB(this,e,arguments.length>1?arguments[1]:void 0)}})});var jT=S((wW,UT)=>{"use strict";qT();var dB=Wt();UT.exports=dB("String","padStart")});var QT=S((AW,HT)=>{"use strict";var pB=jT();HT.exports=pB});var GT=S((RW,WT)=>{"use strict";var hB=QT();WT.exports=hB});var zp="2.0.140-dev.7b3cdcf7.0";var Me=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Me||{}),At=(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))(At||{});var cn=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(cn||{}),Eu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Eu||{});var xu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(xu||{}),dn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(dn||{});var up=O(Ii(),1),qE=O(Ce(),1);import{assertNever as bm,assertNonNullable as YA,isNonNullable as vn,ValueSubject as ol,Subject as KA,Subscription as XA,merge as JA,observableFrom as ZA,fromEvent as pm,map as hm,tap as fm,filterChanged as eR,isNullable as ul,ErrorCategory as mm}from"@vkontakte/videoplayer-shared/es2018";var dm=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var yn=class{constructor(e){this.connection$=new ol(void 0);this.castState$=new ol("NOT_AVAILABLE");this.errorEvent$=new KA;this.realCastState$=new ol("NOT_AVAILABLE");this.subscription=new XA;this.isDestroyed=!1;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=vn((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||dm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:mm.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){vn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ul(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ul(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(pm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return bm(r.sessionState)}})).add(JA(pm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(fm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),hm(r=>r.castState)),ZA([i.getCastState()])).pipe(eR(),hm(tR),fm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=vn(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();YA(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(ul(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?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(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:mm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},tR=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return bm(s)}};var Zd=O(Ce(),1),IE=O(nr(),1),EE=O(Ll(),1);var lv=O(Qn(),1);import{assertNever as zS}from"@vkontakte/videoplayer-shared/es2018";var ue=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:zS(t)}return s},zt=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:zS(e)}};var $=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as q$,Subject as Wn,merge as YS}from"@vkontakte/videoplayer-shared/es2018";var j=class{constructor(e){this.transitionStarted$=new Wn;this.transitionEnded$=new Wn;this.transitionUpdated$=new Wn;this.forceChanged$=new Wn;this.stateChangeStarted$=YS(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=YS(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||q$(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 iv}from"@vkontakte/videoplayer-shared/es2018";var Gn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var KS=O(Ce(),1);var xs=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var zn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,KS.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=xs()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Yn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var je=()=>window.ManagedMediaSource||window.MediaSource,br=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},XS=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Kn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var U$=document.createElement("video"),j$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',H$='video/mp4; codecs="hev1.1.6.L93.B0"',JS='video/webm; codecs="vp09.00.10.08"',ZS='video/webm; codecs="av01.0.00M.08"',Q$='audio/mp4; codecs="mp4a.40.2"',W$='audio/webm; codecs="opus"',ev,G$=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:ZS}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:JS}})]);ev={DASH_WEBM_AV1:e,DASH_WEBM:t}};G$().catch(s=>{console.log(U$),console.error(s)});var Xn=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 ev}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,c,d,f,p,h,m,g,b,v,T,y;this._video=document.createElement("video");try{this._protocols={mms:br(),mse:XS(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let I=!!((c=(l=je())==null?void 0:l.isTypeSupported)!=null&&c.call(l,j$)),x=!!((f=(d=je())==null?void 0:d.isTypeSupported)!=null&&f.call(d,H$)),L=!!((h=(p=je())==null?void 0:p.isTypeSupported)!=null&&h.call(p,Q$));this._codecs={h264:I,h265:x,vp9:!!((g=(m=je())==null?void 0:m.isTypeSupported)!=null&&g.call(m,JS)),av1:!!((v=(b=je())==null?void 0:b.isTypeSupported)!=null&&v.call(b,ZS)),aac:L,opus:!!((y=(T=je())==null?void 0:T.isTypeSupported)!=null&&y.call(T,W$)),mpeg:(I||x)&&L},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(I){console.error(I)}try{this.destroyVideoElement()}catch(I){console.error("Error destroying video element:",I)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var tv="audio/mpeg",Jn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,tv))},this._codecs={mp3:!!((r=(i=je())==null?void 0:i.isTypeSupported)!=null&&r.call(i,tv))}}catch(a){console.error(a)}try{this.destroyAudioElement()}catch(a){console.error("Error destroying audio element:",a)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as z$}from"@vkontakte/videoplayer-shared/es2018";var bc=class{constructor(){this.isInited$=new z$(!1);this._displayChecker=new Yn,this._deviceChecker=new zn(this._displayChecker),this._browserChecker=new Gn,this._videoChecker=new Xn(this._deviceChecker,this._browserChecker),this._audioChecker=new Jn,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(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},F=new bc;var gc=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=F.video,a=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return s.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&a;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&a||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&a;case"DASH_LIVE_CMAF":return n&&e.mp4&&a&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&a;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return iv(o)}})},Sc=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return iv(s)}},Y$=s=>{let t=Object.keys(s).filter(i=>!Sc(i));return gc(t).length>0};import{assertNever as gr,assertNonNullable as Pi,debounce as rv,ErrorCategory as sv,fromEvent as ki,isNonNullable as av,map as nv,merge as ov,observableFrom as K$,Subject as X$,Subscription as vc,timeout as J$,getHighestQuality as Z$}from"@vkontakte/videoplayer-shared/es2018";var eM=5,tM=5,iM=500,uv=7e3,ws=class{constructor(e){this.subscription=new vc;this.loadMediaTimeoutSubscription=new vc;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(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:gr(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:gr(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:gr(e)}break}default:gr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Sc(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 vc;this.subscription.add(e),this.subscription.add(ov(this.videoState.stateChangeStarted$.pipe(nv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(nv(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new X$;e.add(r.pipe(rv(iM)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>eM)&&r.next(o),a=o})),e.add(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<tM&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),$(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:gr(n)}}),t(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(ki(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=ov(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,K$(["init"])).pipe(rv(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"),$(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),$(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),$(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"),$(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"&&$(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let c=t[e];Pi(c);let d=Z$(Object.keys(c));Pi(d);let f=c[d];Pi(f),i=f,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=t[e];Pi(c),i=c.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];Pi(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Pi(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Pi(c),i=ue(c.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:sv.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return gr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return av(o)&&(n.metadata.title=o),av(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(J$(uv).subscribe(()=>a(`timeout(${uv})`)))});(0,lv.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:sv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var _c=O(Ce(),1);import{clearVideoElement as dv}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as rM}from"@vkontakte/videoplayer-shared/es2018";var cv=s=>{try{s.pause(),s.playbackRate=0,rM(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as sM,Subscription as aM}from"@vkontakte/videoplayer-shared/es2018";var yc=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)}},Tc=window.WeakMap?new WeakMap:new yc,Ic=window.WeakMap?new WeakMap:new Map,nM=(s,e=20)=>{let t=0;return sM(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Be=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?dv(i):(i=document.createElement("video"),s.appendChild(i)),Tc.set(i,r);let a=new aM;return a.add(nM(i,e)),Ic.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ve=s=>{let e=Ic.get(s);e==null||e.unsubscribe(),Ic.delete(s);let t=Tc.get(s);Tc.delete(s),t?dv(s):cv(s)};var xc=O(Ii(),1);import{assertNonNullable as Rs,isNonNullable as gt,isNullable as lM,fromEvent as Sr,merge as pv,observableFrom as hv,filterChanged as fv,map as Ps,Subject as mv,Subscription as cM,ValueSubject as dM,ErrorCategory as pM}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Ec,isNullable as oM,Subscription as uM}from"@vkontakte/videoplayer-shared/es2018";var Zn=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=oM(r),l=new uM;return r&&l.add(r.subscribe(c=>{let d=s.getState();i(c,d)&&s.setState(c)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),u&&s.setState(c.to)},a)),l},bt=(s,e,t)=>Zn(e,()=>s.loop,i=>{Ec(i)&&(s.loop=i)},{onError:t}),we=(s,e,t,i)=>Zn(e,()=>({muted:s.muted,volume:s.volume}),r=>{Ec(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),ze=(s,e,t,i)=>Zn(e,()=>s.playbackRate,r=>{Ec(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),As=Zn;var hM=s=>["__",s.language,s.label].join("|"),fM=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},wc=class s{constructor(e){this.available$=new mv;this.current$=new dM(void 0);this.error$=new mv;this.subscription=new cM;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:pM.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(As(t.internalTextTracks,()=>(0,xc.default)(this.internalTracks),a=>{gt(a)&&this.setInternal(a)},{equal:(a,n)=>gt(a)&>(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ps(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(As(t.externalTextTracks,()=>(0,xc.default)(this.externalTracks),a=>{gt(a)&&this.setExternal(a)},{equal:(a,n)=>gt(a)&>(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ps(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(As(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(As(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Rs(this.video);let{textTracks:e}=this.video;this.subscription.add(Sr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(pv(Sr(e,"addtrack"),Sr(e,"removetrack"),hv(["init"])).pipe(Ps(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),fv((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(pv(Sr(e,"change"),hv(["init"])).pipe(Ps(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ps(i=>i&&this.htmlTextTrackToITextTrack(i).id),fv()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(Sr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,c,d,f,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((f=(d=o.target)==null?void 0:d.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Sr(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;gt(t.align)&&(r.align=t.align),gt(t.position)&&(r.position=t.position),gt(t.size)&&(r.size=t.size),gt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Rs(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:hM(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Rs(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(lM(e)||!fM(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){Rs(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){Rs(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=wc;var Li=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 bv=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Ac=s=>{let e=bv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},gv=s=>{let e=bv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as Ae,map as St,merge as eo,filterChanged as vv,isNonNullable as yv,Subject as bM,filter as Rc,mapTo as Pc,combine as gM,once as SM,shareReplay as Re,throttle as vM,ErrorCategory as yM,ValueSubject as Tv,Subscription as TM}from"@vkontakte/videoplayer-shared/es2018";var mM=3,Sv=(s,e,t=mM)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var _e=s=>{let e=P=>Ae(s,P).pipe(Pc(void 0),Re(1)),t=new TM,i=()=>t.unsubscribe(),r=eo(Ae(s,"progress"),Ae(s,"timeupdate")).pipe(St(()=>Sv(s.buffered,s.currentTime)),Re(1)),a=F.browser.isSafari?gM({play:e("play").pipe(SM()),playing:e("playing")}).pipe(Pc(void 0),Re(1)):e("playing"),n=Ae(s,"volumechange").pipe(St(()=>({muted:s.muted,volume:s.volume})),Re(1)),o=Ae(s,"ratechange").pipe(St(()=>s.playbackRate),Re(1)),u=Ae(s,"error").pipe(Rc(()=>!!(s.error||s.played.length)),St(()=>{var V;let P=s.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:yM.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(V=s.error)!=null?V:void 0}}),Re(1)),l=Ae(s,"timeupdate").pipe(St(()=>s.currentTime),Re(1)),c=["waiting","seeking","seeked","timeupdate"],d=new bM,f=.3,p;t.add(eo(...c.map(P=>Ae(s,P))).subscribe(P=>{let V=s.currentTime;s.loop&&yv(p)&&yv(V)&&p>=s.duration-f&&V<=f&&d.next(p),p=V}));let h=e("pause").pipe(Rc(()=>!s.error&&p!==s.duration),Re(1)),m=Ae(s,"enterpictureinpicture").pipe(Re(1)),g=Ae(s,"leavepictureinpicture").pipe(Re(1)),b=new Tv(gv(s));t.add(m.subscribe(()=>b.next(!0))),t.add(g.subscribe(()=>b.next(!1)));let v=new Tv(Ac(s)),T=Ae(s,"fullscreenchange").pipe(Re(1));t.add(T.pipe(St(()=>Ac(s))).subscribe(v));let y=.1,I=1e3,x=Ae(s,"timeupdate").pipe(St(P=>s.duration-s.currentTime<y),vv(),Re(1)),L=eo(x.pipe(Rc(P=>!s.loop&&P)),Ae(s,"ended")).pipe(vM(I),Pc(void 0),Re(1)),R=eo(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Ae(s,P)),x.pipe(St(P=>({type:P?"ended":"unknown"})))).pipe(St(P=>F.browser.isFirefox&&P.type==="ended"?s.readyState<2:s.readyState<3),vv(),Re(1));return{playing$:a,pause$:h,canplay$:e("canplay"),ended$:L,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ae(s,"durationchange").pipe(St(()=>s.duration),Re(1)),isBuffering$:R,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:b,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Yt}from"@vkontakte/videoplayer-shared/es2018";var Kt=s=>{switch(s){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 ke=O(at(),1),Lc=O(Ce(),1),Mi=O(nr(),1);import{isNonNullable as J,isNullable as so,now as Ov,isHigher as ao,isHigherOrEqual as $i,isInvariantQuality as no,isLowerOrEqual as yr,videoSizeToQuality as Fv,assertNotEmptyArray as oo,assertNonNullable as Nv}from"@vkontakte/videoplayer-shared/es2018";var kc=!1,Lt={},Pv=s=>{kc=s},kv=()=>{Lt={}},Lv=s=>{s(Lt)},ks=(s,e)=>{var t;kc&&(Lt.meta=(t=Lt.meta)!=null?t:{},Lt.meta[s]=e)},Pe=class{constructor(e){this.name=e}next(e){var i,r;if(!kc)return;Lt.series=(i=Lt.series)!=null?i:{};let t=(r=Lt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Lt.series[this.name]=t}};import{isHigher as LM,isHigherOrEqual as bU,isLower as $v,isLowerOrEqual as gU,isNonNullable as to,isNullable as $M,videoHeightToQuality as io}from"@vkontakte/videoplayer-shared/es2018";function Mv(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function vr(s,e,t){return $M(s)||to(s.min)&&to(s.max)&&$v(s.max,s.min)||to(s.min)&&e&&LM(s.min,e)||to(s.max)&&t&&$v(s.max,t)}function Dv({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return vr({max:s!=null&&s.max?io(s.max):void 0,min:s!=null&&s.min?io(s.min):void 0},e?io(e):void 0,t?io(t):void 0)}var qv=new Pe("best_bitrate"),uo=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Tr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ov()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},lo='Assertion "ABR Tracks is empty array" failed',ro=new WeakMap,Cv=new WeakMap,Bv=new WeakMap,Ls=(s,e,t,i)=>{var u;let r=[...e].sort(Tr(1)),a=[...t].sort(Tr(1)),n=a.filter(l=>J(l.bitrate)&&J(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,ke.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,ke.default)(a,-1);return o&&(0,Lc.default)(n,o)?o:n.length?(0,ke.default)(n,-1):(0,ke.default)(a,0)},$s=(s,e,t,i)=>{var u;let r=ro.get(e);r||(r=[...e].sort(Tr(1)),ro.set(e,r));let a=ro.get(t);a||(a=[...t].sort(Tr(1)),ro.set(t,a));let n=Bv.get(s);n||(n=a.filter(l=>J(l.bitrate)&&J(s.bitrate)?s.bitrate/l.bitrate>i:!0),Bv.set(s,n));let o=(u=(0,ke.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,ke.default)(a,-1);return o&&(0,Lc.default)(n,o)?o:n.length?(0,ke.default)(n,-1):(0,ke.default)(a,0)},Vv=s=>"quality"in s,co=(s,e,t,i)=>{var n;let r=J((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&J(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&Ov()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Vv(o)?"video":"audio",l=Vv(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},MM=(s,e)=>Math.log(e)/Math.log(s),Uv=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&F.display.pixelRatio){let a=F.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,c=MM(n,o*a+u)+l;Number.isFinite(c)&&(r*=c)}}return J(t==null?void 0:t.min)&&$i(t.min,s.highQualityLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},_v=new WeakMap,vt=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var _,X,Z,E,k;oo(s,lo);let{containerSizeFactor:g,containerSizeLimit:b}=Uv({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&J(o)?o:1,T=_v.get(s);T||(T=s.filter(w=>!no(w.quality)).sort((w,A)=>ao(w.quality,A.quality)?-1:1),_v.set(s,T));let y=(_=(0,ke.default)(T,-1))==null?void 0:_.quality,I=(X=(0,ke.default)(T,0))==null?void 0:X.quality,x=vr(r,I,y),L=v*uo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),M={},R=null;for(let w of T){let A=!0;if(b)if(w.size)A=w.size.width<=b.width&&w.size.height<=b.height;else{let Fe=b&&Fv(b);A=Fe?yr(w.quality,Fe):!0}if(!A){M[w.quality]="FitsContainer";continue}let B=p||t,G=J(B)&&isFinite(B)&&J(w.bitrate)?B-a>=w.bitrate*L:!0,ct=(r==null?void 0:r.min)===w.quality;if(!G&&!ct){M[w.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&J(i.minBufferToSwitchUp)&&u&&!no(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&ao(w.quality,u.quality)){M[w.quality]="Buffer";continue}if(!!d&&$i(w.quality,d)&&!ct){M[w.quality]="DroppedFramesLimit";continue}if(!!f&&$i(w.quality,f)&&!ct){M[w.quality]="StallsLimit";continue}let Se=x||(so(r==null?void 0:r.max)||yr(w.quality,r.max))&&(so(r==null?void 0:r.min)||$i(w.quality,r.min)),ve=J(c)&&!c?yr(w.quality,i.backgroundVideoQualityLimit):!0;if(!Se||!ve){M[w.quality]="FitsQualityLimits";continue}R||(R=w)}R&&R.bitrate&&qv.next(R.bitrate);let P=(Z=R!=null?R:(0,ke.default)(T,-1))!=null?Z:s[0],V=l==null?void 0:l.last,D=co(i,h,P,l);return J(l)&&D.quality!==(V==null?void 0:V.quality)&&h({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${s.map(
|
|
12
|
+
${s.map(w=>{var A,B;return`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate}, size: ${(A=w.size)==null?void 0:A.width}:${(B=w.size)==null?void 0:B.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Mi.default)(i!=null?i:{}).map(([w,A])=>`${w}: ${A}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
|
-
containerSizeFactor: ${
|
|
21
|
-
containerSizeLimit: ${(
|
|
20
|
+
containerSizeFactor: ${g},
|
|
21
|
+
containerSizeLimit: ${(E=b==null?void 0:b.width)!=null?E:0} x ${(k=b==null?void 0:b.height)!=null?k:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${p},
|
|
24
24
|
reserve: ${a},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${v},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${L},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
30
|
droppedVideoMaxQualityLimit: ${d},
|
|
31
31
|
stallsVideoMaxQualityLimit: ${f},
|
|
32
|
-
limitsAreInvalid: ${
|
|
32
|
+
limitsAreInvalid: ${x},
|
|
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,Mi.default)(M).map(([w,A])=>`${w}: ${A}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
40
|
+
[best video track] ${R==null?void 0:R.quality}
|
|
41
41
|
[selected video track] ${D==null?void 0:D.quality}
|
|
42
|
-
`}),D},
|
|
42
|
+
`}),D},po=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var X,Z,E,k,w;oo(s,lo);let{containerSizeFactor:g,containerSizeLimit:b}=Uv({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&J(o)?o:1,T=s.filter(A=>!no(A.quality)).sort((A,B)=>ao(A.quality,B.quality)?-1:1),y=(X=(0,ke.default)(T,-1))==null?void 0:X.quality,I=(Z=(0,ke.default)(T,0))==null?void 0:Z.quality,x=vr(r,I,y),L=v*uo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),M={},P=T.filter(A=>{let B=!0;if(b)if(A.size)B=A.size.width<=b.width&&A.size.height<=b.height;else{let xt=b&&Fv(b);B=xt?yr(A.quality,xt):!0}if(!B)return M[A.quality]="FitsContainer",!1;let G=p||t,ct=J(G)&&isFinite(G)&&J(A.bitrate)?G-a>=A.bitrate*L:!0,dt=(r==null?void 0:r.min)===A.quality;if(!ct&&!dt)return M[A.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&J(i.minBufferToSwitchUp)&&u&&!no(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&ao(A.quality,u.quality))return M[A.quality]="Buffer",!1;if(!!d&&$i(A.quality,d)&&!dt)return M[A.quality]="DroppedFramesLimit",!1;if(!!f&&$i(A.quality,f)&&!dt)return M[A.quality]="StallsLimit",!1;let ve=x||(so(r==null?void 0:r.max)||yr(A.quality,r.max))&&(so(r==null?void 0:r.min)||$i(A.quality,r.min)),Fe=J(c)&&!c?yr(A.quality,i.backgroundVideoQualityLimit):!0;return!ve||!Fe?(M[A.quality]="FitsQualityLimits",!1):!0})[0];P&&P.bitrate&&qv.next(P.bitrate);let V=(E=P!=null?P:(0,ke.default)(T,-1))!=null?E:s[0],D=l==null?void 0:l.last,_=co(i,h,V,l);return J(l)&&_.quality!==(D==null?void 0:D.quality)&&h({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${s.map(
|
|
45
|
+
${s.map(A=>{var B,G;return`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate}, size: ${(B=A.size)==null?void 0:B.width}:${(G=A.size)==null?void 0:G.height} }`}).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,Mi.default)(i!=null?i:{}).map(([A,B])=>`${A}: ${B}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
|
-
containerSizeFactor: ${
|
|
54
|
-
containerSizeLimit: ${(
|
|
53
|
+
containerSizeFactor: ${g},
|
|
54
|
+
containerSizeLimit: ${(k=b==null?void 0:b.width)!=null?k:0} x ${(w=b==null?void 0:b.height)!=null?w:0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
56
|
stallsPredictedThroughput: ${p},
|
|
57
57
|
reserve: ${a},
|
|
58
58
|
playbackRate: ${o},
|
|
59
|
-
playbackRateFactor: ${
|
|
59
|
+
playbackRateFactor: ${v},
|
|
60
60
|
forwardBufferHealth: ${n},
|
|
61
|
-
bitrateFactor: ${
|
|
61
|
+
bitrateFactor: ${L},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
63
|
droppedVideoMaxQualityLimit: ${d},
|
|
64
64
|
stallsVideoMaxQualityLimit: ${f},
|
|
65
|
-
limitsAreInvalid: ${
|
|
65
|
+
limitsAreInvalid: ${x},
|
|
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,Mi.default)(M).map(([A,B])=>`${A}: ${B}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
73
|
[best video track] ${P==null?void 0:P.quality}
|
|
74
74
|
[selected video track] ${_==null?void 0:_.quality}
|
|
75
|
-
`}),_},
|
|
75
|
+
`}),_},ho=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{oo(t,lo);let c=r.considerPlaybackRate&&J(a)?a:1,d=[...t].sort(Tr(-1)),f=s.bitrate;Nv(f);let p=c*uo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=Ls(s,e,t,r.minVideoAudioRatio),g=l||i;J(g)&&isFinite(g)&&(h=d.find(T=>J(T.bitrate)&&J(m==null?void 0:m.bitrate)?g-f>=T.bitrate*p&&T.bitrate>=m.bitrate:!1)),h||(h=m);let b=o==null?void 0:o.last,v=h&&co(r,u,h,o);return J(o)&&(v==null?void 0:v.bitrate)!==(b==null?void 0:b.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,Mi.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
@@ -92,15 +92,15 @@ var zE=Object.create;var Qp=Object.defineProperty;var YE=Object.getOwnPropertyDe
|
|
|
92
92
|
bitrateFactor: ${p},
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
|
-
[selected audio track] ${
|
|
96
|
-
`}),
|
|
95
|
+
[selected audio track] ${v==null?void 0:v.id}
|
|
96
|
+
`}),v},fo=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{oo(t,lo);let c=r.considerPlaybackRate&&J(a)?a:1,d=Cv.get(t);d||(d=[...t].sort(Tr(-1)),Cv.set(t,d));let f=s.bitrate;Nv(f);let p=c*uo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=$s(s,e,t,r.minVideoAudioRatio),g=l||i;J(g)&&isFinite(g)&&(h=d.find(T=>J(T.bitrate)&&J(m==null?void 0:m.bitrate)?g-f>=T.bitrate*p&&T.bitrate>=m.bitrate:!1)),h||(h=m);let b=o==null?void 0:o.last,v=h&&co(r,u,h,o);return J(o)&&(v==null?void 0:v.bitrate)!==(b==null?void 0:b.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,Mi.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
@@ -113,15 +113,15 @@ var zE=Object.create;var Qp=Object.defineProperty;var YE=Object.getOwnPropertyDe
|
|
|
113
113
|
bitrateFactor: ${p},
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
|
-
[selected audio track] ${
|
|
117
|
-
`}),S};var Te=s=>new URL(s).hostname;import{assertNever as KS,assertNonNullable as XS,combine as JM,debounce as ZM,ErrorCategory as JS,filter as ZS,filterChanged as eD,isNonNullable as Lc,map as lo,merge as ey,observableFrom as tD,once as iD,Subscription as rD,ValueSubject as $c,videoQualityToHeight as ty,videoSizeToQuality as sD}from"@vkontakte/videoplayer-shared/es2018";var WS=O(ot(),1);var qS=O(Ae(),1),NS=s=>{if(s instanceof DOMException&&(0,qS.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},_e=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!NS(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return NS(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as oo,isNullable as CM,assertNonNullable as Ds}from"@vkontakte/videoplayer-shared/es2018";var HS=O(yi(),1);import{isNonNullable as US,assertNonNullable as no,now as MM}from"@vkontakte/videoplayer-shared/es2018";function me(){return MM()}function Ac(s){return me()-s}function Pc(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function jS(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function yr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,c,d,f=!1,p="arraybuffer",h=7e3,m=2e3,v=()=>{if(u)return;no(c);let D=Ac(c),_;if(D<m){_=m-D,setTimeout(v,_);return}m*=2,m>h&&(m=h),n&&n.abort(),n=new r,k()},b=D=>(a=D,V),S=D=>(d=D,V),T=()=>(p="json",V),y=()=>{if(!u){if(--l>=0){v(),i&&i();return}u=!0,d&&d(),t&&t()}},E=D=>(f=D,V),k=()=>{c=me(),n=new r,n.open("get",s);let D=0,_,K=0,J=()=>(no(c),Math.max(c,Math.max(_||0,K||0)));if(a&&n.addEventListener("progress",I=>{let R=me();a.updateChunk&&I.loaded>D&&(a.updateChunk(J(),I.loaded-D),D=I.loaded,_=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;no(n);let I=n.status;if(I>=200&&I<300){let{response:R,responseType:x}=n,w=R==null?void 0:R.byteLength;if(typeof w=="number"&&a){let B=w-D;B&&a.updateChunk&&a.updateChunk(J(),B)}x==="json"&&(!R||!(0,HS.default)(R).length)?y():(d&&d(),e(R))}else y()}),n.addEventListener("error",()=>{y()}),f){let I=()=>{no(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=me(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=p,n.send(),V},V={withBitrateReporting:b,withParallel:E,withJSONResponse:T,withRetryCount:D=>(l=D,V),withRetryInterval:(D,_)=>(US(D)&&(m=D),US(_)&&(h=_),V),withTimeout:D=>(o=D,V),withFinally:S,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return V}var $s=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var QS=O(yi(),1);var Ms=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=me(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=me()-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=yr(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=me()}_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=me();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,QS.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as BM}from"@vkontakte/videoplayer-shared/es2018";var uo=1e4,Rc=3;var VM=6e4,_M=10,OM=1,FM=500,Cs=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 BM,this.chunkRateEstimator=new $s(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Pc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Pc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(F.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!LS({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,WS.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||oo(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{jS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ms(Rc,uo,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let y=a&&(!c||c===this.rep);return y||t("Not running!"),y},f=(y,E,k)=>{u&&u.abort(),u=yr(this.urlResolver.resolve(y,!1),E,k,()=>this._retryCallback()).withTimeout(uo).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Rc).withFinally(()=>{u=null}).send()},p=(y,E,k)=>{Ds(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),E,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=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}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let k=me()-1e4,M=0;for(let A=0;A<this.bufferStates.length;A++){let P=this.bufferStates[A];y=Math.min(y,P.buf),P.ts<k&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${y} drop=${M} jitter=${this.sourceJitter}`);let $=y-OM;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?h(1.15):$>1?h(1.1):$>.3?h(1.05):h(1)}},b=y=>{let E,k=()=>E&&E.start?E.start.length:0,M=I=>E.start[I]/1e3,$=I=>E.dur[I]/1e3,A=I=>E.fragIndex+I,P=(I,R)=>({chunkIdx:A(I),startTS:M(I),dur:$(I),discontinuity:R}),V=()=>{let I=0;if(E&&E.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,x=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,w=R;this.sourceJitter>1&&(w+=this.sourceJitter-1);let B=E.dur.length-1;for(;B>=0&&(w-=E.dur[B],!(w<=0));--B);I=Math.min(B,E.dur.length-1-x),I=Math.max(I,0)}return P(I,!0)},D=I=>{let R=k();if(!(R<=0)){if(oo(I)){for(let x=0;x<R;x++)if(M(x)>I)return P(x)}return V()}},_=I=>{let R=k(),x=I?I.chunkIdx+1:0,w=x-E.fragIndex;if(!(R<=0)){if(!I||w<0||w-R>_M)return t(`Resync: offset=${w} bChunks=${R} chunk=`+JSON.stringify(I)),V();if(!(w>=R))return P(x-E.fragIndex,!1)}},K=(I,R,x)=>{l&&l.abort(),l=yr(this.urlResolver.resolve(I,!0,this.lowLatency),R,x,()=>this._retryCallback()).withTimeout(uo).withRetryCount(Rc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(I,R)=>{K(y,x=>{if(!d())return;E=x;let w=!!E.lowLatency;w!==this.lowLatency&&m(w);let B=0;for(let ne=0;ne<E.dur.length;++ne)B+=E.dur[ne];B>0&&(Ds(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/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(R))},()=>this._handleNetworkError())},nextChunk:_}},S=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ds(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:E,logger:k}=this.params,M=b(e.jidxUrl),$,A,P,V,D=0,_,K,J,I=()=>{_&&(clearTimeout(_),_=void 0);let z=Math.max(FM,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=D+z,ve=me(),Se=Math.min(1e4,ge-ve);D=ve;let qe=()=>{l||d()&&M.seek(()=>{d()&&(D=me(),R(),I())})};Se>0?_=window.setTimeout(()=>{this.paused?I():qe()},Se):qe()},R=()=>{let z;for(;z=M.nextChunk(V);)V=z,Ne(z);let ge=M.nextChunk(P);if(ge){if(P&&ge.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?I():(S(),this._initPlayerWith(e));return}ne(ge)}else I()},x=(z,ge)=>{if(!d()||!this.sourceBuffer)return;let ve,Se,qe,xt=Ot=>{window.setTimeout(()=>{d()&&x(z,ge)},Ot)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),xt(100);else{let Ot=me(),ui=E.currentTime;!this.paused&&E.buffered.length>1&&K===ui&&Ot-J>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),K!==ui&&(K=ui,J=Ot);let Hi=this._getBufferSizeSec();if(Hi>30)k(`Buffered ${Hi} seconds; delaying appendBuffer`),xt(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:Hi}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Wr){if(Wr.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),qe=this.sourceBuffer.buffered.length,qe!==0&&(ve=this.sourceBuffer.buffered.start(0),Se=ui,Se-ve>4&&this.sourceBuffer.remove(ve,Se-3)),xt(1e3);else throw Wr}}},w=()=>{A&&$&&(k([`Appending chunk, sz=${A.byteLength}:`,JSON.stringify(P)]),x(A,function(){A=null,R()}))},B=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),ne=z=>{d()&&p(B(z),(ge,ve)=>{if(d()){if(ve/=1e3,A=ge,P=z,n=z.startTS,ve){let Se=Math.min(10,z.dur/ve);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Se:Se}w()}},()=>this._handleNetworkError())},Ne=z=>{d()&&(Ds(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(z),!1)))},ie=z=>{d()&&(e.cachedHeader=z,x(z,()=>{$=!0,w()}))};a=!0,M.seek(z=>{if(d()){if(D=me(),!z){I();return}V=z,!CM(y)||z.startTS>y?ne(z):(P=z,R())}},y),e.cachedHeader?ie(e.cachedHeader):f(e.headerUrl,ie,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),oo(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,Ds(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return oo(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),h=d/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},a={updateChunk:(f,p)=>{let h=me();if(this.chunkRateEstimator.addInterval(f,h,p)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:v}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=a.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Ac(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,f)=>{let p=a.updateChunk(d,f);return p&&l(),p},notifySwitch:d=>{let f=me();d<o&&(n=f),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=yr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(uo).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;_e(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},VM))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var YS=O(rr(),1);import{debounce as NM,filter as GS,fromEvent as qM,interval as UM,isHigher as HM,isInvariantQuality as jM,isLower as QM,merge as WM,Subject as zS,Subscription as GM}from"@vkontakte/videoplayer-shared/es2018";var kc=class{constructor(){this.onDroopedVideoFramesLimit$=new zS;this.subscription=new GM;this.playing=!1;this.tracks=[];this.forceChecker$=new zS;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&&!jM(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&HM(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(qM(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=UM(this.droppedFramesChecker.checkTime).pipe(GS(()=>this.playing),GS(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(NM(this.droppedFramesChecker.checkTime)),i=WM(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,YS.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>QM(a,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Tr=kc;import{map as zM,Observable as YM}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as KM}from"@vkontakte/videoplayer-shared/es2018";var Bs=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var XM=(s,e)=>new YM(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Bs()))},{...i,...e});r.observe(s);let a=KM(document,"visibilitychange").pipe(zM(n=>!document.hidden||Bs())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Je=XM;var aD=["paused","playing","ready"],nD=["paused","playing","ready"],Vs=class{constructor(e){this.subscription=new rD;this.videoState=new H("stopped");this.representations$=new $c([]);this.droppedFramesManager=new Tr;this.maxSeekBackTime$=new $c(1/0);this.zeroTime$=new $c(void 0);this.liveOffset=new Ri;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:JS.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=Kt(u.name))!=null?i:sD(u.video),d=u.bitrate/1e3,f={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:f};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Lc(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Mc.default)(nD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,Mc.default)(aD,e)){this.seek(a.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"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(le(this.params.source.url,u))}return;default:return KS(e)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:JS.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(ey(this.videoState.stateChangeStarted$.pipe(lo(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(lo(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=De(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(Te(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=Ve(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(lo(r=>r.map(({track:a})=>a)),ZS(r=>!!r.length),iD()).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(eD(),lo(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(JM({zeroTime:this.zeroTime$.pipe(ZS(Lc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(bt(this.video,this.params.desiredState.isLooped,t)).add(Be(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ke(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(Je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&ty(r),min:a&&ty(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return KS(r.to)}},t)).add(ey(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,tD(["init"])).pipe(ZM(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}createLiveDashPlayer(){let e=new Cs({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,f,p,h;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(f=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Lc(t)?t:St(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}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let m=(h=e.find(({track:v})=>v.id===a))==null?void 0:h.representation;XS(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;XS(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(le(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var iy=Vs;var II=O(Ae(),1);var be=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as KB,assertNonNullable as XB,debounce as JB,ErrorCategory as SI,filter as md,filterChanged as Fo,fromEvent as ZB,isNonNullable as yI,isNullable as e0,map as bd,merge as No,observableFrom as gd,once as TI,Subscription as t0}from"@vkontakte/videoplayer-shared/es2018";var{NativeAbortSignal:C1,NativeAbortController:B1}=function(s){return{NativeAbortSignal:s.AbortSignal,NativeAbortController:s.AbortController}}(typeof self!="undefined"?self:global);function ry(s){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=s,e}function sy(s){if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason"),Object.defineProperty(s,"name",{value:"AbortError"})}catch(e){s=new Error("This operation was aborted"),s.name="AbortError"}return s}var co=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Ir=class extends co{constructor(){super(),this.listeners||co.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 Li;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Li;function i(){t.abort(this.reason),r()}function r(){for(let a of e)a.removeEventListener("abort",i)}for(let a of e)if(a.aborted){t.abort(a.reason);break}else a.addEventListener("abort",i);return t.signal}},Li=class{constructor(){Object.defineProperty(this,"signal",{value:new Ir,writable:!0,configurable:!0})}abort(e){let t=sy(e),i=ry(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Li.prototype[Symbol.toStringTag]="AbortController",Ir.prototype[Symbol.toStringTag]="AbortSignal");function po(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Dc(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!po({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let f=new t(l,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let f=new Promise((p,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:a}}var oD=()=>"fetch"in window,_s=oD()&&po({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ay=_s?Dc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=_s?ay.fetch:window.fetch,Q1=_s?ay.Request:window.Request,Z=_s?Li:window.AbortController,W1=_s?Ir:window.AbortSignal;var mI=O(Ae(),1),ld=O(Os(),1);var Qy=O(jy(),1);import{ErrorCategory as Ns}from"@vkontakte/videoplayer-shared/es2018";var ho=s=>{if(!s)return{id:"EmptyResponse",category:Ns.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ns.NETWORK,message:`UV Error ${s}`};let e=(0,Qy.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ns.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ns.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ns.PARSER,message:"Response is valid XML, but parser failed"}};var Ie=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as nd,assertNonNullable as Cr,combine as Br,ErrorCategory as ct,filter as Mo,filterChanged as va,flattenObject as Sa,fromEvent as Bt,getTraceSubscriptionMethod as MB,interval as od,isNonNullable as ya,isNullable as pI,map as Vr,merge as Bi,now as ud,Subject as ii,Subscription as hI,tap as DB,throttle as CB,ValueSubject as se}from"@vkontakte/videoplayer-shared/es2018";var go=O(Ae(),1),Ci=O(ot(),1),vo=O(Os(),1);var WD=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},GD=s=>window.clearTimeout(s),Wy=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),Gy=!Wy(window.requestIdleCallback)||!Wy(window.cancelIdleCallback),Er=Gy?WD:window.requestIdleCallback,yt=Gy?GD:window.cancelIdleCallback;var sI=O(Vn(),1);import{assertNever as zD,ErrorCategory as zy,Subject as Yy}from"@vkontakte/videoplayer-shared/es2018";var YD=18,Ky=!1;try{Ky=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=YD}catch(s){console.error(s)}var Fc=class{constructor(e){this.bufferFull$=new Yy;this.error$=new Yy;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:zy.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Ky&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:zy.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:zD(t)}}},Xy=Fc;var xr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as Zt,assertNonNullable as Oe,ErrorCategory as Mt,fromEvent as Zc,getExponentialDelay as ed,isNonNullable as kr,isNullable as Ee,now as bo,once as gB,Subject as vB,Subscription as SB,ValueSubject as Di}from"@vkontakte/videoplayer-shared/es2018";var Jy=O(ot(),1);var fo=s=>s.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,a;i===0?(this.size=void 0,this.valid=!1,a=void 0):i===1?(this.size=void 0,this.valid=!1,a=void 0):i>e.byteLength?(this.size=i,this.valid=!1,a=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,a=i-this.cursor),this.content=new DataView(e.buffer,r,a)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var wr=class extends Q{};import{assertNever as KD}from"@vkontakte/videoplayer-shared/es2018";var qs=class extends Q{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:KD(e)}}};var Us=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let a=this.readString(4);this.compatibleBrands.push(a)}}};var Hs=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var re=class extends Q{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 js=class extends re{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 Qs=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ws=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var $i=class extends re{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var Gs=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zs=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ys=class extends re{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 Ks=class extends re{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Xs=class extends re{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 Js=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zs=class extends re{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 ea=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ta=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ia=class extends re{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var ra=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sa=class extends re{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 aa=class extends re{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 na=class extends re{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 oa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=class extends re{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 la=class extends Q{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 JD={ftyp:Us,moov:Hs,mvhd:js,moof:Qs,mdat:Ws,sidx:$i,trak:Gs,mdia:Js,mfhd:ia,tkhd:Zs,traf:ra,tfhd:sa,tfdt:aa,trun:na,minf:ea,sv3d:zs,st3d:Ys,prhd:Ks,proj:ta,equi:Xs,uuid:qs,stbl:oa,stsd:ua,avc1:la,unknown:wr},$t=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!fo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=JD[e];return i?new i(t,new s):new wr(t,new s)}};var Jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;fo(t)&&((a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var eC=new TextDecoder("ascii"),tC=s=>eC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",iC=s=>{let e=new $i(s,new $t),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},rC=(s,e)=>{let i=new $t().parse(s),r=new Jt(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,d)},sC=s=>{let t=new $t().parse(s),i=new Jt(t),r={},a=i.findAll("uuid"),n=(0,Jy.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},aC=s=>{var r;let t=new $t().parse(s);return(r=new Jt(t).find("sidx"))==null?void 0:r.timescale},nC=(s,e)=>{let i=new $t().parse(s),a=new Jt(i).findAll("traf"),n=a[a.length-1].children.find(d=>d.type==="tfhd"),o=a[a.length-1].children.find(d=>d.type==="tfdt"),u=a[a.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,f)=>d+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},oC=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new $t().parse(s),r=new Jt(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},Zy={validateData:tC,parseInit:oC,getIndexRange:()=>{},parseSegments:iC,parseFeedableSegmentChunk:rC,getChunkEndTime:nC,getServerLatencyTimestamps:sC,getTimescaleFromIndex:aC};var pa=O(Ae(),1);import{assertNonNullable as Nc,isNonNullable as rT,isNullable as lC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as uC}from"@vkontakte/videoplayer-shared/es2018";var eT={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"}},tT=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=da(s,t),r=i in eT,a=r?eT[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,c=da(u),d=l*2**((o-1)*8)+c,f=t+o,p;return f+d>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},da=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ut=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return da(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:uC(e)}},Mi=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=tT(i);if(!e(r))return;r.type==="master"&&Mi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},iT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=tT(s);return Mi(r.value,({tag:a,type:n,value:o})=>(a===17143?e=ut(o,n):a===17026?t=ut(o,n):a===17029&&(i=ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var sT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],cC=[231,22612,22743,167,171,163,160,175],dC=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,c=!1,d=0;return Mi(s,({tag:f,type:p,value:h,valueSize:m})=>{if(f===21419){let v=ut(h,p);l=da(v)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+m):f===357149030?a=!0:f===290298740?n=!0:f===2807729?i=ut(h,p):f===17545?r=ut(h,p):f===21420&&l===475249515?u=ut(h,p):f===374648427?Mi(h,({tag:v,type:b,value:S})=>v===30321?(c=ut(S,b)===1,!1):!0):a&&n&&(0,pa.default)(sT,f)&&(o=!0),!o}),Nc(e,"Failed to parse webm Segment start"),Nc(t,"Failed to parse webm Segment end"),Nc(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},pC=s=>{if(lC(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hC=(s,e)=>{let t=!1,i=!1,r=o=>rT(o.time)&&rT(o.position),a=[],n;return Mi(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=ut(l,u));break;case 183:break;case 241:n&&(n.position=ut(l,u));break;default:t&&(0,pa.default)(sT,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:c}=o,d=a[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},fC=s=>{let e=0,t=!1;try{Mi(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,pa.default)(cC,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,pa.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},aT={validateData:iT,parseInit:dC,getIndexRange:pC,parseSegments:hC,parseFeedableSegmentChunk:fC};var Tt=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return aT;case"mp4":return Zy}}throw new ReferenceError(`Unsupported mime type ${s}`)};var It=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Gc=O(RT(),1),KT=O(rr(),1),XT=O(jT(),1),JT=O(ot(),1),zc=O(yi(),1);var QT=O(Ae(),1),Wc=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,QT.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as fB,isNullable as zT}from"@vkontakte/videoplayer-shared/es2018";var WT=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var GT=s=>{var e;try{let t=hB(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function hB(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
116
|
+
[selected audio track] ${v==null?void 0:v.id}
|
|
117
|
+
`}),v};var Te=s=>new URL(s).hostname;import{assertNever as Zv,assertNonNullable as ey,combine as ZM,debounce as eD,ErrorCategory as ty,filter as iy,filterChanged as tD,isNonNullable as Bc,map as So,merge as ry,observableFrom as iD,once as rD,Subscription as sD,ValueSubject as Vc,videoQualityToHeight as sy,videoSizeToQuality as aD}from"@vkontakte/videoplayer-shared/es2018";var Yv=O(at(),1);var Hv=O(Ce(),1),jv=s=>{if(s instanceof DOMException&&(0,Hv.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},Oe=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!jv(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return jv(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as bo,isNullable as BM,assertNonNullable as Cs}from"@vkontakte/videoplayer-shared/es2018";var Wv=O(Ii(),1);import{isNonNullable as Qv,assertNonNullable as mo,now as DM}from"@vkontakte/videoplayer-shared/es2018";function be(){return DM()}function $c(s){return be()-s}function Mc(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Gv(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Ir(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,c,d,f=!1,p="arraybuffer",h=7e3,m=2e3,g=()=>{if(u)return;mo(c);let D=$c(c),_;if(D<m){_=m-D,setTimeout(g,_);return}m*=2,m>h&&(m=h),n&&n.abort(),n=new r,x()},b=D=>(a=D,V),v=D=>(d=D,V),T=()=>(p="json",V),y=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},I=D=>(f=D,V),x=()=>{c=be(),n=new r,n.open("get",s);let D=0,_,X=0,Z=()=>(mo(c),Math.max(c,Math.max(_||0,X||0)));if(a&&n.addEventListener("progress",E=>{let k=be();a.updateChunk&&E.loaded>D&&(a.updateChunk(Z(),E.loaded-D),D=E.loaded,_=k)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;mo(n);let E=n.status;if(E>=200&&E<300){let{response:k,responseType:w}=n,A=k==null?void 0:k.byteLength;if(typeof A=="number"&&a){let B=A-D;B&&a.updateChunk&&a.updateChunk(Z(),B)}w==="json"&&(!k||!(0,Wv.default)(k).length)?y():(d&&d(),e(k))}else y()}),n.addEventListener("error",()=>{y()}),f){let E=()=>{mo(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(X=be(),n.removeEventListener("readystatechange",E))};n.addEventListener("readystatechange",E)}return n.responseType=p,n.send(),V},V={withBitrateReporting:b,withParallel:I,withJSONResponse:T,withRetryCount:D=>(l=D,V),withRetryInterval:(D,_)=>(Qv(D)&&(m=D),Qv(_)&&(h=_),V),withTimeout:D=>(o=D,V),withFinally:v,send:x,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return V}var Ms=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var zv=O(Ii(),1);var Ds=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=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)},a=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=Ir(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=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,zv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as VM}from"@vkontakte/videoplayer-shared/es2018";var go=1e4,Dc=3;var _M=6e4,OM=10,FM=1,NM=500,Bs=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 VM,this.chunkRateEstimator=new Ms(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Mc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Mc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(F.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Dv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Yv.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||bo(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Gv(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ds(Dc,go,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let y=a&&(!c||c===this.rep);return y||t("Not running!"),y},f=(y,I,x)=>{u&&u.abort(),u=Ir(this.urlResolver.resolve(y,!1),I,x,()=>this._retryCallback()).withTimeout(go).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Dc).withFinally(()=>{u=null}).send()},p=(y,I,x)=>{Cs(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,x,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=y=>{let I=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${I}=>${y}`),i.playbackRate=y)},m=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let x=be()-1e4,L=0;for(let R=0;R<this.bufferStates.length;R++){let P=this.bufferStates[R];y=Math.min(y,P.buf),P.ts<x&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${y} drop=${L} jitter=${this.sourceJitter}`);let M=y-FM;this.sourceJitter>=0?M-=this.sourceJitter/2:this.sourceJitter-=1,M>3?h(1.15):M>1?h(1.1):M>.3?h(1.05):h(1)}},b=y=>{let I,x=()=>I&&I.start?I.start.length:0,L=E=>I.start[E]/1e3,M=E=>I.dur[E]/1e3,R=E=>I.fragIndex+E,P=(E,k)=>({chunkIdx:R(E),startTS:L(E),dur:M(E),discontinuity:k}),V=()=>{let E=0;if(I&&I.dur){let k=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,w=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,A=k;this.sourceJitter>1&&(A+=this.sourceJitter-1);let B=I.dur.length-1;for(;B>=0&&(A-=I.dur[B],!(A<=0));--B);E=Math.min(B,I.dur.length-1-w),E=Math.max(E,0)}return P(E,!0)},D=E=>{let k=x();if(!(k<=0)){if(bo(E)){for(let w=0;w<k;w++)if(L(w)>E)return P(w)}return V()}},_=E=>{let k=x(),w=E?E.chunkIdx+1:0,A=w-I.fragIndex;if(!(k<=0)){if(!E||A<0||A-k>OM)return t(`Resync: offset=${A} bChunks=${k} chunk=`+JSON.stringify(E)),V();if(!(A>=k))return P(w-I.fragIndex,!1)}},X=(E,k,w)=>{l&&l.abort(),l=Ir(this.urlResolver.resolve(E,!0,this.lowLatency),k,w,()=>this._retryCallback()).withTimeout(go).withRetryCount(Dc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(E,k)=>{X(y,w=>{if(!d())return;I=w;let A=!!I.lowLatency;A!==this.lowLatency&&m(A);let B=0;for(let G=0;G<I.dur.length;++G)B+=I.dur[G];B>0&&(Cs(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,E(D(k))},()=>this._handleNetworkError())},nextChunk:_}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Cs(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:I,logger:x}=this.params,L=b(e.jidxUrl),M,R,P,V,D=0,_,X,Z,E=()=>{_&&(clearTimeout(_),_=void 0);let Y=Math.max(NM,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=D+Y,Se=be(),ve=Math.min(1e4,ge-Se);D=Se;let Fe=()=>{l||d()&&L.seek(()=>{d()&&(D=be(),k(),E())})};ve>0?_=window.setTimeout(()=>{this.paused?E():Fe()},ve):Fe()},k=()=>{let Y;for(;Y=L.nextChunk(V);)V=Y,ct(Y);let ge=L.nextChunk(P);if(ge){if(P&&ge.discontinuity){x("Detected discontinuity; restarting playback"),this.paused?E():(v(),this._initPlayerWith(e));return}G(ge)}else E()},w=(Y,ge)=>{if(!d()||!this.sourceBuffer)return;let Se,ve,Fe,xt=Ot=>{window.setTimeout(()=>{d()&&w(Y,ge)},Ot)};if(this.sourceBuffer.updating)x("Source buffer is updating; delaying appendBuffer"),xt(100);else{let Ot=be(),ci=I.currentTime;!this.paused&&I.buffered.length>1&&X===ci&&Ot-Z>500&&(x("Stall suspected; trying to fix"),this._fixupStall()),X!==ci&&(X=ci,Z=Ot);let Wi=this._getBufferSizeSec();if(Wi>30)x(`Buffered ${Wi} seconds; delaying appendBuffer`),xt(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:Wi}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Gr){if(Gr.name==="QuotaExceededError")x("QuotaExceededError; delaying appendBuffer"),Fe=this.sourceBuffer.buffered.length,Fe!==0&&(Se=this.sourceBuffer.buffered.start(0),ve=ci,ve-Se>4&&this.sourceBuffer.remove(Se,ve-3)),xt(1e3);else throw Gr}}},A=()=>{R&&M&&(x([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(P)]),w(R,function(){R=null,k()}))},B=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),G=Y=>{d()&&p(B(Y),(ge,Se)=>{if(d()){if(Se/=1e3,R=ge,P=Y,n=Y.startTS,Se){let ve=Math.min(10,Y.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}A()}},()=>this._handleNetworkError())},ct=Y=>{d()&&(Cs(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(Y),!1)))},dt=Y=>{d()&&(e.cachedHeader=Y,w(Y,()=>{M=!0,A()}))};a=!0,L.seek(Y=>{if(d()){if(D=be(),!Y){E();return}V=Y,!BM(y)||Y.startTS>y?G(Y):(P=Y,k())}},y),e.cachedHeader?dt(e.cachedHeader):f(e.headerUrl,dt,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),bo(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,Cs(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return bo(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),h=d/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},a={updateChunk:(f,p)=>{let h=be();if(this.chunkRateEstimator.addInterval(f,h,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:g}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=a.get();if(d&&o&&this.autoQuality){if(u&&d>o&&$c(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,f)=>{let p=a.updateChunk(d,f);return p&&l(),p},notifySwitch:d=>{let f=be();d<o&&(n=f),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Ir(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(go).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;Oe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},_M))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Jv=O(nr(),1);import{debounce as qM,filter as Kv,fromEvent as UM,interval as jM,isHigher as HM,isInvariantQuality as QM,isLower as WM,merge as GM,Subject as Xv,Subscription as zM}from"@vkontakte/videoplayer-shared/es2018";var Cc=class{constructor(){this.onDroopedVideoFramesLimit$=new Xv;this.subscription=new zM;this.playing=!1;this.tracks=[];this.forceChecker$=new Xv;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&&!QM(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&HM(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(UM(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=jM(this.droppedFramesChecker.checkTime).pipe(Kv(()=>this.playing),Kv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(qM(this.droppedFramesChecker.checkTime)),i=GM(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,Jv.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>WM(a,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Er=Cc;import{map as YM,Observable as KM}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as XM}from"@vkontakte/videoplayer-shared/es2018";var Vs=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var JM=(s,e)=>new KM(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Vs()))},{...i,...e});r.observe(s);let a=XM(document,"visibilitychange").pipe(YM(n=>!document.hidden||Vs())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Ke=JM;var nD=["paused","playing","ready"],oD=["paused","playing","ready"],_s=class{constructor(e){this.subscription=new sD;this.videoState=new j("stopped");this.representations$=new Vc([]);this.droppedFramesManager=new Er;this.maxSeekBackTime$=new Vc(1/0);this.zeroTime$=new Vc(void 0);this.liveOffset=new Li;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:ty.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=Kt(u.name))!=null?i:aD(u.video),d=u.bitrate/1e3,f={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:f};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Bc(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,_c.default)(oD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,_c.default)(nD,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ue(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ue(this.params.source.url,u))}return;default:return Zv(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:ty.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(ry(this.videoState.stateChangeStarted$.pipe(So(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(So(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${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(Te(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=_e(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(So(r=>r.map(({track:a})=>a)),iy(r=>!!r.length),rD()).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(tD(),So(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(ZM({zeroTime:this.zeroTime$.pipe(iy(Bc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(bt(this.video,this.params.desiredState.isLooped,t)).add(we(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(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:a}})=>{this.dash.setAutoQualityLimits({max:r&&sy(r),min:a&&sy(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Zv(r.to)}},t)).add(ry(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,iD(["init"])).pipe(eD(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ve(this.video)}createLiveDashPlayer(){let e=new Bs({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,f,p,h;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(f=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Bc(t)?t:vt(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}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let m=(h=e.find(({track:g})=>g.id===a))==null?void 0:h.representation;ey(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;ey(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ue(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var ay=_s;var Ie=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as JB,assertNonNullable as ZB,combine as e0,debounce as t0,ErrorCategory as TI,filter as xa,filterChanged as wa,fromEvent as i0,isNonNullable as II,isNullable as r0,map as Fr,merge as Aa,observableFrom as Go,once as zo,Subscription as s0,throttle as a0,ValueSubject as n0}from"@vkontakte/videoplayer-shared/es2018";var{NativeAbortSignal:q1,NativeAbortController:U1}=function(s){return{NativeAbortSignal:s.AbortSignal,NativeAbortController:s.AbortController}}(typeof self!="undefined"?self:global);function ny(s){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=s,e}function oy(s){if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason"),Object.defineProperty(s,"name",{value:"AbortError"})}catch(e){s=new Error("This operation was aborted"),s.name="AbortError"}return s}var vo=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},xr=class extends vo{constructor(){super(),this.listeners||vo.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 Di;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Di;function i(){t.abort(this.reason),r()}function r(){for(let a of e)a.removeEventListener("abort",i)}for(let a of e)if(a.aborted){t.abort(a.reason);break}else a.addEventListener("abort",i);return t.signal}},Di=class{constructor(){Object.defineProperty(this,"signal",{value:new xr,writable:!0,configurable:!0})}abort(e){let t=oy(e),i=ny(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Di.prototype[Symbol.toStringTag]="AbortController",xr.prototype[Symbol.toStringTag]="AbortSignal");function yo(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Oc(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!yo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let f=new t(l,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let f=new Promise((p,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:a}}var uD=()=>"fetch"in window,Os=uD()&&yo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),uy=Os?Oc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Xe=Os?uy.fetch:window.fetch,J1=Os?uy.Request:window.Request,ee=Os?Di:window.AbortController,Z1=Os?xr:window.AbortSignal;var gI=O(Ce(),1),fd=O(Fs(),1);var zy=O(Gy(),1);import{ErrorCategory as qs}from"@vkontakte/videoplayer-shared/es2018";var To=s=>{if(!s)return{id:"EmptyResponse",category:qs.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:qs.NETWORK,message:`UV Error ${s}`};let e=(0,zy.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:qs.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:qs.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:qs.PARSER,message:"Response is valid XML, but parser failed"}};var Ee=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as dd,assertNonNullable as Br,combine as Vr,ErrorCategory as ut,filter as No,filterChanged as ya,flattenObject as Ta,fromEvent as Bt,getTraceSubscriptionMethod as CB,interval as pd,isNonNullable as Ia,isNullable as fI,map as _r,merge as Oi,now as hd,Subject as ri,Subscription as mI,tap as BB,throttle as VB,ValueSubject as se}from"@vkontakte/videoplayer-shared/es2018";var wo=O(Ce(),1),_i=O(at(),1),Ao=O(Fs(),1);var GD=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},zD=s=>window.clearTimeout(s),Yy=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),Ky=!Yy(window.requestIdleCallback)||!Yy(window.cancelIdleCallback),wr=Ky?GD:window.requestIdleCallback,yt=Ky?zD:window.cancelIdleCallback;var nI=O(Qn(),1);import{assertNever as YD,ErrorCategory as Xy,Subject as Jy}from"@vkontakte/videoplayer-shared/es2018";var KD=18,Zy=!1;try{Zy=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=KD}catch(s){console.error(s)}var Hc=class{constructor(e){this.bufferFull$=new Jy;this.error$=new Jy;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Xy.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Zy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Xy.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:YD(t)}}},eT=Hc;var Ar=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as Zt,assertNonNullable as Le,ErrorCategory as Mt,fromEvent as sd,getExponentialDelay as ad,isHigher as SB,isNonNullable as ei,isNullable as pe,now as xo,once as vB,Subject as yB,Subscription as TB,ValueSubject as Vi}from"@vkontakte/videoplayer-shared/es2018";var tT=O(at(),1);var Io=s=>s.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,a;i===0?(this.size=void 0,this.valid=!1,a=void 0):i===1?(this.size=void 0,this.valid=!1,a=void 0):i>e.byteLength?(this.size=i,this.valid=!1,a=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,a=i-this.cursor),this.content=new DataView(e.buffer,r,a)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Rr=class extends Q{};import{assertNever as XD}from"@vkontakte/videoplayer-shared/es2018";var Us=class extends Q{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:XD(e)}}};var js=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let a=this.readString(4);this.compatibleBrands.push(a)}}};var Hs=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var re=class extends Q{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 Qs=class extends re{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 Ws=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gs=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var Ci=class extends re{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var zs=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ys=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ks=class extends re{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 Xs=class extends re{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Js=class extends re{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 Zs=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ea=class extends re{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 ta=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ia=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ra=class extends re{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var sa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var aa=class extends re{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 na=class extends re{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 oa=class extends re{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 ua=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var la=class extends re{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 ca=class extends Q{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 ZD={ftyp:js,moov:Hs,mvhd:Qs,moof:Ws,mdat:Gs,sidx:Ci,trak:zs,mdia:Zs,mfhd:ra,tkhd:ea,traf:sa,tfhd:aa,tfdt:na,trun:oa,minf:ta,sv3d:Ys,st3d:Ks,prhd:Xs,proj:ia,equi:Js,uuid:Us,stbl:ua,stsd:la,avc1:ca,unknown:Rr},$t=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!Io(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=ZD[e];return i?new i(t,new s):new Rr(t,new s)}};var Jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;Io(t)&&((a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var tC=new TextDecoder("ascii"),iC=s=>tC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",rC=s=>{let e=new Ci(s,new $t),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},sC=(s,e)=>{let i=new $t().parse(s),r=new Jt(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,d)},aC=s=>{let t=new $t().parse(s),i=new Jt(t),r={},a=i.findAll("uuid"),n=(0,tT.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},nC=s=>{var r;let t=new $t().parse(s);return(r=new Jt(t).find("sidx"))==null?void 0:r.timescale},oC=(s,e)=>{let i=new $t().parse(s),a=new Jt(i).findAll("traf"),n=a[a.length-1].children.find(d=>d.type==="tfhd"),o=a[a.length-1].children.find(d=>d.type==="tfdt"),u=a[a.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,f)=>d+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},uC=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new $t().parse(s),r=new Jt(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},iT={validateData:iC,parseInit:uC,getIndexRange:()=>{},parseSegments:rC,parseFeedableSegmentChunk:sC,getChunkEndTime:oC,getServerLatencyTimestamps:aC,getTimescaleFromIndex:nC};var ha=O(Ce(),1);import{assertNonNullable as Qc,isNonNullable as nT,isNullable as cC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as lC}from"@vkontakte/videoplayer-shared/es2018";var rT={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"}},sT=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=pa(s,t),r=i in rT,a=r?rT[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,c=pa(u),d=l*2**((o-1)*8)+c,f=t+o,p;return f+d>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},pa=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},nt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return pa(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:lC(e)}},Bi=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=sT(i);if(!e(r))return;r.type==="master"&&Bi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},aT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=sT(s);return Bi(r.value,({tag:a,type:n,value:o})=>(a===17143?e=nt(o,n):a===17026?t=nt(o,n):a===17029&&(i=nt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var oT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],dC=[231,22612,22743,167,171,163,160,175],pC=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,c=!1,d=0;return Bi(s,({tag:f,type:p,value:h,valueSize:m})=>{if(f===21419){let g=nt(h,p);l=pa(g)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+m):f===357149030?a=!0:f===290298740?n=!0:f===2807729?i=nt(h,p):f===17545?r=nt(h,p):f===21420&&l===475249515?u=nt(h,p):f===374648427?Bi(h,({tag:g,type:b,value:v})=>g===30321?(c=nt(v,b)===1,!1):!0):a&&n&&(0,ha.default)(oT,f)&&(o=!0),!o}),Qc(e,"Failed to parse webm Segment start"),Qc(t,"Failed to parse webm Segment end"),Qc(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},hC=s=>{if(cC(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},fC=(s,e)=>{let t=!1,i=!1,r=o=>nT(o.time)&&nT(o.position),a=[],n;return Bi(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=nt(l,u));break;case 183:break;case 241:n&&(n.position=nt(l,u));break;default:t&&(0,ha.default)(oT,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:c}=o,d=a[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},mC=s=>{let e=0,t=!1;try{Bi(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ha.default)(dC,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,ha.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},uT={validateData:aT,parseInit:pC,getIndexRange:hC,parseSegments:fC,parseFeedableSegmentChunk:mC};var Tt=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return uT;case"mp4":return iT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var It=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Jc=O($T(),1),ZT=O(nr(),1),eI=O(GT(),1),tI=O(at(),1),Zc=O(Ii(),1);var zT=O(Ce(),1),Xc=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,zT.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as mB,isNullable as XT}from"@vkontakte/videoplayer-shared/es2018";var YT=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var KT=s=>{var e;try{let t=fB(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function fB(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
118
118
|
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
119
119
|
(-(?<script>[a-z]{4}))?
|
|
120
120
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
121
121
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
122
122
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
123
123
|
(?:-(?<privateuse>(?:${e})))?
|
|
124
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var YT=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},lt=(s,e)=>{let t=s;t=(0,Gc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,KT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Gc.default)(t,n,(o,u)=>zT(a)?o:zT(u)?a:(0,XT.default)(a,parseInt(u,10),"0"))}return t},mo=(s,e)=>{var A,P,V,D,_,K,J,I,R,x,w,B,ne,Ne,ie,z,ge,ve,Se,qe,xt,Ot,ui,Hi,Wr,op,up,lp,cp,dp,pp,hp,fp,mp,bp,gp,vp,Sp,yp,Tp,Ip,Ep,xp,wp,Ap,Pp,Rp,kp,Lp,$p,Mp,Dp,Cp,Bp,Vp,_p,Op,Fp,Np,qp,Up;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(et=>{var te,li;return(li=(te=et.textContent)==null?void 0:te.trim())!=null?li:""}),o=(A=(0,JT.default)(n,0))!=null?A:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=a.getAttribute("publishTime"),d=a.getElementsByTagName("vk:Attrs")[0],f=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let b,S=a.getAttribute("mediaPresentationDuration"),T=[...a.getElementsByTagName("Period")],y=T.reduce((et,te)=>({...et,[te.id]:te.children}),{}),E=T.reduce((et,te)=>({...et,[te.id]:te.getAttribute("duration")}),{});S?b=YT(S):(0,zc.default)(E).filter(et=>et).length&&!u?b=(0,zc.default)(E).reduce((et,te)=>{var li;return et+((li=YT(te))!=null?li:0)},0):m&&(b=parseInt(m,10));let k=0,M=(V=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?V:[];for(let et of T.map(te=>te.id))for(let te of y[et]){let li=(D=te.getAttribute("id"))!=null?D:"id"+(k++).toString(10),Gr=(_=te.getAttribute("mimeType"))!=null?_:"",pu=(K=te.getAttribute("codecs"))!=null?K:"",hu=(J=te.getAttribute("contentType"))!=null?J:Gr==null?void 0:Gr.split("/")[0],qE=(R=(I=te.getAttribute("profiles"))==null?void 0:I.split(","))!=null?R:[],Hp=(w=GT((x=te.getAttribute("lang"))!=null?x:""))!=null?w:{},qa=(Ne=(ne=(B=te.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:ne.trim())!=null?Ne:void 0,UE=te.querySelectorAll("Representation"),HE=te.querySelector("SegmentTemplate"),jE=(z=(ie=te.querySelector("Role"))==null?void 0:ie.getAttribute("value"))!=null?z:void 0,ji=hu,de={id:li,language:Hp.language,isDefault:jE==="main",label:qa,codecs:pu,hdr:ji==="video"&&Wc(pu),mime:Gr,representations:[]};for(let ee of UE){let Ft=(ge=ee.getAttribute("lang"))!=null?ge:void 0,zr=(Se=(ve=qa!=null?qa:te.getAttribute("label"))!=null?ve:ee.getAttribute("label"))!=null?Se:void 0,Ua=(Ot=(xt=(qe=ee.querySelector("BaseURL"))==null?void 0:qe.textContent)==null?void 0:xt.trim())!=null?Ot:"",ci=new URL(Ua||o,e).toString(),Nt=(ui=ee.getAttribute("mimeType"))!=null?ui:Gr,Ha=(Wr=(Hi=ee.getAttribute("codecs"))!=null?Hi:pu)!=null?Wr:"",ja;if(hu==="text"){let qt=ee.getAttribute("id")||"",Qa=((op=Hp.privateuse)==null?void 0:op.includes("x-auto"))||qt.includes("_auto"),di=ee.querySelector("SegmentTemplate");if(di){let Yr={representationId:(up=ee.getAttribute("id"))!=null?up:void 0,bandwidth:(lp=ee.getAttribute("bandwidth"))!=null?lp:void 0},Wa=parseInt((cp=ee.getAttribute("bandwidth"))!=null?cp:"",10)/1e3,Ga=(pp=parseInt((dp=di.getAttribute("startNumber"))!=null?dp:"",10))!=null?pp:1,Qi=parseInt((hp=di.getAttribute("timescale"))!=null?hp:"",10),fu=(fp=di.querySelectorAll("SegmentTimeline S"))!=null?fp:[],Wi=di.getAttribute("media");if(!Wi)continue;let za=[],Ya=0,Ka="",Gi=0,Kr=Ga,we=0;for(let tt of fu){let pi=parseInt((mp=tt.getAttribute("d"))!=null?mp:"",10),Ye=parseInt((bp=tt.getAttribute("r"))!=null?bp:"",10)||0,Ut=parseInt((gp=tt.getAttribute("t"))!=null?gp:"",10);we=Number.isFinite(Ut)?Ut:we;let hi=pi/Qi*1e3,Ht=we/Qi*1e3;for(let pt=0;pt<Ye+1;pt++){let jt=lt(Wi,{...Yr,segmentNumber:Kr.toString(10),segmentTime:(we+pt*pi).toString(10)}),zi=(Ht!=null?Ht:0)+pt*hi,Jr=zi+hi;Kr++,za.push({time:{from:zi,to:Jr},url:jt})}we+=(Ye+1)*pi,Ya+=(Ye+1)*hi}Gi=we/Qi*1e3,Ka=lt(Wi,{...Yr,segmentNumber:Kr.toString(10),segmentTime:we.toString(10)});let Xr={time:{from:Gi,to:1/0},url:Ka},wt={type:"template",baseUrl:ci,segmentTemplateUrl:Wi,initUrl:"",totalSegmentsDurationMs:Ya,segments:za,nextSegmentBeyondManifest:Xr,timescale:Qi};ja={id:qt,kind:"text",segmentReference:wt,profiles:[],duration:b,bitrate:Wa,mime:"",codecs:"",width:0,height:0,isAuto:Qa}}else ja={id:qt,isAuto:Qa,kind:"text",url:ci}}else{let qt=(Sp=(vp=ee.getAttribute("contentType"))!=null?vp:Nt==null?void 0:Nt.split("/")[0])!=null?Sp:hu,Qa=(Tp=(yp=te.getAttribute("profiles"))==null?void 0:yp.split(","))!=null?Tp:[],di=parseInt((Ip=ee.getAttribute("width"))!=null?Ip:"",10),Yr=parseInt((Ep=ee.getAttribute("height"))!=null?Ep:"",10),Wa=parseInt((xp=ee.getAttribute("bandwidth"))!=null?xp:"",10)/1e3,Ga=(wp=ee.getAttribute("frameRate"))!=null?wp:"",Qi=(Ap=ee.getAttribute("quality"))!=null?Ap:void 0,fu=Ga?WT(Ga):void 0,Wi=(Pp=ee.getAttribute("id"))!=null?Pp:"id"+(k++).toString(10),za=qt==="video"?`${Yr}p`:qt==="audio"?`${Wa}Kbps`:Ha,Ya=`${Wi}@${za}`,Ka=[...M,...qE,...Qa],Gi,Kr=ee.querySelector("SegmentBase"),we=(Rp=ee.querySelector("SegmentTemplate"))!=null?Rp:HE;if(Kr){let wt=(Lp=(kp=ee.querySelector("SegmentBase Initialization"))==null?void 0:kp.getAttribute("range"))!=null?Lp:"",[tt,pi]=wt.split("-").map(jt=>parseInt(jt,10)),Ye={from:tt,to:pi},Ut=($p=ee.querySelector("SegmentBase"))==null?void 0:$p.getAttribute("indexRange"),[hi,Ht]=Ut?Ut.split("-").map(jt=>parseInt(jt,10)):[],pt=Ut?{from:hi,to:Ht}:void 0;Gi={type:"byteRange",url:ci,initRange:Ye,indexRange:pt}}else if(we){let wt={representationId:(Mp=ee.getAttribute("id"))!=null?Mp:void 0,bandwidth:(Dp=ee.getAttribute("bandwidth"))!=null?Dp:void 0},tt=parseInt((Cp=we.getAttribute("timescale"))!=null?Cp:"",10),pi=(Bp=we.getAttribute("initialization"))!=null?Bp:"",Ye=we.getAttribute("media"),Ut=(_p=parseInt((Vp=we.getAttribute("startNumber"))!=null?Vp:"",10))!=null?_p:1,hi=lt(pi,wt);if(!Ye)throw new ReferenceError("No media attribute in SegmentTemplate");let Ht=(Op=we.querySelectorAll("SegmentTimeline S"))!=null?Op:[],pt=[],jt=0,zi="",Jr=0;if(Ht.length){let Xa=Ut,it=0;for(let Yi of Ht){let ht=parseInt((Fp=Yi.getAttribute("d"))!=null?Fp:"",10),fi=parseInt((Np=Yi.getAttribute("r"))!=null?Np:"",10)||0,Ja=parseInt((qp=Yi.getAttribute("t"))!=null?qp:"",10);it=Number.isFinite(Ja)?Ja:it;let mu=ht/tt*1e3,bu=it/tt*1e3;for(let Za=0;Za<fi+1;Za++){let WE=lt(Ye,{...wt,segmentNumber:Xa.toString(10),segmentTime:(it+Za*ht).toString(10)}),jp=(bu!=null?bu:0)+Za*mu,GE=jp+mu;Xa++,pt.push({time:{from:jp,to:GE},url:WE})}it+=(fi+1)*ht,jt+=(fi+1)*mu}Jr=it/tt*1e3,zi=lt(Ye,{...wt,segmentNumber:Xa.toString(10),segmentTime:it.toString(10)})}else if(fB(b)){let it=parseInt((Up=we.getAttribute("duration"))!=null?Up:"",10)/tt*1e3,Yi=Math.ceil(b/it),ht=0;for(let fi=1;fi<Yi;fi++){let Ja=lt(Ye,{...wt,segmentNumber:fi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+it},url:Ja}),ht+=it}Jr=ht,zi=lt(Ye,{...wt,segmentNumber:Yi.toString(10),segmentTime:ht.toString(10)})}let QE={time:{from:Jr,to:1/0},url:zi};Gi={type:"template",baseUrl:ci,segmentTemplateUrl:Ye,initUrl:hi,totalSegmentsDurationMs:jt,segments:pt,nextSegmentBeyondManifest:QE,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!qt||!Nt)continue;let Xr={video:"video",audio:"audio",text:"text"}[qt];if(!Xr)continue;ji||(ji=Xr),ja={id:Ya,kind:Xr,segmentReference:Gi,profiles:Ka,duration:b,bitrate:Wa,mime:Nt,codecs:Ha,width:di,height:Yr,fps:fu,quality:Qi}}de.language||(de.language=Ft),de.label||(de.label=zr),de.mime||(de.mime=Nt),de.codecs||(de.codecs=Ha),de.hdr||(de.hdr=ji==="video"&&Wc(Ha)),de.representations.push(ja)}if(ji){let ee=r[ji].find(Ft=>Ft.id===de.id);if(ee&&de.representations.every(Ft=>Ft.segmentReference.type==="template"))for(let Ft of ee.representations){let zr=de.representations.find(Nt=>Nt.id===Ft.id),Ua=zr==null?void 0:zr.segmentReference,ci=Ft.segmentReference;ci.segments.push(...Ua.segments),ci.nextSegmentBeyondManifest=Ua.nextSegmentBeyondManifest}else r[ji].push(de)}}return{duration:b,streams:r,baseUrls:n,live:v}};var Yc=O(ot(),1);import{videoSizeToQuality as mB}from"@vkontakte/videoplayer-shared/es2018";var ZT=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Kt(a):void 0)!=null?u:mB({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},eI=({id:s,bitrate:e})=>({id:s,bitrate:e}),tI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),iI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Kc=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Yc.default)(i.split("."),0),isDefault:r}),Xc=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Yc.default)(r.split("."),0)}),Jc=s=>"url"in s,We=s=>s.type==="template";import{isNonNullable as rI}from"@vkontakte/videoplayer-shared/es2018";var N=(s,e)=>rI(s)&&rI(e)&&s.readyState==="open"&&bB(s,e);function bB(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var ha=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Di(0);this.currentLowLatencySegmentLength$=new Di(0);this.currentSegmentLength$=new Di(0);this.onLastSegment$=new Di(!1);this.fullyBuffered$=new Di(!1);this.playingRepresentation$=new Di(void 0);this.playingRepresentationInit$=new Di(void 0);this.error$=new vB;this.gaps=[];this.subscription=new SB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;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=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Oe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Xy(this.sourceBuffer),this.subscription.add(Zc(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Zc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,xr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Oe(i,"No init buffer for starting representation"),Oe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ee(a)||Ee(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Oe(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();kr(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=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ee(a)||Ee(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Oe(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();kr(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=Zt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,vo.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!We(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Oe(r);let a=this.segments.get(i);Oe(a,"No segments for starting representation");let n=this.initData.get(i);if(Oe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,Zt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);Oe(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ee(o)||Ee(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Oe(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();kr(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(){!Ee(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 Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ee(e)||Ee(this.downloadingRepresentationId)||Ee(this.playingRepresentationId)||Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||kr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Oe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);kr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(a=d)}if(isFinite(this.bufferLimit)&&xr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,go.default)(u,r))c="high";else{let d=(0,Ci.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Ci.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;kr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,vo.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,vo.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!We(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(a=(0,Ci.default)(c,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Oe(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,Ci.default)(e,-1))==null?void 0:t.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!We(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),c=lt(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let v=p<=i&&h>=i,b=p>i||v||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+S||r<S&&h-p>=S||h<=i+S;return(f==="none"||f==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&b&&T});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=a;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){We(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Zt(o,async function*(){let c=ed(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=bo(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())We(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Zt(n,async function*(){let u=ed(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Zc(window,"online").pipe(gB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=bo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(We(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ci.default)(e,0).byte.from,to:(0,Ci.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=bo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!We(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=bo();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,go.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,f=d-c+1,p=c<r,h=d<=r;if(!p)continue;let m=Tt(o.mime);if(l.status==="downloading"&&h){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-c),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===f?v:m.parseFeedableSegmentChunk(v);b!=null&&b.byteLength&&(l.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.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",Jc(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Er(()=>(0,sI.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?Zt(this.destroyAbortController.signal,async function*(){let o=ed(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&We(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Mt.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||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ee(e))return!1;let r=[],a=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:f}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,f):l.push(u[c])}return l},o=u=>{var c;if(a>=t)return r;r.push({...u.time}),r=n(r);let l=Jc(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let f of this.segments.values())for(let p of f)(0,go.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let f={time:{from:l,to:c},url:"",status:"none"};o(f)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!N(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||!N(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||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ee(e)?0:be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Er(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||Ee(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Mt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ei=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var So=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as fa,assertNever as aI,fromEvent as nI,merge as yB,now as ma,Subject as Lr,ValueSubject as td,flattenObject as $r,ErrorCategory as ba,SubscriptionRemovable as TB}from"@vkontakte/videoplayer-shared/es2018";var yo=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Io=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new Lr;this.manifestReceived=new Lr;this.firstBytesRequested=new Lr;this.firstBytesReceived=new Lr;this.lastConnectionType$=new td(void 0);this.lastConnectionReused$=new td(void 0);this.lastRequestFirstBytes$=new td(void 0);this.recoverableError$=new Lr;this.error$=new Lr;this.abortAllController=new Z;this.subscription=new TB;this.fetchManifest=fa(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=yo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(To);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=fa(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var _,K,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:aI(t)}this.requestQuic&&(c=ei(c));let p=this.abortAllController.signal,h;if(n){let I=new Z;if(h=yB(nI(this.abortAllController.signal,"abort"),nI(n,"abort")).subscribe(()=>{try{I.abort()}catch(R){To(R)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(R){To(R)}p=I.signal}let m=0,v=ma();f.log("startRequest",$r({url:c,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.firstBytesRequested.next();let b=yield this.doFetch(c,{priority:a,headers:d,signal:p}),S=ma();if(!b)return f.error("error",{message:"No response in request"}),f.end(),this.unsubscribeAbortSubscription(h),null;if((_=this.throughputEstimator)==null||_.addRawRtt(S-v),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let I=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:I}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let I=ma(),R={requestStartedAt:v,requestEndedAt:I,duration:I-v};return f.log("endRequest",$r(R)),f.end(),b.arrayBuffer()}let T=b.body;if(o){let I;[T,I]=b.body.tee(),(K=this.throughputEstimator)==null||K.trackStream(I,u)}let y=T.getReader(),E,k=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(k)&&(E=k),!E&&i&&(E=i.to-i.from+1);let M=E?new Uint8Array(E):new Uint8Array(0),$=!1,A=I=>{this.unsubscribeAbortSubscription(h),$=!0,To(I)},P=fa(p,async function*({done:I,value:R}){if(m===0&&(this.lastRequestFirstBytes$.next(ma()-v),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!I&&R){if(l&&E)M.set(R,m),m+=R.byteLength;else{let x=new Uint8Array(M.length+R.length);x.set(M),x.set(R,M.length),M=x,m+=R.byteLength}r==null||r(new DataView(M.buffer),m),yield y==null?void 0:y.read().then(P,A)}}.bind(this));yield y==null?void 0:y.read().then(P,A),this.unsubscribeAbortSubscription(h);let V=ma(),D={failed:$,requestStartedAt:v,requestEndedAt:V,duration:V-v};return $?(f.error("endRequest",$r(D)),f.end(),null):(f.log("endRequest",$r(D)),f.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=fa(this.abortAllController.signal,async function*(e,t,i){var b;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(c,a))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let S=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!S)return null;m=new DataView(S)}let v=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:v}}.bind(this));this.fetchTemplateRepresentation=fa(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=So(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:aI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ze(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ba.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ba.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ba.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ba.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ba.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},To=s=>{if(!It(s))throw s};var Dt=(s,e,t)=>t*e+(1-t)*s,id=(s,e)=>s.reduce((t,i)=>t+i,0)/e,oI=(s,e,t,i)=>{let r=0,a=t,n=id(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};import{isNullable as IB,ValueSubject as uI}from"@vkontakte/videoplayer-shared/es2018";var ti=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 uI(e.initial),this.debounced$=new uI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${t}`),this.smoothedSeries$=new ke(`smoothed_${t}`),this.reportedSeries$=new ke(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(IB(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 Eo=class extends ti{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Dt(this.slow,e,this.params.emaAlphaSlow),this.fast=Dt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var xo=class extends ti{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=id(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);let i=oI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var wo=class extends ti{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?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Ct=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Eo({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new xo({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 wo({initial:e,label:"liveEdgeDelay",...t})}};var Mr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as EB,ValueSubject as xB}from"@vkontakte/videoplayer-shared/es2018";var ga=class s{constructor(e,t){this.currentRepresentation$=new xB(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(!EB(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&We(t.segmentReference))}};var Po=O(ot(),1),rd=O(Ae(),1);import{assertNever as Ro}from"@vkontakte/videoplayer-shared/es2018";var Ao=s=>{let{webmDecodingInfo:e}=F.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Ro(s)}return[t,i]},lI=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Ao(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(F.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...Ao(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ao(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ao(s),...a,"HLS","HLS_ONDEMAND"];default:Ro(e)}if(F.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Ro(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},cI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=F.device.isMac&&F.browser.isSafari;if(F.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:Ro(s)}else F.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},sd=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ko=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Po.default)(t.value.split("."),0)}for(let t of s){let i=(0,Po.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Po.default)(e.value.split("."),0)},Lo=s=>{let e=s.map(i=>Dr(i)),{codecs:t}=F.video;return RB().filter(i=>{if((0,rd.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})},$o=s=>{let e=s.map(i=>Dr(i)),{codecs:t}=F.video;return kB().filter(i=>{if((0,rd.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Dr=s=>s.split(".")[0].replace("0",""),RB=()=>["av1","vp9","hev1","avc1"],kB=()=>["opus","mp4a"];var BB=["timeupdate","progress","play","seeked","stalled","waiting"],VB=["timeupdate","progress","loadeddata","playing","seeked"];var Do=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new hI;this.representationSubscription=new hI;this.state$=new H("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 ii;this.manifestRequested=new ii;this.manifestReceived=new ii;this.firstBytesRequested=new ii;this.firstBytesReceived=new ii;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 ii;this.fetcherError$=new ii;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ii;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=nd(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:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=nd(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=mo(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=ho(e))!=null?u:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,m,v;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((v=(m=Qe())==null?void 0:m.isTypeSupported)!=null&&v.call(m,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";p||(m=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:m})=>i(c,h,m));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:m})=>m);c==="audio"&&(n=$o(h),p=n[0]),c==="video"&&(a=Lo(h),this.forceVideoCodec&&(0,mI.default)(a,this.forceVideoCodec)?p=this.forceVideoCodec:p=a[0]),p&&(r[c]=f.filter(({codecs:m})=>Dr(m)===p))}else{let h=new Set(f.map(({codecs:m})=>m));p=ko(h),p&&(r[c]=f.filter(({codecs:m})=>m.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),v=r.video.some(b=>!b.hdr);F.display.isHDR&&h&&m?r.video=r.video.filter(b=>b.hdr):v&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",Sa(o)),o}.bind(this));this.initRepresentations=nd(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",Sa({initialVideo:e,initialAudio:t,sourceHls:i})),Cr(this.manifest),Cr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Bt(p,"error").pipe(Mo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=qn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),hr())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 ha("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],ya(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new ha("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ga.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ga(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Bi(...VB.map(p=>Bt(this.element,p))).pipe(Vr(p=>this.element?be(this.element.buffered,this.element.currentTime*1e3):0),va(),DB(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Bi(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(va()).subscribe(h=>this.liveStreamEndTimestamp=ud())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=od(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,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(Br({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Vr(({isActiveLive:h,isLowLatency:m})=>h&&m),va()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Mr(this.element,1)})),this.representationSubscription.add(Br({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mo(({bufferLength:h,isActiveLive:m,isLowLatency:v})=>m&&v&&!!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(Br({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Mo(({isLive:h})=>h),va((h,m)=>m.bufferLength<h.bufferLength),Vr(({rtt:h,bufferLength:m,segmentServerLatency:v})=>{let b=zt(this.manifestUrlString,2);return(h/2+m+v+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Br({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:v})=>{if(!v||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-b;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(y)>S&&(E=1+Math.sign(y)*T),Mr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var v,b;let m=0;if(h){let S=((b=(v=this.element)==null?void 0:v.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var E,k;return(k=(E=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?k:S}))-S}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Br({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(CB(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,b=zt(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,k=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let A="none";if(M?A="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),A="active_low_latency"):b!==0&&k<T?A="live_forward_buffering":k<T+E&&(A="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),A==="live_forward_buffering"||A==="live_with_target_offset"){let P=p-(T+y),V=this.normolizeLiveOffset(Math.trunc(b+P/v)),D=Math.abs(V-b),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=b:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,2)}(A==="live_with_target_offset"||A==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Bi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Vr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Bi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Vr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Br({allBuffersFull:l,someBufferEnded:c}).pipe(va(),Vr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),Mo(p=>p));if(this.representationSubscription.add(Bi(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:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Bi(...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 v;if(((v=this.source)==null?void 0:v.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ct.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=[(f=this.manifest.duration)!=null?f:0,...(0,ld.default)((0,ld.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),We(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&ya(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=od(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.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 Io({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;Cr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ud()-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((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Cr(this.element),this.state$.setState("running"),this.subscription.add(Bi(...BB.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.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(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,m,v,b,S,T,y,E,k,M;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=ud(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(b=(v=this.audioBufferManager)==null?void 0:v.lastDataObtainedTimestamp)!=null?b:0,l=(T=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?T:0,c=(E=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?E:0,d=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&c<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||f)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let $=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive($).catch(A=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),r.liveLastOffset=$}else{let $=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain($),(M=this.audioBufferManager)==null||M.maintain($),r.position=$}this.tracer.log("stallIntervalCallback",Sa(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=od(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;Cr(this.element),Cr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(pI(this.element)||pI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Sa({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;ya(this.element)&&ya(this.source)&&ya(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=MB(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}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};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Sa(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var Co=class{constructor(e,t){this.fov=e,this.orientation=t}};var Bo=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,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...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 bI=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var JT=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},ot=(s,e)=>{let t=s;t=(0,Jc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,ZT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Jc.default)(t,n,(o,u)=>XT(a)?o:XT(u)?a:(0,eI.default)(a,parseInt(u,10),"0"))}return t},Eo=(s,e)=>{var R,P,V,D,_,X,Z,E,k,w,A,B,G,ct,dt,Y,ge,Se,ve,Fe,xt,Ot,ci,Wi,Gr,lp,cp,dp,pp,hp,fp,mp,bp,gp,Sp,vp,yp,Tp,Ip,Ep,xp,wp,Ap,Rp,Pp,kp,Lp,$p,Mp,Dp,Cp,Bp,Vp,_p,Op,Fp,Np,qp,Up,jp,Hp;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(Je=>{var ie,di;return(di=(ie=Je.textContent)==null?void 0:ie.trim())!=null?di:""}),o=(R=(0,tI.default)(n,0))!=null?R:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=a.getAttribute("publishTime"),d=a.getElementsByTagName("vk:Attrs")[0],f=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let b,v=a.getAttribute("mediaPresentationDuration"),T=[...a.getElementsByTagName("Period")],y=T.reduce((Je,ie)=>({...Je,[ie.id]:ie.children}),{}),I=T.reduce((Je,ie)=>({...Je,[ie.id]:ie.getAttribute("duration")}),{});v?b=JT(v):(0,Zc.default)(I).filter(Je=>Je).length&&!u?b=(0,Zc.default)(I).reduce((Je,ie)=>{var di;return Je+((di=JT(ie))!=null?di:0)},0):m&&(b=parseInt(m,10));let x=0,L=(V=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?V:[];for(let Je of T.map(ie=>ie.id))for(let ie of y[Je]){let di=(D=ie.getAttribute("id"))!=null?D:"id"+(x++).toString(10),zr=(_=ie.getAttribute("mimeType"))!=null?_:"",Su=(X=ie.getAttribute("codecs"))!=null?X:"",vu=(Z=ie.getAttribute("contentType"))!=null?Z:zr==null?void 0:zr.split("/")[0],UE=(k=(E=ie.getAttribute("profiles"))==null?void 0:E.split(","))!=null?k:[],Qp=(A=KT((w=ie.getAttribute("lang"))!=null?w:""))!=null?A:{},Ka=(ct=(G=(B=ie.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:G.trim())!=null?ct:void 0,jE=ie.querySelectorAll("Representation"),HE=ie.querySelector("SegmentTemplate"),QE=(Y=(dt=ie.querySelector("Role"))==null?void 0:dt.getAttribute("value"))!=null?Y:void 0,Gi=vu,ce={id:di,language:Qp.language,isDefault:QE==="main",label:Ka,codecs:Su,hdr:Gi==="video"&&Xc(Su),mime:zr,representations:[]};for(let te of jE){let Ft=(ge=te.getAttribute("lang"))!=null?ge:void 0,Yr=(ve=(Se=Ka!=null?Ka:ie.getAttribute("label"))!=null?Se:te.getAttribute("label"))!=null?ve:void 0,Xa=(Ot=(xt=(Fe=te.querySelector("BaseURL"))==null?void 0:Fe.textContent)==null?void 0:xt.trim())!=null?Ot:"",pi=new URL(Xa||o,e).toString(),Nt=(ci=te.getAttribute("mimeType"))!=null?ci:zr,Ja=(Gr=(Wi=te.getAttribute("codecs"))!=null?Wi:Su)!=null?Gr:"",Za;if(vu==="text"){let qt=te.getAttribute("id")||"",en=((lp=Qp.privateuse)==null?void 0:lp.includes("x-auto"))||qt.includes("_auto"),hi=te.querySelector("SegmentTemplate");if(hi){let Kr={representationId:(cp=te.getAttribute("id"))!=null?cp:void 0,bandwidth:(dp=te.getAttribute("bandwidth"))!=null?dp:void 0},tn=parseInt((pp=te.getAttribute("bandwidth"))!=null?pp:"",10)/1e3,rn=(fp=parseInt((hp=hi.getAttribute("startNumber"))!=null?hp:"",10))!=null?fp:1,zi=parseInt((mp=hi.getAttribute("timescale"))!=null?mp:"",10),yu=(bp=hi.querySelectorAll("SegmentTimeline S"))!=null?bp:[],Yi=hi.getAttribute("media");if(!Yi)continue;let sn=[],an=0,nn="",Ki=0,Xr=rn,xe=0;for(let Ze of yu){let fi=parseInt((gp=Ze.getAttribute("d"))!=null?gp:"",10),Ge=parseInt((Sp=Ze.getAttribute("r"))!=null?Sp:"",10)||0,Ut=parseInt((vp=Ze.getAttribute("t"))!=null?vp:"",10);xe=Number.isFinite(Ut)?Ut:xe;let mi=fi/zi*1e3,jt=xe/zi*1e3;for(let pt=0;pt<Ge+1;pt++){let Ht=ot(Yi,{...Kr,segmentNumber:Xr.toString(10),segmentTime:(xe+pt*fi).toString(10)}),Xi=(jt!=null?jt:0)+pt*mi,Zr=Xi+mi;Xr++,sn.push({time:{from:Xi,to:Zr},url:Ht})}xe+=(Ge+1)*fi,an+=(Ge+1)*mi}Ki=xe/zi*1e3,nn=ot(Yi,{...Kr,segmentNumber:Xr.toString(10),segmentTime:xe.toString(10)});let Jr={time:{from:Ki,to:1/0},url:nn},wt={type:"template",baseUrl:pi,segmentTemplateUrl:Yi,initUrl:"",totalSegmentsDurationMs:an,segments:sn,nextSegmentBeyondManifest:Jr,timescale:zi};Za={id:qt,kind:"text",segmentReference:wt,profiles:[],duration:b,bitrate:tn,mime:"",codecs:"",width:0,height:0,isAuto:en}}else Za={id:qt,isAuto:en,kind:"text",url:pi}}else{let qt=(Tp=(yp=te.getAttribute("contentType"))!=null?yp:Nt==null?void 0:Nt.split("/")[0])!=null?Tp:vu,en=(Ep=(Ip=ie.getAttribute("profiles"))==null?void 0:Ip.split(","))!=null?Ep:[],hi=parseInt((xp=te.getAttribute("width"))!=null?xp:"",10),Kr=parseInt((wp=te.getAttribute("height"))!=null?wp:"",10),tn=parseInt((Ap=te.getAttribute("bandwidth"))!=null?Ap:"",10)/1e3,rn=(Rp=te.getAttribute("frameRate"))!=null?Rp:"",zi=(Pp=te.getAttribute("quality"))!=null?Pp:void 0,yu=rn?YT(rn):void 0,Yi=(kp=te.getAttribute("id"))!=null?kp:"id"+(x++).toString(10),sn=qt==="video"?`${Kr}p`:qt==="audio"?`${tn}Kbps`:Ja,an=`${Yi}@${sn}`,nn=[...L,...UE,...en],Ki,Xr=te.querySelector("SegmentBase"),xe=(Lp=te.querySelector("SegmentTemplate"))!=null?Lp:HE;if(Xr){let wt=(Mp=($p=te.querySelector("SegmentBase Initialization"))==null?void 0:$p.getAttribute("range"))!=null?Mp:"",[Ze,fi]=wt.split("-").map(Ht=>parseInt(Ht,10)),Ge={from:Ze,to:fi},Ut=(Dp=te.querySelector("SegmentBase"))==null?void 0:Dp.getAttribute("indexRange"),[mi,jt]=Ut?Ut.split("-").map(Ht=>parseInt(Ht,10)):[],pt=Ut?{from:mi,to:jt}:void 0;Ki={type:"byteRange",url:pi,initRange:Ge,indexRange:pt}}else if(xe){let wt={representationId:(Cp=te.getAttribute("id"))!=null?Cp:void 0,bandwidth:(Bp=te.getAttribute("bandwidth"))!=null?Bp:void 0},Ze=parseInt((Vp=xe.getAttribute("timescale"))!=null?Vp:"",10),fi=(_p=xe.getAttribute("initialization"))!=null?_p:"",Ge=xe.getAttribute("media"),Ut=(Fp=parseInt((Op=xe.getAttribute("startNumber"))!=null?Op:"",10))!=null?Fp:1,mi=ot(fi,wt);if(!Ge)throw new ReferenceError("No media attribute in SegmentTemplate");let jt=(Np=xe.querySelectorAll("SegmentTimeline S"))!=null?Np:[],pt=[],Ht=0,Xi="",Zr=0;if(jt.length){let on=Ut,et=0;for(let Ji of jt){let ht=parseInt((qp=Ji.getAttribute("d"))!=null?qp:"",10),bi=parseInt((Up=Ji.getAttribute("r"))!=null?Up:"",10)||0,un=parseInt((jp=Ji.getAttribute("t"))!=null?jp:"",10);et=Number.isFinite(un)?un:et;let Tu=ht/Ze*1e3,Iu=et/Ze*1e3;for(let ln=0;ln<bi+1;ln++){let GE=ot(Ge,{...wt,segmentNumber:on.toString(10),segmentTime:(et+ln*ht).toString(10)}),Wp=(Iu!=null?Iu:0)+ln*Tu,zE=Wp+Tu;on++,pt.push({time:{from:Wp,to:zE},url:GE})}et+=(bi+1)*ht,Ht+=(bi+1)*Tu}Zr=et/Ze*1e3,Xi=ot(Ge,{...wt,segmentNumber:on.toString(10),segmentTime:et.toString(10)})}else if(mB(b)){let et=parseInt((Hp=xe.getAttribute("duration"))!=null?Hp:"",10)/Ze*1e3,Ji=Math.ceil(b/et),ht=0;for(let bi=1;bi<Ji;bi++){let un=ot(Ge,{...wt,segmentNumber:bi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+et},url:un}),ht+=et}Zr=ht,Xi=ot(Ge,{...wt,segmentNumber:Ji.toString(10),segmentTime:ht.toString(10)})}let WE={time:{from:Zr,to:1/0},url:Xi};Ki={type:"template",baseUrl:pi,segmentTemplateUrl:Ge,initUrl:mi,totalSegmentsDurationMs:Ht,segments:pt,nextSegmentBeyondManifest:WE,timescale:Ze}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!qt||!Nt)continue;let Jr={video:"video",audio:"audio",text:"text"}[qt];if(!Jr)continue;Gi||(Gi=Jr),Za={id:an,kind:Jr,segmentReference:Ki,profiles:nn,duration:b,bitrate:tn,mime:Nt,codecs:Ja,width:hi,height:Kr,fps:yu,quality:zi}}ce.language||(ce.language=Ft),ce.label||(ce.label=Yr),ce.mime||(ce.mime=Nt),ce.codecs||(ce.codecs=Ja),ce.hdr||(ce.hdr=Gi==="video"&&Xc(Ja)),ce.representations.push(Za)}if(Gi){let te=r[Gi].find(Ft=>Ft.id===ce.id);if(te&&ce.representations.every(Ft=>Ft.segmentReference.type==="template"))for(let Ft of te.representations){let Yr=ce.representations.find(Nt=>Nt.id===Ft.id),Xa=Yr==null?void 0:Yr.segmentReference,pi=Ft.segmentReference;pi.segments.push(...Xa.segments),pi.nextSegmentBeyondManifest=Xa.nextSegmentBeyondManifest}else r[Gi].push(ce)}}return{duration:b,streams:r,baseUrls:n,live:g}};var ed=O(at(),1);import{videoSizeToQuality as bB}from"@vkontakte/videoplayer-shared/es2018";var fa=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Kt(a):void 0)!=null?u:bB({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},iI=({id:s,bitrate:e})=>({id:s,bitrate:e}),rI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),sI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),td=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,ed.default)(i.split("."),0),isDefault:r}),id=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,ed.default)(r.split("."),0)}),rd=s=>"url"in s,He=s=>s.type==="template";import{isNonNullable as aI}from"@vkontakte/videoplayer-shared/es2018";var N=(s,e)=>aI(s)&&aI(e)&&s.readyState==="open"&&gB(s,e);function gB(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var ma=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Vi(0);this.currentLowLatencySegmentLength$=new Vi(0);this.currentSegmentLength$=new Vi(0);this.onLastSegment$=new Vi(!1);this.fullyBuffered$=new Vi(!1);this.playingRepresentation$=new Vi(void 0);this.playingRepresentationInit$=new Vi(void 0);this.error$=new yB;this.gaps=[];this.subscription=new TB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ee;this.switchAbortController=new ee;this.destroyAbortController=new ee;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=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Le(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new eT(this.sourceBuffer),this.subscription.add(sd(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(sd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Le(i,"No init buffer for starting representation"),Le(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(pe(a)||pe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Le(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ei(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=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Le(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(pe(a)||pe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Le(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ei(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=Zt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Ao.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!He(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Le(r);let a=this.segments.get(i);Le(a,"No segments for starting representation");let n=this.initData.get(i);if(Le(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ee,Zt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);Le(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(pe(o)||pe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Le(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();ei(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 ee,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var f;if(pe(e)||pe(this.downloadingRepresentationId)||pe(this.playingRepresentationId)||pe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||ei(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(Le(t,`No such representation ${this.downloadingRepresentationId}`),Le(i,`No such representation ${this.playingRepresentationId}`),pe(r)||pe(a))return;let n=r.find(p=>e>=p.time.from&&e<p.time.to);ei(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 p=this.getForwardBufferDuration(e),h=fa(i),m=fa(t),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&ei(h)&&ei(m)&&SB(h.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(g||b?o+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(f=[...this.segments.entries()].map(([y,I])=>{let x=I.find(L=>e>=L.time.from&&e<L.time.to);return{representationId:y,status:x==null?void 0:x.status}}).find(y=>y.status==="fed"))==null?void 0:f.representationId;if(!T)return;this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))}}if(isFinite(this.bufferLimit)&&Ar(this.sourceBuffer.buffered)>=this.bufferLimit){let p=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let c=[];if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(r,t.segmentReference.type,o),c.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,wo.default)(c,n))p="high";else{let h=(0,_i.default)(c,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(c,t,p).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!c.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,_i.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;ei(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Ao.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,Ao.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!He(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(a=(0,_i.default)(c,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Le(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,_i.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!He(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),c=ot(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,b=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+v||r<v&&h-p>=v||h<=i+v;return(f==="none"||f==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ee(this.sourceBuffer.buffered,p)&&Ee(this.sourceBuffer.buffered,h)))&&b&&T});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=a;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){He(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Zt(o,async function*(){let c=ad(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=xo(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())He(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Zt(n,async function*(){let u=ad(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),sd(window,"online").pipe(vB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=xo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(He(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,_i.default)(e,0).byte.from,to:(0,_i.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=xo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!He(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=xo();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,wo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,f=d-c+1,p=c<r,h=d<=r;if(!p)continue;let m=Tt(o.mime);if(l.status==="downloading"&&h){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===f?g:m.parseFeedableSegmentChunk(g);b!=null&&b.byteLength&&(l.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(pe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ee(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ee(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.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",rd(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=wr(()=>(0,nI.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?Zt(this.destroyAbortController.signal,async function*(){let o=ad(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&He(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Mt.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||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||pe(e))return!1;let r=[],a=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:f}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,f):l.push(u[c])}return l},o=u=>{var c;if(a>=t)return r;r.push({...u.time}),r=n(r);let l=rd(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let f of this.segments.values())for(let p of f)(0,wo.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let f={time:{from:l,to:c},url:"",status:"none"};o(f)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!N(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||!N(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||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||pe(e)?0:Ie(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:a}=this.sourceBuffer;for(let n=0;n<a.length;n++){let o=a.start(n)*1e3,u=a.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(a=>{if(r&&a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=wr(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(pe(this.sourceBuffer)||!N(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),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Mt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ti=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Ro=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as ba,assertNever as oI,fromEvent as uI,merge as IB,now as ga,Subject as $r,ValueSubject as nd,flattenObject as Mr,ErrorCategory as Sa,SubscriptionRemovable as EB}from"@vkontakte/videoplayer-shared/es2018";var Po=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Lo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new $r;this.manifestReceived=new $r;this.firstBytesRequested=new $r;this.firstBytesReceived=new $r;this.lastConnectionType$=new nd(void 0);this.lastConnectionReused$=new nd(void 0);this.lastRequestFirstBytes$=new nd(void 0);this.recoverableError$=new $r;this.error$=new $r;this.abortAllController=new ee;this.subscription=new EB;this.fetchManifest=ba(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ti(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Po(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ko);return r?(t.log("success",Mr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Mr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ba(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var _,X,Z;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(c,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),c=E.toString();break}default:oI(t)}this.requestQuic&&(c=ti(c));let p=this.abortAllController.signal,h;if(n){let E=new ee;if(h=IB(uI(this.abortAllController.signal,"abort"),uI(n,"abort")).subscribe(()=>{try{E.abort()}catch(k){ko(k)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(k){ko(k)}p=E.signal}let m=0,g=ga();f.log("startRequest",Mr({url:c,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let b=yield this.doFetch(c,{priority:a,headers:d,signal:p}),v=ga();if(!b)return f.error("error",{message:"No response in request"}),f.end(),this.unsubscribeAbortSubscription(h),null;if((_=this.throughputEstimator)==null||_.addRawRtt(v-g),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let E=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:E}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let E=ga(),k={requestStartedAt:g,requestEndedAt:E,duration:E-g};return f.log("endRequest",Mr(k)),f.end(),b.arrayBuffer()}let T=b.body;if(o){let E;[T,E]=b.body.tee(),(X=this.throughputEstimator)==null||X.trackStream(E,u)}let y=T.getReader(),I,x=parseInt((Z=b.headers.get("content-length"))!=null?Z:"",10);Number.isFinite(x)&&(I=x),!I&&i&&(I=i.to-i.from+1);let L=I?new Uint8Array(I):new Uint8Array(0),M=!1,R=E=>{this.unsubscribeAbortSubscription(h),M=!0,ko(E)},P=ba(p,async function*({done:E,value:k}){if(m===0&&(this.lastRequestFirstBytes$.next(ga()-g),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!E&&k){if(l&&I)L.set(k,m),m+=k.byteLength;else{let w=new Uint8Array(L.length+k.length);w.set(L),w.set(k,L.length),L=w,m+=k.byteLength}r==null||r(new DataView(L.buffer),m),yield y==null?void 0:y.read().then(P,R)}}.bind(this));yield y==null?void 0:y.read().then(P,R),this.unsubscribeAbortSubscription(h);let V=ga(),D={failed:M,requestStartedAt:g,requestEndedAt:V,duration:V-g};return M?(f.error("endRequest",Mr(D)),f.end(),null):(f.log("endRequest",Mr(D)),f.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=ba(this.abortAllController.signal,async function*(e,t,i){var b;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(c,a))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let v=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=ba(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Ro(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:oI(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(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Sa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Sa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Sa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Sa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Sa.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ko=s=>{if(!It(s))throw s};var Dt=(s,e,t)=>t*e+(1-t)*s,od=(s,e)=>s.reduce((t,i)=>t+i,0)/e,lI=(s,e,t,i)=>{let r=0,a=t,n=od(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};import{isNullable as xB,ValueSubject as cI}from"@vkontakte/videoplayer-shared/es2018";var ii=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 cI(e.initial),this.debounced$=new cI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Pe(`raw_${t}`),this.smoothedSeries$=new Pe(`smoothed_${t}`),this.reportedSeries$=new Pe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(xB(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var $o=class extends ii{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Dt(this.slow,e,this.params.emaAlphaSlow),this.fast=Dt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Mo=class extends ii{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=od(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);let i=lI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Do=class extends ii{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?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Ct=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new $o({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Mo({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 Do({initial:e,label:"liveEdgeDelay",...t})}};var Dr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as wB,ValueSubject as AB}from"@vkontakte/videoplayer-shared/es2018";var va=class s{constructor(e,t){this.currentRepresentation$=new AB(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(!wB(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&He(t.segmentReference))}};var Bo=O(at(),1),ud=O(Ce(),1);import{assertNever as Vo}from"@vkontakte/videoplayer-shared/es2018";var Co=s=>{let{webmDecodingInfo:e}=F.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Vo(s)}return[t,i]},dI=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...Co(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(F.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...Co(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Co(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Co(s),...a,"HLS","HLS_ONDEMAND"];default:Vo(e)}if(F.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Vo(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},pI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=F.device.isMac&&F.browser.isSafari;if(F.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:Vo(s)}else F.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},ld=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],_o=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Bo.default)(t.value.split("."),0)}for(let t of s){let i=(0,Bo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Bo.default)(e.value.split("."),0)},Oo=s=>{let e=s.map(i=>Cr(i)),{codecs:t}=F.video;return LB().filter(i=>{if((0,ud.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})},Fo=s=>{let e=s.map(i=>Cr(i)),{codecs:t}=F.video;return $B().filter(i=>{if((0,ud.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Cr=s=>s.split(".")[0].replace("0",""),LB=()=>["av1","vp9","hev1","avc1"],$B=()=>["opus","mp4a"];var _B=["timeupdate","progress","play","seeked","stalled","waiting"],OB=["timeupdate","progress","loadeddata","playing","seeked"];var qo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new mI;this.representationSubscription=new mI;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 ri;this.manifestRequested=new ri;this.manifestReceived=new ri;this.firstBytesRequested=new ri;this.firstBytesReceived=new ri;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 ri;this.fetcherError$=new ri;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ri;this.gapWatchdogActive=!1;this.destroyController=new ee;this.initManifest=dd(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ue(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:ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=dd(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ut.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=Eo(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=To(e))!=null?u:{id:"ManifestParsing",category:ut.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,m,g;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((g=(m=je())==null?void 0:m.isTypeSupported)!=null&&g.call(m,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";p||(m=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:m})=>i(c,h,m));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:m})=>m);c==="audio"&&(n=Fo(h),p=n[0]),c==="video"&&(a=Oo(h),this.forceVideoCodec&&(0,gI.default)(a,this.forceVideoCodec)?p=this.forceVideoCodec:p=a[0]),p&&(r[c]=f.filter(({codecs:m})=>Cr(m)===p))}else{let h=new Set(f.map(({codecs:m})=>m));p=_o(h),p&&(r[c]=f.filter(({codecs:m})=>m.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),g=r.video.some(b=>!b.hdr);F.display.isHDR&&h&&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:a,audio:n}),this.tracer.log("updateManifestEnd",Ta(o)),o}.bind(this));this.initRepresentations=dd(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",Ta({initialVideo:e,initialAudio:t,sourceHls:i})),Br(this.manifest),Br(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Bt(p,"error").pipe(No(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Kn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),br())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 ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ia(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new ma("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}va.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new va(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Oi(...OB.map(p=>Bt(this.element,p))).pipe(_r(p=>this.element?Ie(this.element.buffered,this.element.currentTime*1e3):0),ya(),BB(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Oi(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ya()).subscribe(h=>this.liveStreamEndTimestamp=hd())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=pd(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=ue(this.manifestUrlString,m+1e3,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(Vr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(_r(({isActiveLive:h,isLowLatency:m})=>h&&m),ya()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Dr(this.element,1)})),this.representationSubscription.add(Vr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(No(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!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(Vr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(No(({isLive:h})=>h),ya((h,m)=>m.bufferLength<h.bufferLength),_r(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let b=zt(this.manifestUrlString,2);return(h/2+m+g+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Vr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,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=h-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(y)>v&&(I=1+Math.sign(y)*T),Dr(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,b;let m=0;if(h){let v=((b=(g=this.element)==null?void 0:g.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var I,x;return(x=(I=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?x:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Vr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(VB(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,b=zt(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,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,x=isFinite(h)?h:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),M=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(M);let R="none";if(L?R="active_low_latency":this.isLowLatency$.getValue()&&M?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),R="active_low_latency"):b!==0&&x<T?R="live_forward_buffering":x<T+I&&(R="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),R==="live_forward_buffering"||R==="live_with_target_offset"){let P=p-(T+y),V=this.normolizeLiveOffset(Math.trunc(b+P/g)),D=Math.abs(V-b),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=b:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=ue(this.manifestUrlString,_,2)}(R==="live_with_target_offset"||R==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ut.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Oi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(_r(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Oi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(_r(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Vr({allBuffersFull:l,someBufferEnded:c}).pipe(ya(),_r(({allBuffersFull:p,someBufferEnded:h})=>p&&h),No(p=>p));if(this.representationSubscription.add(Oi(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:ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Oi(...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 g;if(((g=this.source)==null?void 0:g.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ut.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=[(f=this.manifest.duration)!=null?f:0,...(0,fd.default)((0,fd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),He(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Ia(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=pd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ut.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 Lo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.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,a,n;Br(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?hd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ue(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((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Br(this.element),this.state$.setState("running"),this.subscription.add(Oi(..._B.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ut.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(()=>{var t;this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Ee(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,m,g,b,v,T,y,I,x,L;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=hd(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.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,c=(I=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,d=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&c<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||f)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let M=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(M).catch(R=>{this.error$.next({id:"stallIntervalCallback",category:ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:R})}),r.liveLastOffset=M}else{let M=this.element.currentTime*1e3;(x=this.videoBufferManager)==null||x.maintain(M),(L=this.audioBufferManager)==null||L.maintain(M),r.position=M}this.tracer.log("stallIntervalCallback",Ta(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=pd(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ut.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;Br(this.element),Br(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ee(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(fI(this.element)||fI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ta({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Ia(this.element)&&Ia(this.source)&&Ia(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=CB(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(r&&l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ta(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var Uo=class{constructor(e,t){this.fov=e,this.orientation=t}};var jo=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,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...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 SI=`attribute vec2 a_vertex;
|
|
125
125
|
attribute vec2 a_texel;
|
|
126
126
|
|
|
127
127
|
varying vec2 v_texel;
|
|
@@ -132,7 +132,7 @@ void main(void) {
|
|
|
132
132
|
// save texel vector to pass to fragment shader
|
|
133
133
|
v_texel = a_texel;
|
|
134
134
|
}
|
|
135
|
-
`;var
|
|
135
|
+
`;var vI=`#ifdef GL_ES
|
|
136
136
|
precision highp float;
|
|
137
137
|
precision highp int;
|
|
138
138
|
#else
|
|
@@ -175,6 +175,6 @@ void main(void) {
|
|
|
175
175
|
// sample using new coordinates
|
|
176
176
|
gl_FragColor = texture2D(u_texture, tc);
|
|
177
177
|
}
|
|
178
|
-
`;var _r=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 Co(this.params.fov,this.params.orientation),this.cameraRotationManager=new Bo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(bI,this.gl.VERTEX_SHADER),i=this.createShader(gI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,f=t+r;return[a,n,o,u,l,c,d,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as FB,now as Ta,once as NB,Subscription as qB,ValueSubject as cd,isNonNullable as UB,safeStorage as dd,filterChanged as HB}from"@vkontakte/videoplayer-shared/es2018";var Vo="stalls_manager_metrics",pd="stalls_manager_abr_params",vI="stalls_manager_default_tuning_abr_params",hd=class{constructor(){this.isSeeked$=new cd(!1);this.isBuffering$=new cd(!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 qB;this.severeStallOccurred$=new cd(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(pd):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Ta(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Ta()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(vI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(pd),this.setStoredData(vI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Vo,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(Vo,[]),this.setStoredData(pd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){var i;return JSON.parse((i=dd.get(e))!=null?i:t)}setStoredData(e,t){dd.set(e,JSON.stringify(t))}removeStoredData(e){dd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Vo,"[]"),r=t/e,a=i.length?Dt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Vo,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(NB()).subscribe(t=>this.providerStartWatchingTimestamp=Ta())),this.subscription.add(this.currentStallDuration$.pipe(HB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(FB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Ta(),d=r&&this.currentStallsCount>=r,f=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,UB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Ta()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},_o=hd;import{combine as jB,map as QB,observeElementSize as WB,Subscription as GB,ValueSubject as fd,noop as zB}from"@vkontakte/videoplayer-shared/es2018";var Oo=class{constructor(){this.subscription=new GB;this.pipSize$=new fd(void 0);this.videoSize$=new fd(void 0);this.elementSize$=new fd(void 0);this.pictureInPictureWindowRemoveEventListener=zB}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(WB(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(jB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(QB(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Vi=class{constructor(e){this.subscription=new t0;this.videoState=new H("stopped");this.observableVideo=null;this.droppedFramesManager=new Tr;this.stallsManager=new _o;this.elementSizeManager=new Oo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new 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.hostname$.next(void 0),this.videoState.setState("stopped"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return KB(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new _r(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=De(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(Te(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 Do({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;e0(this.observableVideo)&&(this.observableVideo=Ve(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:SI.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(md(l=>!!l.length),TI()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(bd(l=>l.to.state!=="none"),Fo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(md(yI),TI()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(bd(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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"),L(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),d=this.player.getCodecs();if(XB(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Kc(h));let m=[];for(let v of h.representations){let b=eI(v);m.push(b),this.audioTracksMap.set(b,{stream:h,representation:v})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let f=[];for(let p of c.video){f.push(Xc(p));let h=[];for(let m of p.representations){let v=ZT({...m,streamId:p.id});v&&(h.push(v),this.videoTracksMap.set(v,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(f);for(let p of c.text)for(let h of p.representations){let m=tI(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),d!=null&&d.video&&this.params.output.availableVideoCodecs$.next(d.video),d!=null&&d.audio&&this.params.output.availableAudioCodecs$.next(d.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(No(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$,ZB(this.video,"progress")).pipe(md(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,II.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[f,p]=d,h=[...this.videoTracksMap.keys()].find(v=>{var b;return((b=this.videoTracksMap.get(v))==null?void 0:b.representation.id)===f.id});yI(h)&&(this.stallsManager.lastVideoTrackSelected=h);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),p){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,v)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Fo()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Xc(f));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Fo()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Kc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(bd(({to:l})=>l==="ready"),Fo());this.subscription.add(No(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,gd(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(No(o,this.player.state$.stateChangeEnded$,gd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=No(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,gd(["init"])).pipe(JB(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var P,V,D,_,K,J,I,R,x,w,B,ne,Ne;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ls:ks,t=this.params.tuning.useNewAutoSelectVideoTrack?ao:so,i=this.params.tuning.useNewAutoSelectVideoTrack?St:ro,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(P=r.videoTrack.getState())==null?void 0:P.id,l=[...this.videoTracksMap.keys()].find(({id:ie})=>ie===o),c=a.currentVideoTrack$.getValue(),d=((_=(D=r.videoStream.getState())!=null?D:l&&((V=this.videoTracksMap.get(l))==null?void 0:V.stream))!=null?_:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let f=[...this.videoStreamsMap.keys()].find(({id:ie})=>ie===d.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=be(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let v=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(h/Math.min(m,v||1/0),1),S=(K=r.audioStream.getState())!=null?K:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,T=(J=[...this.audioStreamsMap.keys()].find(({id:ie})=>ie===(S==null?void 0:S.id)))!=null?J:this.audioStreamsMap.keys().next().value,y=0;if(T){if(l&&!n){let ie=e(l,p,(I=this.audioStreamsMap.get(T))!=null?I:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(R=ie==null?void 0:ie.bitrate)!=null?R:-1/0)}if(c){let ie=e(c,p,(x=this.audioStreamsMap.get(T))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(w=ie==null?void 0:ie.bitrate)!=null?w:-1/0)}}let E=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:y,forwardBufferHealth:b,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),k=n?E!=null?E:l:l!=null?l:E,M=T&&t(k,p,(B=this.audioStreamsMap.get(T))!=null?B:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),$=(ne=this.videoTracksMap.get(k))==null?void 0:ne.representation,A=M&&((Ne=this.audioTracksMap.get(M))==null?void 0:Ne.representation);if($&&A)return[$,A];if($&&!A&&this.audioTracksMap.size===0)return[$,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:SI.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),Ce(this.video),this.tracer.end()}};var Ia=class extends Vi{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 vd,merge as EI,filter as xI,filterChanged as wI,isNullable as Sd,map as AI,ValueSubject as yd,isNonNullable as i0}from"@vkontakte/videoplayer-shared/es2018";var Ea=class extends Vi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new yd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(wI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(AI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(vd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(AI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(xI(u=>i0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(vd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:EI(r.playbackRateState$,new yd(1))}).pipe(xI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||Sd(c)||(t=u-c)})).add(vd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:EI(r.playbackRateState$,new yd(1))}).pipe(wI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||Sd(u)||Sd(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=iI(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)})}};import{assertNever as R0,assertNonNullable as k0,debounce as L0,ErrorCategory as jI,filter as Vd,filterChanged as Xo,fromEvent as $0,isNonNullable as QI,isNullable as M0,map as _d,merge as Jo,observableFrom as Od,once as WI,Subscription as D0}from"@vkontakte/videoplayer-shared/es2018";var HI=O(Ae(),1),Cd=O(Os(),1);import{abortable as Ld,assertNonNullable as qr,combine as Ur,ErrorCategory as dt,filter as zo,filterChanged as ka,flattenObject as La,fromEvent as Et,getTraceSubscriptionMethod as v0,interval as $d,isNonNullable as $a,isNullable as qI,map as Hr,merge as qi,now as Md,Subject as si,Subscription as Dd,tap as S0,throttle as UI,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var jo=O(Ae(),1),Ni=O(ot(),1),Qo=O(Os(),1);var _I=O(Vn(),1);import{assertNever as r0,ErrorCategory as PI,Subject as RI}from"@vkontakte/videoplayer-shared/es2018";var s0=18,kI=!1;try{kI=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=s0}catch(s){console.error(s)}var Td=class{constructor(e){this.bufferFull$=new RI;this.error$=new RI;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:PI.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};kI&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:PI.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:r0(t)}}},LI=Td;import{abortable as ri,assertNonNullable as Fe,ErrorCategory as Oi,fromEvent as Ad,getExponentialDelay as Pd,isNonNullable as Or,isNullable as xe,now as Ho,once as l0,Subject as c0,Subscription as d0,ValueSubject as Fi}from"@vkontakte/videoplayer-shared/es2018";var Id=O(ot(),1);import{videoSizeToQuality as a0,throttleFn as n0}from"@vkontakte/videoplayer-shared/es2018";var $I=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Kt(a):void 0)!=null?u:a0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},MI=({id:s,bitrate:e})=>({id:s,bitrate:e}),DI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),CI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ed=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Id.default)(i.split("."),0),isDefault:r}),xd=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Id.default)(r.split("."),0)}),wd=s=>"url"in s,Ge=s=>s.type==="template";var BI=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},_i=(s,e)=>{for(let t of s)if(e(t))return t;return null},VI=s=>{let e=!1,t=n0(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as o0,Subscription as u0}from"@vkontakte/videoplayer-shared/es2018";var qo=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var Uo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new u0;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(o0(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!N(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=qo(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var xa=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Fi(0);this.currentLowLatencySegmentLength$=new Fi(0);this.currentSegmentLength$=new Fi(0);this.onLastSegment$=new Fi(!1);this.fullyBuffered$=new Fi(!1);this.playingRepresentation$=new Fi(void 0);this.playingRepresentationInit$=new Fi(void 0);this.error$=new c0;this.gaps=[];this.subscription=new d0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;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=ri(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Fe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new LI(this.sourceBuffer),this.sourceBufferBufferedDiff=new Uo(this.mediaSource,this.sourceBuffer),this.subscription.add(Ad(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Ad(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Oi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,xr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=be(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Fe(i,"No init buffer for starting representation"),Fe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=ri(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Fe(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(xe(a)||xe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Fe(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Or(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=ri(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Fe(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(xe(a)||xe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Fe(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Or(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=ri(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Qo.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!Ge(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Fe(r);let a=this.segments.get(i);Fe(a,"No segments for starting representation");let n=this.initData.get(i);if(Fe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,ri(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);Fe(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(xe(o)||xe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Fe(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(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();Or(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(){!xe(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 Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(xe(e)||xe(this.downloadingRepresentationId)||xe(this.playingRepresentationId)||xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||Or(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Fe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Or(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=be(this.sourceBuffer.buffered,e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(a=d)}if(isFinite(this.bufferLimit)&&xr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=be(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,jo.default)(u,r))c="high";else{let d=(0,Ni.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&be(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Ni.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-be(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;Or(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Qo.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,Qo.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ge(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(a=(0,Ni.default)(c,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Fe(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ge(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=lt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let v=p<=i&&h>=i,b=p>i||v||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+S||r<S&&h-p>=S||h<=i+S;return(f==="none"||f==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&b&&T});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=a;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Ge(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ri(o,async function*(){let c=Pd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Ho(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ge(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ri(n,async function*(){let u=Pd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ad(window,"online").pipe(l0()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Ho(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ge(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ni.default)(e,0).byte.from,to:(0,Ni.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Ho(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Oi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ge(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Ho();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Oi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,jo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,c=l.byte.from-i,d=l.byte.to-i,f=d-c+1,p=c<r,h=d<=r;if(p){if(l.status==="downloading"&&h){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(m,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-c),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===f?m:Tt(o.mime).parseFeedableSegmentChunk(m);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Oi.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",wd(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Er(()=>(0,_I.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?ri(this.destroyAbortController.signal,async function*(){let o=Pd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&Ge(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Oi.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||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||xe(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push({...o.time});let u=wd(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let f of d)(0,jo.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let d={time:{from:u,to:l},url:"",status:"none"};n(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=BI(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||!N(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||!N(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||!N(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||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||xe(e)?0:be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Er(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Oi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||xe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=qo(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let c=0;c<e.length;c+=2){let d=e[c],f=e[c+1];u||(u=d-t<=n&&f+t>=o),(n>=d&&n<f-t||o>d+t&&o<=f)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Oi.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,Ni.default)(e,-1))==null?void 0:t.time.to:0)||0}};import{abortable as wa,assertNever as OI,fromEvent as FI,merge as p0,now as Aa,Subject as Fr,ValueSubject as Rd,flattenObject as Nr,ErrorCategory as Pa,SubscriptionRemovable as h0}from"@vkontakte/videoplayer-shared/es2018";var Go=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new Fr;this.manifestReceived=new Fr;this.firstBytesRequested=new Fr;this.firstBytesReceived=new Fr;this.lastConnectionType$=new Rd(void 0);this.lastConnectionReused$=new Rd(void 0);this.lastRequestFirstBytes$=new Rd(void 0);this.recoverableError$=new Fr;this.error$=new Fr;this.abortAllController=new Z;this.subscription=new h0;this.fetchManifest=wa(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=yo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Wo);return r?(t.log("success",Nr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Nr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=wa(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var _,K,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:OI(t)}this.requestQuic&&(c=ei(c));let p=this.abortAllController.signal,h;if(n){let I=new Z;if(h=p0(FI(this.abortAllController.signal,"abort"),FI(n,"abort")).subscribe(()=>{try{I.abort()}catch(R){Wo(R)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(R){Wo(R)}p=I.signal}let m=0,v=Aa();f.log("startRequest",Nr({url:c,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.firstBytesRequested.next();let b=yield this.doFetch(c,{priority:a,headers:d,signal:p}),S=Aa();if(!b)return f.error("error",{message:"No response in request"}),f.end(),this.unsubscribeAbortSubscription(h),null;if((_=this.throughputEstimator)==null||_.addRawRtt(S-v),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let I=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:I}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let I=Aa(),R={requestStartedAt:v,requestEndedAt:I,duration:I-v};return f.log("endRequest",Nr(R)),f.end(),b.arrayBuffer()}let T=b.body;if(o){let I;[T,I]=b.body.tee(),(K=this.throughputEstimator)==null||K.trackStream(I,u)}let y=T.getReader(),E,k=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(k)&&(E=k),!E&&i&&(E=i.to-i.from+1);let M=E?new Uint8Array(E):new Uint8Array(0),$=!1,A=I=>{this.unsubscribeAbortSubscription(h),$=!0,Wo(I)},P=wa(p,async function*({done:I,value:R}){if(m===0&&(this.lastRequestFirstBytes$.next(Aa()-v),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!I&&R){if(l&&E)M.set(R,m),m+=R.byteLength;else{let x=new Uint8Array(M.length+R.length);x.set(M),x.set(R,M.length),M=x,m+=R.byteLength}r==null||r(new DataView(M.buffer),m),yield y==null?void 0:y.read().then(P,A)}}.bind(this));yield y==null?void 0:y.read().then(P,A),this.unsubscribeAbortSubscription(h);let V=Aa(),D={failed:$,requestStartedAt:v,requestEndedAt:V,duration:V-v};return $?(f.error("endRequest",Nr(D)),f.end(),null):(f.log("endRequest",Nr(D)),f.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=wa(this.abortAllController.signal,async function*(e,t,i){var b;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(c,a))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let S=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!S)return null;m=new DataView(S)}let v=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:v}}.bind(this));this.fetchTemplateRepresentation=wa(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=So(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:OI(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ze(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Pa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Pa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Pa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Pa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Pa.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Wo=s=>{if(!It(s))throw s};import{isNullable as f0,ValueSubject as m0}from"@vkontakte/videoplayer-shared/es2018";var Ra=class s{constructor(e,t){this.currentRepresentation$=new m0(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(!f0(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ge(t.segmentReference))}};var y0=["progress","play","seeked","stalled","waiting"],T0=["timeupdate","progress","loadeddata","playing","seeked"];var Yo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Dd;this.representationSubscription=new Dd;this.state$=new H("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 si;this.manifestRequested=new si;this.manifestReceived=new si;this.firstBytesRequested=new si;this.firstBytesReceived=new si;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 si;this.fetcherError$=new si;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new si;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=Ld(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=Ld(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:dt.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=mo(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=ho(e))!=null?u:{id:"ManifestParsing",category:dt.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,m,v;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((v=(m=Qe())==null?void 0:m.isTypeSupported)!=null&&v.call(m,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";p||(m=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:m})=>i(c,h,m));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:m})=>m);c==="audio"&&(n=$o(h),p=n[0]),c==="video"&&(a=Lo(h),this.forceVideoCodec&&(0,HI.default)(a,this.forceVideoCodec)?p=this.forceVideoCodec:p=a[0]),p&&(r[c]=f.filter(({codecs:m})=>Dr(m)===p))}else{let h=new Set(f.map(({codecs:m})=>m));p=ko(h),p&&(r[c]=f.filter(({codecs:m})=>m.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),v=r.video.some(b=>!b.hdr);F.display.isHDR&&h&&m?r.video=r.video.filter(b=>b.hdr):v&&(r.video=r.video.filter(b=>!b.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",La(o)),o}.bind(this));this.initRepresentations=Ld(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",La({initialVideo:e,initialAudio:t,sourceHls:i})),qr(this.manifest),qr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Dd,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Et(p,"error").pipe(zo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=qn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),hr())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 xa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],$a(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new xa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ra.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ra(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(qi(...T0.map(p=>Et(this.element,p))).pipe(Hr(p=>this.element?be(this.element.buffered,this.element.currentTime*1e3):0),ka(),S0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(qi(Et(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ka()).subscribe(h=>this.liveStreamEndTimestamp=Md())),this.subscription.add(Et(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=$d(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Et(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(Hr(({isActiveLive:h,isLowLatency:m})=>h&&m),ka()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Mr(this.element,1)})),this.representationSubscription.add(Ur({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(zo(({bufferLength:h,isActiveLive:m,isLowLatency:v})=>m&&v&&!!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(zo(({isLive:h})=>h),ka((h,m)=>m.bufferLength<h.bufferLength),Hr(({rtt:h,bufferLength:m,segmentServerLatency:v})=>{let b=zt(this.manifestUrlString,2);return(h/2+m+v+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ur({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:v})=>{if(!v||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-b;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(y)>S&&(E=1+Math.sign(y)*T),Mr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var v,b;let m=0;if(h){let S=((b=(v=this.element)==null?void 0:v.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var E,k;return(k=(E=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?k:S}))-S}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Ur({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(UI(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,b=zt(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,k=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let A="none";if(M?A="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),A="active_low_latency"):b!==0&&k<T?A="live_forward_buffering":k<T+E&&(A="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),A==="live_forward_buffering"||A==="live_with_target_offset"){let P=p-(T+y),V=this.normolizeLiveOffset(Math.trunc(b+P/v)),D=Math.abs(V-b),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=b:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,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 l=qi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Hr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=qi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Hr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Ur({allBuffersFull:l,someBufferEnded:c}).pipe(ka(),Hr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),zo(p=>p));if(this.representationSubscription.add(qi(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(qi(...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 v;if(((v=this.source)==null?void 0:v.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)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,Cd.default)((0,Cd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ge(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&$a(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=$d(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 Go({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;qr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Md()-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((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){qr(this.element),this.state$.setState("running");let e=Et(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(UI(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(qi(...y0.map(t=>Et(this.element,t)),Et(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Et(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(Et(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,m,v,b,S,T,y,E,k,M,$;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=Md(),o=100,u=(v=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?v:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(S=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?S:0,c=(y=(T=this.videoBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?y:0,d=(k=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?k:0,f=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let A=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(A).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:dt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),a.liveLastOffset=A}else{let A=this.element.currentTime*1e3;(M=this.videoBufferManager)==null||M.maintain(A),($=this.audioBufferManager)==null||$.maintain(A),a.position=A}this.tracer.log("stallIntervalCallback",La(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=$d(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:dt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;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=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(qI(this.element)||qI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",La({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;$a(this.element)&&$a(this.source)&&$a(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=v0(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 a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",La({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 I0,map as E0,observeElementSize as x0,Subscription as w0,ValueSubject as Bd,noop as A0}from"@vkontakte/videoplayer-shared/es2018";var Ko=class{constructor(){this.subscription=new w0;this.pipSize$=new Bd(void 0);this.videoSize$=new Bd(void 0);this.elementSize$=new Bd(void 0);this.pictureInPictureWindowRemoveEventListener=A0}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(x0(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(I0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(E0(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Ui=class{constructor(e){this.subscription=new D0;this.videoState=new H("stopped");this.observableVideo=null;this.droppedFramesManager=new Tr;this.stallsManager=new _o;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.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return R0(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new _r(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=De(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(Te(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 Yo({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;M0(this.observableVideo)&&(this.observableVideo=Ve(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:jI.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Vd(d=>!!d.length),WI()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(_d(d=>d.to.state!=="none"),Xo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Vd(QI),WI()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(_d(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Be(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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"),L(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams(),p=this.player.getCodecs();if(k0(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let v of f.audio){m.push(Ed(v));let b=[];for(let S of v.representations){let T=MI(S);b.push(T),this.audioTracksMap.set(T,{stream:v,representation:S})}this.audioStreamsMap.set(v,b)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of f.video){h.push(xd(m));let v=[];for(let b of m.representations){let S=$I({...b,streamId:m.id});S&&(v.push(S),this.videoTracksMap.set(S,{stream:m,representation:b}))}this.videoStreamsMap.set(m,v)}this.params.output.availableVideoStreams$.next(h);for(let m of f.text)for(let v of m.representations){let b=DI(m,v);this.textTracksMap.set(b,{stream:m,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),p!=null&&p.video&&this.params.output.availableVideoCodecs$.next(p.video),p!=null&&p.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&VI(o)||null;this.subscription.add(Jo(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,$0(this.video,"progress")).pipe(Vd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),f=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||f||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let m=_i(this.videoTracksMap.keys(),b=>{var S;return((S=this.videoTracksMap.get(b))==null?void 0:S.representation.id)===p.id});QI(m)&&(this.stallsManager.lastVideoTrackSelected=m);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),d==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,b)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Xo()).subscribe(d=>{let f=_i(this.videoTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(xd(h));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Xo()).subscribe(d=>{let f=_i(this.audioTracksMap.entries(),([,{representation:v}])=>v.id===d);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Ed(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var f,p;if(d!=null&&d.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(_d(({to:d})=>d==="ready"),Xo());this.subscription.add(Jo(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Od(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Jo(l,this.player.state$.stateChangeEnded$,Od(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Jo(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Od(["init"])).pipe(L0(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var $,A,P,V,D,_,K,J,I,R,x,w;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ls:ks,t=this.params.tuning.useNewAutoSelectVideoTrack?ao:so,i=this.params.tuning.useNewAutoSelectVideoTrack?St:ro,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=($=r.videoTrack.getState())==null?void 0:$.id,u=_i(this.videoTracksMap.keys(),B=>B.id===o),l=a.currentVideoTrack$.getValue(),c=((V=(P=r.videoStream.getState())!=null?P:u&&((A=this.videoTracksMap.get(u))==null?void 0:A.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=_i(this.videoStreamsMap.keys(),B=>B.id===c.id),f=d&&this.videoStreamsMap.get(d);if(!f)return;let p=be(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(p/Math.min(h,m||1/0),1),b=(D=r.audioStream.getState())!=null?D:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(b==null?void 0:b.id)&&_i(this.audioStreamsMap.keys(),B=>B.id===b.id)||this.audioStreamsMap.keys().next().value,T=0;if(S){if(u&&!n){let B=e(u,f,(_=this.audioStreamsMap.get(S))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(K=B==null?void 0:B.bitrate)!=null?K:-1/0)}if(l){let B=e(l,f,(J=this.audioStreamsMap.get(S))!=null?J:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(I=B==null?void 0:B.bitrate)!=null?I:-1/0)}}let y=u;(n||!y)&&(y=i(f,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve: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 E=S&&t(y,f,(R=this.audioStreamsMap.get(S))!=null?R:[],{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}),k=(x=this.videoTracksMap.get(y))==null?void 0:x.representation,M=E&&((w=this.audioTracksMap.get(E))==null?void 0:w.representation);k&&M?(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=M):k&&!M&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:jI.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),Ce(this.video),this.tracer.end()}};var Ma=class extends Ui{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 Fd,merge as GI,filter as zI,filterChanged as YI,isNullable as Nd,map as KI,ValueSubject as qd,isNonNullable as C0}from"@vkontakte/videoplayer-shared/es2018";var Da=class extends Ui{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new qd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(YI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(KI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Fd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(KI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(zI(u=>C0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Fd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:GI(r.playbackRateState$,new qd(1))}).pipe(zI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||Nd(c)||(t=u-c)})).add(Fd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:GI(r.playbackRateState$,new qd(1))}).pipe(YI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||Nd(u)||Nd(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=CI(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 XI="X-Playback-Duration",Ud=async s=>{var r;let e=await Ze(s),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(XI)?parseInt(e.headers.get(XI),10):void 0};import{assertNever as Q0,combine as W0,debounce as G0,ErrorCategory as tu,filter as z0,filterChanged as Y0,isNonNullable as eE,isNullable as iu,map as tE,merge as K0,observableFrom as X0,Subscription as J0,ValueSubject as Qd,VideoQuality as Z0}from"@vkontakte/videoplayer-shared/es2018";var jd=O(xl(),1);import{videoSizeToQuality as B0,getExponentialDelay as V0}from"@vkontakte/videoplayer-shared/es2018";var _0=s=>{let e=null;if(s.QUALITY&&(e=Kt(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=B0({width:t,height:i})}return e!=null?e:null},O0=(s,e)=>{var a,n;let t=s.split(`
|
|
179
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,
|
|
180
|
-
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+c},url:l}),a=a+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(N0(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 Z;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:j0.WTF,thrown:t,message:e})}};var Ca=class{constructor(e){this.subscription=new J0;this.videoState=new H("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Qd([]);this.liveOffset=new Ri;this.manifestStartTime$=new Qd(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(L(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Q0(t)}};var i;this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Z0.INVARIANT,url:this.params.source.url};let t=(r,a)=>Zo(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new eu(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Xe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:tu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:tu.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(Te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Qd((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:tu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ve(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),a(Je(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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(Y0(),tE(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&eE(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(W0({startTime:this.manifestStartTime$.pipe(z0(eE)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(tE(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=K0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,X0(["init"])).pipe(G0(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),Ce(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(iu(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[c,"mq"],[d,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=le(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Ud(n).then(c=>{var d;if(!iu(c))this.maxSeekBackTime$.next(c);else{let f=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(iu(f)||!isFinite(f))&&Ze(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let v=new URL(h,n).toString();Ud(v).then(b=>{iu(b)||this.maxSeekBackTime$.next(b)})}}).catch(()=>{})}})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tu.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 eV,debounce as tV,ErrorCategory as Wd,fromEvent as Gd,isNonNullable as iV,isNullable as rV,map as iE,merge as rE,observableFrom as sE,Subscription as sV,ValueSubject as aV,VideoQuality as nV}from"@vkontakte/videoplayer-shared/es2018";var Ba=class{constructor(e){this.subscription=new sV;this.videoState=new H("stopped");this.manifests$=new aV([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return eV(t)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:nV.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(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Zo(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.manifestReceived$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Wd.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Wd.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ve(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(iE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&iV(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(v=>v.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Te(m.url)))}let d=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==f){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(iE(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!F.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(rE(Gd(o,"addtrack"),Gd(o,"removetrack"),Gd(o,"change"),sE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=rE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,sE(["init"])).pipe(tV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}prepare(){var a,n;let e=this.selectManifest();if(rV(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var oE=O(rr(),1),zd=O(yi(),1),uE=O(ot(),1);import{assertNever as oV,assertNonNullable as aE,debounce as uV,ErrorCategory as nE,isHigherOrEqual as lV,isLowerOrEqual as cV,isNonNullable as dV,merge as pV,observableFrom as hV,Subscription as fV,map as mV}from"@vkontakte/videoplayer-shared/es2018";var Va=class{constructor(e){this.subscription=new fV;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new Xe;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?L(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return oV(e)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),(0,oE.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,zd.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:nE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ve(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(mV(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Be(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),a(Je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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&&dV(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=pV(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,hV(["init"])).pipe(uV(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),Ce(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;aE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];aE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ei(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:nE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let f=St(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,zd.default)(this.trackUrls).map(d=>d.track);if(!r||!a||br(e,n[0].quality,(c=(0,uE.default)(n,-1))==null?void 0:c.quality)){i();return}let o=e.max?cV(r,e.max):!0,u=e.min?lV(r,e.min):!0;o&&u||i(e)}};import{assertNever as cE,debounce as SV,merge as dE,observableFrom as yV,Subscription as TV,map as pE,ValueSubject as IV,ErrorCategory as Kd,VideoQuality as EV}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as bV}from"@vkontakte/videoplayer-shared/es2018";var lE=["stun:videostun.mycdn.me:80"],gV=1e3,vV=3,Yd=()=>null,ru=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=Yd;this.externalStopCallback=Yd;this.externalErrorCallback=Yd;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:lE}]};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:bV.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),gV)}normalizeOptions(e={}){let t={stunServerList:lE,maxRetryNumber:vV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var _a=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new IV(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return cE(e)}};this.subscription=new TV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=De(e.container,e.tuning),this.liveStreamClient=new ru(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),Ce(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Kd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(dE(this.videoState.stateChangeStarted$.pipe(pE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(pE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Ve(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Je(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(Be(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 cE(n.to)}},i)).add(dE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,yV(["init"])).pipe(SV(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(Te(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:EV.INVARIANT}),this.video.srcObject=e,L(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Kd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){_e(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Kd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var jr=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 Fa,assertNonNullable as ai,ErrorCategory as su,filter as vE,isNonNullable as SE,isNullable as LV,map as $V,merge as MV,once as DV,Subject as ce,Subscription as yE,ValueSubject as q,flattenObject as Xd}from"@vkontakte/videoplayer-shared/es2018";import{Observable as xV,map as hE,Subscription as wV,Subject as AV}from"@vkontakte/videoplayer-shared/es2018";var fE=s=>new xV(e=>{let t=new wV,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(hE(({from:l,to:c})=>`${l}-${c}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(hE(({type:l})=>l!==void 0)),n=new AV,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as PV,Subscription as RV,combine as kV,filter as bE,once as gE}from"@vkontakte/videoplayer-shared/es2018";function mE(){return new(window.AudioContext||window.webkitAudioContext)}var Oa=class Oa{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Z;this.subscriptions=new RV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(bE(a=>!!a.type),gE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){F.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(kV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(bE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),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=mE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Oa.errorId,category:PV.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Oa.errorId} exception`,thrown:e})}};Oa.errorId="VolumeMultiplierManager";var Qr=Oa;var CV={chunkDuration:5e3,maxParallelRequests:5},Na=class{constructor(e){this.current$=new q({type:void 0});this.providerError$=new ce;this.noAvailableProvidersError$=new ce;this.volumeMultiplierError$=new ce;this.providerOutput={position$:new q(0),duration$:new q(1/0),volume$:new q({muted:!1,volume:1}),availableVideoStreams$:new q([]),currentVideoStream$:new q(void 0),availableVideoTracks$:new q([]),currentVideoTrack$:new q(void 0),availableVideoCodecs$:new q([]),availableAudioStreams$:new q([]),currentAudioStream$:new q(void 0),availableAudioTracks$:new q([]),availableAudioCodecs$:new q([]),currentVideoSegmentLength$:new q(0),currentAudioSegmentLength$:new q(0),isAudioAvailable$:new q(!0),autoVideoTrackLimitingAvailable$:new q(!1),autoVideoTrackLimits$:new q(void 0),currentBuffer$:new q(void 0),isBuffering$:new q(!0),error$:new ce,fetcherError$:new ce,fetcherRecoverableError$:new ce,warning$:new ce,willSeekEvent$:new ce,soundProhibitedEvent$:new ce,seekedEvent$:new ce,loopedEvent$:new ce,endedEvent$:new ce,manifestRequested$:new ce,manifestReceived$:new ce,firstBytesRequested$:new ce,firstBytesReceived$:new ce,firstBytesEvent$:new ce,loadedMetadataEvent$:new ce,firstFrameEvent$:new ce,canplay$:new ce,isLive$:new q(void 0),isLiveEnded$:new q(null),canPlayLiveTailBuffer$:new q(!1),isLowLatency$:new q(!1),canChangePlaybackSpeed$:new q(!0),liveTime$:new q(void 0),liveBufferTime$:new q(void 0),liveLatency$:new q(void 0),severeStallOccurred$:new ce,availableTextTracks$:new q([]),currentTextTrack$:new q(void 0),hostname$:new q(void 0),httpConnectionType$:new q(void 0),httpConnectionReused$:new q(void 0),inPiP$:new q(!1),inFullscreen$:new q(!1),element$:new q(void 0),elementVisible$:new q(!0),availableSources$:new q(void 0),is3DVideo$:new q(!1),playbackState$:new q(""),getCurrentTime$:new q(null)};this.subscription=new yE;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=dc([...cI(this.params.tuning),...lI(this.params.tuning)]).filter(l=>SE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Jd.default)(r,l)),...t.filter(l=>(0,Jd.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Xd(a)),this.screenFormatsIterator=new jr(a);let n=[...sd(!0),...sd(!1)];this.chromecastFormatsIterator=new jr(n.filter(l=>SE(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(){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 jr(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(LV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:su.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Fa(e)}}createScreenProvider(e){var u,l;let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let c=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ai(c),this.params.tuning.useNewDashProvider?new Ma({...o,source:c,sourceHls:d,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):new Ia({...o,source:c,sourceHls:d,forceVideoCodec:(l=this.videoCodecsIterator)==null?void 0:l.getValue()})}case"DASH_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return ai(c),this.params.tuning.useNewDashProvider?new Da({...o,source:c}):new Ea({...o,source:c})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let c=this.applyFailoverHost(t[e]);return ai(c),new Ba({...o,source:c})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return ai(c),new Ca({...o,source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let c=this.applyFailoverHost(t[e]);return ai(c),new Va({...o,source:c})}case"DASH_LIVE":{let c=this.applyFailoverHost(t[e]);return ai(c),new iy({...o,source:c,config:{...CV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let c=this.applyFailoverHost(t[e]);return ai(c),new _a({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 Fa(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ai(o),new xs({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Fa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Fa(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 Fa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,IE.default)((0,TE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new yE,t=!1,i=0;return e.add(MV(this.providerOutput.error$.pipe(vE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),fE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe($V(r=>({id:`ProviderHangup:${r}`,category:su.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(vE(({to:a})=>a==="playing"),DV()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===su.NETWORK,u=r.category===su.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,f=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:f,canReinitProvider:c},c?(i++,this.reinitProvider()):f?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Xd(n)):this.tracer.error("providerError",Xd(n))})),e}};import{fromEvent as au,once as BV,combine as VV,Subscription as EE,ValueSubject as Zd,map as _V,filter as OV,isNonNullable as nu,now as ze,safeStorage as ep}from"@vkontakte/videoplayer-shared/es2018";var FV=5e3,xE="one_video_throughput",wE="one_video_rtt",Vt=window.navigator.connection,AE=()=>{let s=Vt==null?void 0:Vt.downlink;if(nu(s)&&s!==10)return s*1e3},PE=()=>{let s=Vt==null?void 0:Vt.rtt;if(nu(s)&&s!==3e3)return s},RE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},tp=class s{constructor(e){this.subscription=new EE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(xE)||(e.useBrowserEstimation?AE():void 0)||FV,i=(a=(r=s.load(wE))!=null?r:e.useBrowserEstimation?PE():void 0)!=null?a:0;if(this.throughput$=new Zd(t),this.rtt$=new Zd(i),this.rttAdjustedThroughput$=new Zd(RE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ct.getSmoothedValue(t,-1,e),this.rtt=Ct.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=AE();u&&this.throughput.next(u);let l=PE();nu(l)&&this.rtt.next(l)};Vt&&"onchange"in Vt&&this.subscription.add(au(Vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ep.set(xE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ep.set(wE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(VV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_V(({throughput:n,rtt:o})=>RE(n,o,e.rttPenaltyRequestSize)),OV(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=ze(),r=new EE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(au(e,"progress").pipe(BV()).subscribe(a=>{t=a.loaded,i=ze()}));break;case 1:case 0:r.add(au(e,"loadstart").subscribe(()=>{t=0,i=ze()}));break}r.add(au(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=ze(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=ze(),n=0,o=ze(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,ze()-a,1),this.concurrentDownloads.delete(e);else if(d){if(t){let f=ze();if(f-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||f-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let h=o-a;h&&this.addRawSpeed(n,h,1,t),n=d.byteLength,a=ze()}else n+=d.byteLength;o=ze()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ze()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ze()-o,this.concurrentDownloads.size),n=0,o=ze());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(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=ep.get(e);if(nu(t))return(i=parseInt(t,10))!=null?i:void 0}},kE=tp;import{fillWithDefault as NV,VideoQuality as ou}from"@vkontakte/videoplayer-shared/es2018";var LE={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:ou.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:ou.Q_720P,trafficSavingLimit:ou.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ou.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},$E=s=>{var e;return{...NV(s,LE),configName:[...(e=s.configName)!=null?e:[],...LE.configName]}};import{assertNonNullable as uu,combine as _t,ErrorCategory as lu,filter as U,filterChanged as Y,fromEvent as rp,isNonNullable as BE,isNullable as GV,Logger as zV,map as G,mapTo as VE,merge as ni,now as cu,once as j,Subject as W,Subscription as _E,tap as sp,ValueSubject as C,isHigher as YV,isInvariantQuality as OE,flattenObject as oi,throttle as ap,getTraceSubscriptionMethod as FE,TracerFactory as KV,InternalsExposure as XV}from"@vkontakte/videoplayer-shared/es2018";import{merge as qV,map as UV,filter as ME,isNonNullable as HV}from"@vkontakte/videoplayer-shared/es2018";var ip=({seekState:s,position$:e})=>qV(s.stateChangeEnded$.pipe(UV(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),ME(HV)),e.pipe(ME(()=>s.getState().state==="none")));import{assertNonNullable as jV}from"@vkontakte/videoplayer-shared/es2018";var DE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return jV(e,`Wrong container or containerId {${s.container}}`),e};import{filter as QV,once as WV}from"@vkontakte/videoplayer-shared/es2018";var CE=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(QV(r=>r.length>0),WV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var du=class{constructor(e={configName:[]},t=KV.createRootTracer(!1)){this.subscription=new _E;this.logger=new zV;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 H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),videoStream:new H(void 0),audioStream:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),isLowLatency:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({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}),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 W,ready$:new W,started$:new W,playing$:new W,paused$:new W,stopped$:new W,willReady$:new W,willStart$:new W,willResume$:new W,willPause$:new W,willStop$:new W,willDestruct$:new W,watchCoverageRecord$:new W,watchCoverageLive$:new W,managedError$:new W,fatalError$:new W,fetcherRecoverableError$:new W,ended$:new W,looped$:new W,seeked$:new W,willSeek$:new W,autoplaySoundProhibited$:new W,manifestRequested$:new W,manifestReceived$:new W,firstBytesRequested$:new W,firstBytesReceived$:new W,firstBytes$:new W,loadedMetadata$:new W,firstFrame$:new W,canplay$:new W,log$:new W,fetcherError$:new W,severeStallOccured$:new W};this.experimental={element$:new C(void 0),tuningConfigName$:new C([]),enableDebugTelemetry$:new C(!1),dumpTelemetry:RS,getCurrentTime$:new C(null)};if(this.initLogs(),this.tuning=$E(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,np.default)(this.info).forEach(i=>i.setSuppressErrors(!0)),(0,np.default)(this.events).forEach(i=>i.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new dn({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new kE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new XV("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(f=>JSON.stringify(f,(p,h)=>{let m=typeof h;return(0,NE.default)(["number","string","boolean"],m)?h:h===null?null:`<${m}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:lu.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",oi(o)),this.domContainer=DE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Na({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?F.isInited$.pipe(U(n=>!!n),j()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),rp(document,"visibilitychange").pipe(j()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),j()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),j()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),j()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),j()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{uu(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(U(i=>i.length>0),j()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",oi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{var i;uu(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",oi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{var t;CE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),j()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),j()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),j()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(U(e=>e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),j()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(GV(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return BE(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(ni(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(xc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(U(({from:e})=>e==="stopped"),j()).subscribe(()=>{this.initedAt=cu(),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",oi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:lu.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(j()).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",oi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(_t({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>OE(u)?1:OE(l)?-1:YV(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(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(U(n=>BE(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(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).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(G(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(sp(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(_t({hasLiveOffsetByPaused:ni(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),Y(),G(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(_t({atLiveEdge:_t({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ip({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Y(),sp(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(_t({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Y(),sp(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),Y()).subscribe(this.info.volume$)).add(ip({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ni(e.providerOutput.endedEvent$.pipe(VE(!0)),e.providerOutput.seekedEvent$.pipe(VE(!1))).pipe(Y()).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(G(n=>({id:n?`No${n}`:"NoProviders",category:lu.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(j()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(j()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(j()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(j()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(j(),G(n=>n!=null?n:cu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(j(),G(()=>cu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(j(),G(()=>cu()-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(U(({to:n})=>n==="playing"),j()).subscribe(()=>i.next(!1)));let r=0,a=ni(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),Y());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ni(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(ni(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(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 _E;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(U(i=>i.length>0),j()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=St(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(ni(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(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;uu(this.providerContainer),uu(e),PS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>AS(i)),this.providerContainer.current$.subscribe(({type:i})=>Rs("provider",i)),e.duration$.subscribe(i=>Rs("duration",i)),e.availableVideoTracks$.pipe(U(i=>!!i.length),j()).subscribe(i=>Rs("tracks",i)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),e.position$.subscribe(new ke("position")),e.currentVideoTrack$.pipe(G(i=>i==null?void 0:i.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),e.isBuffering$.subscribe(new ke("isBuffering"))].forEach(i=>this.subscription.add(i)),Rs("codecs",F.video.supportedCodecs)}initTracerSubscription(){let e=FE(this.tracer.log.bind(this.tracer)),t=FE(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(Y()).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(_t({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(U(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(U(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(U(i=>i>0),Y()).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(_t({currentBuffer:this.info.currentBuffer$.pipe(U(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(ap(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(_t({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(U(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),ap(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),U(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),U(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),U(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(_t({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(U(({throughputEstimation:i,rtt:r})=>!!i&&!!r),ap(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),U(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:lu.DOM,message:String(r)})})};this.subscription.add(ni(rp(document,"visibilitychange"),rp(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",oi({quality:t,availableTracks:oi(e),track:oi(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&&!Bs()}};import{Subscription as yJ,Observable as TJ,Subject as IJ,ValueSubject as EJ,VideoQuality as xJ}from"@vkontakte/videoplayer-shared/es2018";var wJ=`@vkontakte/videoplayer-core@${Wp}`;export{en as ChromecastState,gu as HttpConnectionType,TJ as Observable,$e as PlaybackState,du as Player,tn as PredefinedQualityLimits,wJ as SDK_VERSION,IJ as Subject,yJ as Subscription,vu as Surface,Wp as VERSION,EJ as ValueSubject,At as VideoFormat,xJ as VideoQuality,z$ as areValidLiveRecordSources,F as clientChecker,Es as isMobile};
|
|
178
|
+
`;var Or=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 Uo(this.params.fov,this.params.orientation),this.cameraRotationManager=new jo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(SI,this.gl.VERTEX_SHADER),i=this.createShader(vI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,f=t+r;return[a,n,o,u,l,c,d,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as qB,now as Ea,once as UB,Subscription as jB,ValueSubject as md,isNonNullable as HB,safeStorage as bd,filterChanged as QB}from"@vkontakte/videoplayer-shared/es2018";var Ho="stalls_manager_metrics",gd="stalls_manager_abr_params",yI="stalls_manager_default_tuning_abr_params",Sd=class{constructor(){this.isSeeked$=new md(!1);this.isBuffering$=new md(!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 jB;this.severeStallOccurred$=new md(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(gd):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Ea(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Ea()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(yI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(gd),this.setStoredData(yI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ho,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(Ho,[]),this.setStoredData(gd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>a&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){var i;return JSON.parse((i=bd.get(e))!=null?i:t)}setStoredData(e,t){bd.set(e,JSON.stringify(t))}removeStoredData(e){bd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ho,"[]"),r=t/e,a=i.length?Dt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ho,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(UB()).subscribe(t=>this.providerStartWatchingTimestamp=Ea())),this.subscription.add(this.currentStallDuration$.pipe(QB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(qB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Ea(),d=r&&this.currentStallsCount>=r,f=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,HB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Ea()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},Qo=Sd;import{combine as WB,map as GB,observeElementSize as zB,Subscription as YB,ValueSubject as vd,noop as KB}from"@vkontakte/videoplayer-shared/es2018";var Wo=class{constructor(){this.subscription=new YB;this.pipSize$=new vd(void 0);this.videoSize$=new vd(void 0);this.elementSize$=new vd(void 0);this.pictureInPictureWindowRemoveEventListener=KB}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(zB(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(WB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(GB(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Fi=class{constructor(e){this.subscription=new s0;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new Er;this.stallsManager=new Qo;this.elementSizeManager=new Wo;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.unmuteAfterBrowserResetsHappened=new n0(!1);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(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"),$(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&$(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"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return JB(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Or(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new 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(Te(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 qo({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;r0(this.observableVideo)&&(this.observableVideo=_e(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:TI.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(xa(d=>!!d.length),zo()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Fr(d=>d.to.state!=="none"),wa());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(xa(II),zo()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Fr(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(we(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(t.volume.stateChangeStarted$.pipe(Fr(()=>{let d=t.volume.getTransition(),f=this.params.output.element$.getValue();return!f||!d?!1:!d.to.muted&&f.muted}),xa(d=>!!d),zo()).subscribe(()=>{this.unmuteAfterBrowserResetsHappened.next(!0)})),this.subscription.add(we(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.playbackRateState$.pipe(xa(()=>this.unmuteAfterBrowserResetsHappened.getValue()),zo()).subscribe(()=>{let d=this.params.output.element$.getValue(),f=t.playbackRate.getState();d&&f!==d.playbackRate&&(d.playbackRate=f)})),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(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"),$(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams(),p=this.player.getCodecs();if(ZB(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of f.audio){m.push(td(g));let b=[];for(let v of g.representations){let T=iI(v);b.push(T),this.audioTracksMap.set(T,{stream:g,representation:v})}this.audioStreamsMap.set(g,b)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of f.video){h.push(id(m));let g=[];for(let b of m.representations){let v=fa({...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(h);for(let m of f.text)for(let g of m.representations){let b=rI(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),p!=null&&p.video&&this.params.output.availableVideoCodecs$.next(p.video),p!=null&&p.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=Aa(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$,i0(this.video,"progress")).pipe(xa(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(a0(u))),this.subscription.add(o.subscribe(async()=>{let d=this.player.state$.getState(),f=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||f)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,g=[...this.videoTracksMap.keys()].find(v=>{var T;return((T=this.videoTracksMap.get(v))==null?void 0:T.representation.id)===h.id});II(g)&&(this.stallsManager.lastVideoTrackSelected=g);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")await this.player.initRepresentations(h.id,m==null?void 0:m.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add(e0({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Aa(Go([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Fr(d=>d.to)))}).pipe(Fr(({videoState:d,autoVideoTrackState:f})=>d.to!=="stopped"&&f),wa()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(wa()).subscribe(d=>{let f=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(id(h));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(wa()).subscribe(d=>{let f=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===d);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(td(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var f,p;if(d!=null&&d.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Fr(({to:d})=>d==="ready"),wa());this.subscription.add(Aa(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Go(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Aa(l,this.player.state$.stateChangeEnded$,Go(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Aa(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Go(["init"])).pipe(t0(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var M,R,P,V,D,_,X,Z,E,k,w,A,B;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?$s:Ls,t=this.params.tuning.useNewAutoSelectVideoTrack?fo:ho,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:po,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(M=r.videoTrack.getState())==null?void 0:M.id,u=[...this.videoTracksMap.keys()].find(({id:G})=>G===o),l=a.currentVideoTrack$.getValue(),c=((V=(P=r.videoStream.getState())!=null?P:u&&((R=this.videoTracksMap.get(u))==null?void 0:R.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=[...this.videoStreamsMap.keys()].find(({id:G})=>G===c.id),f=d&&this.videoStreamsMap.get(d);if(!f)return;let p=Ie(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(h,m||1/0),1),b=(D=r.audioStream.getState())!=null?D:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(_=[...this.audioStreamsMap.keys()].find(({id:G})=>G===(b==null?void 0:b.id)))!=null?_:this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let G=e(u,f,(X=this.audioStreamsMap.get(v))!=null?X:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(Z=G==null?void 0:G.bitrate)!=null?Z:-1/0)}if(l){let G=e(l,f,(E=this.audioStreamsMap.get(v))!=null?E:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(k=G==null?void 0:G.bitrate)!=null?k:-1/0)}}let y=u;(n||!y)&&(y=i(f,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve: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 I=v&&t(y,f,(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}),x=(A=this.videoTracksMap.get(y))==null?void 0:A.representation,L=I&&((B=this.audioTracksMap.get(I))==null?void 0:B.representation);if(x&&L)return[x,L];if(x&&!L&&this.audioTracksMap.size===0)return[x,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:TI.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 Ra=class extends Fi{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 yd,merge as EI,filter as xI,filterChanged as wI,isNullable as Td,map as AI,ValueSubject as Id,isNonNullable as o0}from"@vkontakte/videoplayer-shared/es2018";var Pa=class extends Fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Id(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(wI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(AI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(yd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(AI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(xI(u=>o0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(yd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:EI(r.playbackRateState$,new Id(1))}).pipe(xI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||Td(c)||(t=u-c)})).add(yd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:EI(r.playbackRateState$,new Id(1))}).pipe(wI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||Td(u)||Td(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=sI(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)})}};import{assertNever as C0,assertNonNullable as B0,combine as V0,debounce as _0,ErrorCategory as jI,filter as Od,filterChanged as Oa,fromEvent as O0,isNonNullable as HI,isNullable as F0,map as Fa,merge as Na,observableFrom as au,once as QI,Subscription as N0}from"@vkontakte/videoplayer-shared/es2018";var UI=O(Ce(),1),Vd=O(Fs(),1);import{abortable as Md,assertNonNullable as Ur,combine as jr,ErrorCategory as lt,filter as iu,filterChanged as Ba,flattenObject as Va,fromEvent as Et,getTraceSubscriptionMethod as x0,interval as Dd,isNonNullable as _a,isNullable as NI,map as Hr,merge as Hi,now as Cd,Subject as ni,Subscription as Bd,tap as w0,throttle as qI,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var Jo=O(Ce(),1),ji=O(at(),1),Zo=O(Fs(),1);var VI=O(Qn(),1);import{assertNever as u0,ErrorCategory as RI,Subject as PI}from"@vkontakte/videoplayer-shared/es2018";var l0=18,kI=!1;try{kI=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=l0}catch(s){console.error(s)}var Ed=class{constructor(e){this.bufferFull$=new PI;this.error$=new PI;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:RI.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};kI&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:RI.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:u0(t)}}},LI=Ed;import{abortable as si,assertNonNullable as $e,ErrorCategory as qi,fromEvent as Pd,getExponentialDelay as kd,isHigher as f0,isNonNullable as ai,isNullable as he,now as Xo,once as m0,Subject as b0,Subscription as g0,ValueSubject as Ui}from"@vkontakte/videoplayer-shared/es2018";var xd=O(at(),1);import{videoSizeToQuality as c0,throttleFn as d0}from"@vkontakte/videoplayer-shared/es2018";var ka=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Kt(a):void 0)!=null?u:c0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},$I=({id:s,bitrate:e})=>({id:s,bitrate:e}),MI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),DI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),wd=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,xd.default)(i.split("."),0),isDefault:r}),Ad=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,xd.default)(r.split("."),0)}),Rd=s=>"url"in s,Qe=s=>s.type==="template";var CI=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},Ni=(s,e)=>{for(let t of s)if(e(t))return t;return null},BI=s=>{let e=!1,t=d0(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as p0,Subscription as h0}from"@vkontakte/videoplayer-shared/es2018";var Yo=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var Ko=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new h0;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(p0(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!N(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Yo(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var La=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ui(0);this.currentLowLatencySegmentLength$=new Ui(0);this.currentSegmentLength$=new Ui(0);this.onLastSegment$=new Ui(!1);this.fullyBuffered$=new Ui(!1);this.playingRepresentation$=new Ui(void 0);this.playingRepresentationInit$=new Ui(void 0);this.error$=new b0;this.gaps=[];this.subscription=new g0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ee;this.switchAbortController=new ee;this.destroyAbortController=new ee;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=si(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);$e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new LI(this.sourceBuffer),this.sourceBufferBufferedDiff=new Ko(this.mediaSource,this.sourceBuffer),this.subscription.add(Pd(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Pd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:qi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ie(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);$e(i,"No init buffer for starting representation"),$e(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=si(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);$e(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),$e(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();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=si(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);$e(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),$e(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();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=si(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Zo.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!Qe(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);$e(r);let a=this.segments.get(i);$e(a,"No segments for starting representation");let n=this.initData.get(i);if($e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ee,si(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);$e(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(he(o)||he(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),$e(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(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(){!he(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 ee,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var f;if(he(e)||he(this.downloadingRepresentationId)||he(this.playingRepresentationId)||he(this.sourceBuffer)||!N(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),a=this.segments.get(this.playingRepresentationId);if($e(t,`No such representation ${this.downloadingRepresentationId}`),$e(i,`No such representation ${this.playingRepresentationId}`),he(r)||he(a))return;let n=r.find(p=>e>=p.time.from&&e<p.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 p=this.getForwardBufferDuration(e),h=ka(i),m=ka(t),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&ai(h)&&ai(m)&&f0(h.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(g||b?o+=Math.min(p,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(f=[...this.segments.entries()].map(([y,I])=>{let x=I.find(L=>e>=L.time.from&&e<L.time.to);return{representationId:y,status:x==null?void 0:x.status}}).find(y=>y.status==="fed"))==null?void 0:f.representationId;if(!T)return;this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))}}if(isFinite(this.bufferLimit)&&Ar(this.sourceBuffer.buffered)>=this.bufferLimit){let p=Ie(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let c=null;if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(r,t.segmentReference.type,o),c!=null&&c.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Jo.default)(c,n))p="high";else{let h=(0,ji.default)(c,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(c,t,p).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!(c!=null&&c.length)&&Ie(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,ji.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-Ie(this.sourceBuffer.buffered,e)<u),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;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=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Zo.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,Zo.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Qe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(a=(0,ji.default)(c,-1))==null?void 0:a.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;$e(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(!Qe(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=ot(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,b=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+v||r<v&&h-p>=v||h<=i+v;return(f==="none"||f==="partially_ejected"&&b&&T&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ee(this.sourceBuffer.buffered,p)&&Ee(this.sourceBuffer.buffered,h)))&&b&&T});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=a;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}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:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await si(o,async function*(){let c=kd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Xo(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())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:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await si(n,async function*(){let u=kd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Pd(window,"online").pipe(m0()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Xo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(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,ji.default)(e,0).byte.from,to:(0,ji.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Xo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:qi.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:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Xo();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:qi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Jo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,c=l.byte.from-i,d=l.byte.to-i,f=d-c+1,p=c<r,h=d<=r;if(p){if(l.status==="downloading"&&h){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(m,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-c),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===f?m:Tt(o.mime).parseFeedableSegmentChunk(m);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(he(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ee(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ee(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:qi.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",Rd(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=wr(()=>(0,VI.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?si(this.destroyAbortController.signal,async function*(){let o=kd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&Qe(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:qi.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||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||he(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push({...o.time});let u=Rd(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let f of d)(0,Jo.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let d={time:{from:u,to:l},url:"",status:"none"};n(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=CI(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||!N(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||!N(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||!N(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||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||he(e)?0:Ie(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let a=Math.round(r.from),n=Math.round(r.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=wr(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:qi.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(he(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||he(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Yo(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let c=0;c<e.length;c+=2){let d=e[c],f=e[c+1];u||(u=d-t<=n&&f+t>=o),(n>=d&&n<f-t||o>d+t&&o<=f)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:qi.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,ji.default)(e,-1))==null?void 0:t.time.to:0)||0}};import{abortable as $a,assertNever as _I,fromEvent as OI,merge as S0,now as Ma,Subject as Nr,ValueSubject as Ld,flattenObject as qr,ErrorCategory as Da,SubscriptionRemovable as v0}from"@vkontakte/videoplayer-shared/es2018";var tu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new Nr;this.manifestReceived=new Nr;this.firstBytesRequested=new Nr;this.firstBytesReceived=new Nr;this.lastConnectionType$=new Ld(void 0);this.lastConnectionReused$=new Ld(void 0);this.lastRequestFirstBytes$=new Ld(void 0);this.recoverableError$=new Nr;this.error$=new Nr;this.abortAllController=new ee;this.subscription=new v0;this.fetchManifest=$a(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ti(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Po(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(eu);return r?(t.log("success",qr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",qr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=$a(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var _,X,Z;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(c,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),c=E.toString();break}default:_I(t)}this.requestQuic&&(c=ti(c));let p=this.abortAllController.signal,h;if(n){let E=new ee;if(h=S0(OI(this.abortAllController.signal,"abort"),OI(n,"abort")).subscribe(()=>{try{E.abort()}catch(k){eu(k)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(k){eu(k)}p=E.signal}let m=0,g=Ma();f.log("startRequest",qr({url:c,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested.next();let b=yield this.doFetch(c,{priority:a,headers:d,signal:p}),v=Ma();if(!b)return f.error("error",{message:"No response in request"}),f.end(),this.unsubscribeAbortSubscription(h),null;if((_=this.throughputEstimator)==null||_.addRawRtt(v-g),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let E=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:E}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let E=Ma(),k={requestStartedAt:g,requestEndedAt:E,duration:E-g};return f.log("endRequest",qr(k)),f.end(),b.arrayBuffer()}let T=b.body;if(o){let E;[T,E]=b.body.tee(),(X=this.throughputEstimator)==null||X.trackStream(E,u)}let y=T.getReader(),I,x=parseInt((Z=b.headers.get("content-length"))!=null?Z:"",10);Number.isFinite(x)&&(I=x),!I&&i&&(I=i.to-i.from+1);let L=I?new Uint8Array(I):new Uint8Array(0),M=!1,R=E=>{this.unsubscribeAbortSubscription(h),M=!0,eu(E)},P=$a(p,async function*({done:E,value:k}){if(m===0&&(this.lastRequestFirstBytes$.next(Ma()-g),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!E&&k){if(l&&I)L.set(k,m),m+=k.byteLength;else{let w=new Uint8Array(L.length+k.length);w.set(L),w.set(k,L.length),L=w,m+=k.byteLength}r==null||r(new DataView(L.buffer),m),yield y==null?void 0:y.read().then(P,R)}}.bind(this));yield y==null?void 0:y.read().then(P,R),this.unsubscribeAbortSubscription(h);let V=Ma(),D={failed:M,requestStartedAt:g,requestEndedAt:V,duration:V-g};return M?(f.error("endRequest",qr(D)),f.end(),null):(f.log("endRequest",qr(D)),f.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=$a(this.abortAllController.signal,async function*(e,t,i){var b;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(c,a))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,a-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(b=e.indexRange)!=null?b:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let v=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=$a(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Ro(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:_I(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(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Da.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Da.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Da.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Da.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Da.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},eu=s=>{if(!It(s))throw s};import{isNullable as y0,ValueSubject as T0}from"@vkontakte/videoplayer-shared/es2018";var Ca=class s{constructor(e,t){this.currentRepresentation$=new T0(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(!y0(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Qe(t.segmentReference))}};var A0=["progress","play","seeked","stalled","waiting"],R0=["timeupdate","progress","loadeddata","playing","seeked"];var ru=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Bd;this.representationSubscription=new Bd;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 ni;this.manifestRequested=new ni;this.manifestReceived=new ni;this.firstBytesRequested=new ni;this.firstBytesReceived=new ni;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 ni;this.fetcherError$=new ni;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ni;this.gapWatchdogActive=!1;this.destroyController=new ee;this.initManifest=Md(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ue(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:lt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Md(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:lt.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=Eo(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=To(e))!=null?u:{id:"ManifestParsing",category:lt.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let i=(c,d,f)=>{var p,h,m,g;return!!((h=(p=this.element)==null?void 0:p.canPlayType)!=null&&h.call(p,d)&&((g=(m=je())==null?void 0:m.isTypeSupported)!=null&&g.call(m,`${d}; codecs="${f}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:f,streamIsAlive:p}=t.live,h=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";p||(m=f?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let c of["video","audio"]){let f=t.streams[c].filter(({mime:h,codecs:m})=>i(c,h,m));r[c]=f;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let h=f.map(({codecs:m})=>m);c==="audio"&&(n=Fo(h),p=n[0]),c==="video"&&(a=Oo(h),this.forceVideoCodec&&(0,UI.default)(a,this.forceVideoCodec)?p=this.forceVideoCodec:p=a[0]),p&&(r[c]=f.filter(({codecs:m})=>Cr(m)===p))}else{let h=new Set(f.map(({codecs:m})=>m));p=_o(h),p&&(r[c]=f.filter(({codecs:m})=>m.startsWith(p)))}if(c==="video"){let h=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),g=r.video.some(b=>!b.hdr);F.display.isHDR&&h&&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:a,audio:n}),this.tracer.log("updateManifestEnd",Va(o)),o}.bind(this));this.initRepresentations=Md(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",Va({initialVideo:e,initialAudio:t,sourceHls:i})),Ur(this.manifest),Ur(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Bd,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Et(p,"error").pipe(iu(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Kn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),br())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 La("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],_a(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new La("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ca.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ca(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Hi(...R0.map(p=>Et(this.element,p))).pipe(Hr(p=>this.element?Ie(this.element.buffered,this.element.currentTime*1e3):0),Ba(),w0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Hi(Et(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ba()).subscribe(h=>this.liveStreamEndTimestamp=Cd())),this.subscription.add(Et(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Dd(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=ue(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Et(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(jr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Hr(({isActiveLive:h,isLowLatency:m})=>h&&m),Ba()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Dr(this.element,1)})),this.representationSubscription.add(jr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(iu(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!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(jr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(iu(({isLive:h})=>h),Ba((h,m)=>m.bufferLength<h.bufferLength),Hr(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let b=zt(this.manifestUrlString,2);return(h/2+m+g+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(jr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,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=h-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(y)>v&&(I=1+Math.sign(y)*T),Dr(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,b;let m=0;if(h){let v=((b=(g=this.element)==null?void 0:g.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var I,x;return(x=(I=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?x:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(jr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(qI(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,b=zt(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,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,x=isFinite(h)?h:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),M=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(M);let R="none";if(L?R="active_low_latency":this.isLowLatency$.getValue()&&M?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),R="active_low_latency"):b!==0&&x<T?R="live_forward_buffering":x<T+I&&(R="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),R==="live_forward_buffering"||R==="live_with_target_offset"){let P=p-(T+y),V=this.normolizeLiveOffset(Math.trunc(b+P/g)),D=Math.abs(V-b),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=b:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=ue(this.manifestUrlString,_,2)}(R==="live_with_target_offset"||R==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:lt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Hi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Hr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Hi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Hr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=jr({allBuffersFull:l,someBufferEnded:c}).pipe(Ba(),Hr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),iu(p=>p));if(this.representationSubscription.add(Hi(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:lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Hi(...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 g;if(((g=this.source)==null?void 0:g.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:lt.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=[(f=this.manifest.duration)!=null?f:0,...(0,Vd.default)((0,Vd.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&&_a(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Dd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:lt.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 tu({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.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,a,n;Ur(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Cd()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ue(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((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Ur(this.element),this.state$.setState("running");let e=Et(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(qI(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Hi(...A0.map(t=>Et(this.element,t)),Et(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:lt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Et(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(Et(this.element,"waiting").subscribe(()=>{var i;this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ee(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,m,g,b,v,T,y,I,x,L,M;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=Cd(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(v=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?v:0,c=(y=(T=this.videoBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?y:0,d=(x=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?x:0,f=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let R=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(R).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:lt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),a.liveLastOffset=R}else{let R=this.element.currentTime*1e3;(L=this.videoBufferManager)==null||L.maintain(R),(M=this.audioBufferManager)==null||M.maintain(R),a.position=R}this.tracer.log("stallIntervalCallback",Va(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=Dd(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:lt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;Ur(this.element),Ur(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ee(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(NI(this.element)||NI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Va({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;_a(this.element)&&_a(this.source)&&_a(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=x0(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 a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",Va({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 P0,map as k0,observeElementSize as L0,Subscription as $0,ValueSubject as _d,noop as M0}from"@vkontakte/videoplayer-shared/es2018";var su=class{constructor(){this.subscription=new $0;this.pipSize$=new _d(void 0);this.videoSize$=new _d(void 0);this.elementSize$=new _d(void 0);this.pictureInPictureWindowRemoveEventListener=M0}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(L0(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(P0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(k0(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Qi=class{constructor(e){this.subscription=new N0;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new Er;this.stallsManager=new Qo;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 Xt;this.audioTrackSwitchHistory=new Xt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(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"),$(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&$(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"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return C0(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Or(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new 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(Te(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 ru({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;F0(this.observableVideo)&&(this.observableVideo=_e(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:jI.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Od(d=>!!d.length),QI()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Fa(d=>d.to.state!=="none"),Oa());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Od(HI),QI()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Fa(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(we(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(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"),$(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams(),p=this.player.getCodecs();if(B0(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of f.audio){m.push(wd(g));let b=[];for(let v of g.representations){let T=$I(v);b.push(T),this.audioTracksMap.set(T,{stream:g,representation:v})}this.audioStreamsMap.set(g,b)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of f.video){h.push(Ad(m));let g=[];for(let b of m.representations){let v=ka({...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(h);for(let m of f.text)for(let g of m.representations){let b=MI(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),p!=null&&p.video&&this.params.output.availableVideoCodecs$.next(p.video),p!=null&&p.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&BI(o)||null;this.subscription.add(Na(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$,O0(this.video,"progress")).pipe(Od(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),f=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||f||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let m=Ni(this.videoTracksMap.keys(),b=>{var v;return((v=this.videoTracksMap.get(b))==null?void 0:v.representation.id)===p.id});HI(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,b)}},r)),this.subscription.add(V0({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Na(au([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Fa(d=>d.to)))}).pipe(Fa(({videoState:d,autoVideoTrackState:f})=>d.to!=="stopped"&&f),Oa()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Oa()).subscribe(d=>{let f=Ni(this.videoTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Ad(h));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Oa()).subscribe(d=>{let f=Ni(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(wd(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var f,p;if(d!=null&&d.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Fa(({to:d})=>d==="ready"),Oa());this.subscription.add(Na(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,au(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Na(l,this.player.state$.stateChangeEnded$,au(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Na(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,au(["init"])).pipe(_0(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var M,R,P,V,D,_,X,Z,E,k,w,A;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?$s:Ls,t=this.params.tuning.useNewAutoSelectVideoTrack?fo:ho,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:po,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(M=r.videoTrack.getState())==null?void 0:M.id,u=Ni(this.videoTracksMap.keys(),B=>B.id===o),l=a.currentVideoTrack$.getValue(),c=((V=(P=r.videoStream.getState())!=null?P:u&&((R=this.videoTracksMap.get(u))==null?void 0:R.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Ni(this.videoStreamsMap.keys(),B=>B.id===c.id),f=d&&this.videoStreamsMap.get(d);if(!f)return;let p=Ie(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(h,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)&&Ni(this.audioStreamsMap.keys(),B=>B.id===b.id)||this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let B=e(u,f,(_=this.audioStreamsMap.get(v))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(X=B==null?void 0:B.bitrate)!=null?X:-1/0)}if(l){let B=e(l,f,(Z=this.audioStreamsMap.get(v))!=null?Z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(E=B==null?void 0:B.bitrate)!=null?E:-1/0)}}let y=u;(n||!y)&&(y=i(f,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve: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 I=v&&t(y,f,(k=this.audioStreamsMap.get(v))!=null?k:[],{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}),x=(w=this.videoTracksMap.get(y))==null?void 0:w.representation,L=I&&((A=this.audioTracksMap.get(I))==null?void 0:A.representation);x&&L?(this.selectedRepresentations.video=x,this.selectedRepresentations.audio=L):x&&!L&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=x,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:jI.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 qa=class extends Qi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Fd,merge as WI,filter as GI,filterChanged as zI,isNullable as Nd,map as YI,ValueSubject as qd,isNonNullable as q0}from"@vkontakte/videoplayer-shared/es2018";var Ua=class extends Qi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new qd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(zI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(YI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Fd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(YI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(GI(u=>q0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Fd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:WI(r.playbackRateState$,new qd(1))}).pipe(GI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||Nd(c)||(t=u-c)})).add(Fd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:WI(r.playbackRateState$,new qd(1))}).pipe(zI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||Nd(u)||Nd(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=DI(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 KI="X-Playback-Duration",Ud=async s=>{var r;let e=await Xe(s),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(KI)?parseInt(e.headers.get(KI),10):void 0};import{assertNever as J0,combine as Z0,debounce as eV,ErrorCategory as uu,filter as tV,filterChanged as iV,isNonNullable as ZI,isNullable as lu,map as eE,merge as rV,observableFrom as sV,Subscription as aV,ValueSubject as Qd,VideoQuality as nV}from"@vkontakte/videoplayer-shared/es2018";var Hd=O(Ll(),1);import{videoSizeToQuality as U0,getExponentialDelay as j0}from"@vkontakte/videoplayer-shared/es2018";var H0=s=>{let e=null;if(s.QUALITY&&(e=Kt(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=U0({width:t,height:i})}return e!=null?e:null},Q0=(s,e)=>{var a,n;let t=s.split(`
|
|
179
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Hd.default)(l[1].split(",").map(v=>v.split("="))),f=(a=d.QUALITY)!=null?a:`stream-${d.BANDWIDTH}`,p=H0(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[v,T]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));v&&T&&(g={width:v,height:T})}let b=new URL(t[++o],e).toString();p&&i.push({id:f,quality:p,url:b,bandwidth:h,size:g,fps:m})}if(c){let d=(0,Hd.default)(c[1].split(",").map(m=>{let g=m.indexOf("=");return[m.substring(0,g),m.substring(g+1)]}).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),f=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,h=d.NAME;f&&p&&r.push({type:"internal",id:p,label:h,language:p,url:f,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},W0=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),jd=0,XI=async(s,e=s,t,i)=>{let a=await(await Xe(s,i)).text();jd+=1;try{let{qualityManifests:n,textTracks:o}=Q0(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(jd<=t.manifestRetryMaxCount)return await W0(j0(jd-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),XI(s,e,t)}return{qualityManifests:[],textTracks:[]}},nu=XI;import{isNonNullable as G0,Subscription as z0,throttle as Y0,ValueSubject as JI,Subject as K0,ErrorCategory as X0}from"@vkontakte/videoplayer-shared/es2018";var ou=class{constructor(e,t,i,r,a){this.subscription=new z0;this.abortControllers={destroy:new ee,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new JI(null);this.getCurrentTime$=new JI(null);this.error$=new K0;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(Y0(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 Xe(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
180
|
+
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+c},url:l}),a=a+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(G0(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 ee;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:X0.WTF,thrown:t,message:e})}};var ja=class{constructor(e){this.subscription=new aV;this.videoState=new j("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Qd([]);this.liveOffset=new Li;this.manifestStartTime$=new Qd(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?$(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),$(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"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&($(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return J0(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:nV.INVARIANT,url:this.params.source.url};let t=(r,a)=>nu(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new ou(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:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:uu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:uu.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(Te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Qd((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:uu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=_e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(we(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ke(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(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(iV(),eE(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&ZI(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Z0({startTime:this.manifestStartTime$.pipe(tV(ZI)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(eE(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=rV(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,sV(["init"])).pipe(eV(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(lu(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[c,"mq"],[d,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ue(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Ud(n).then(c=>{var d;if(!lu(c))this.maxSeekBackTime$.next(c);else{let f=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(lu(f)||!isFinite(f))&&Xe(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();Ud(g).then(b=>{lu(b)||this.maxSeekBackTime$.next(b)})}}).catch(()=>{})}})}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:uu.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=ue(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 oV,debounce as uV,ErrorCategory as Wd,filter as tE,fromEvent as Gd,isNonNullable as lV,isNullable as cV,map as zd,merge as iE,observableFrom as rE,once as sE,Subscription as dV,ValueSubject as aE,VideoQuality as pV}from"@vkontakte/videoplayer-shared/es2018";var Ha=class{constructor(e){this.subscription=new dV;this.videoState=new j("stopped");this.manifests$=new aE([]);this.unmuteAfterBrowserResetsHappened=new aE(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?$(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),$(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"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return oV(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:pV.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(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),nu(ue(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.manifestReceived$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Wd.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Wd.WTF,message:"HlsProvider internal logic error",thrown:o})},r=_e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(zd(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(t.volume.stateChangeStarted$.pipe(zd(()=>{let o=t.volume.getTransition(),u=this.params.output.element$.getValue();return!u||!o?!1:!o.to.muted&&u.muted}),tE(o=>!!o),sE()).subscribe(()=>{this.unmuteAfterBrowserResetsHappened.next(!0)})),this.subscription.add(we(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.playbackRateState$.pipe(tE(()=>this.unmuteAfterBrowserResetsHappened.getValue()),sE()).subscribe(()=>{let o=this.params.output.element$.getValue(),u=t.playbackRate.getState();o&&u!==o.playbackRate&&(o.playbackRate=u)})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&lV(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Te(m.url)))}let d=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==f){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(zd(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!F.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(iE(Gd(o,"addtrack"),Gd(o,"removetrack"),Gd(o,"change"),rE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=iE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,rE(["init"])).pipe(uV(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 a,n;let e=this.selectManifest();if(cV(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var uE=O(nr(),1),Yd=O(Ii(),1),lE=O(at(),1);import{assertNever as hV,assertNonNullable as nE,debounce as fV,ErrorCategory as oE,isHigherOrEqual as mV,isLowerOrEqual as bV,isNonNullable as gV,merge as SV,observableFrom as vV,Subscription as yV,map as TV}from"@vkontakte/videoplayer-shared/es2018";var Qa=class{constructor(e){this.subscription=new yV;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.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?$(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),$(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"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return hV(e)}};this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),(0,uE.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Yd.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:oE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=_e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(TV(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(we(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(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&&gV(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=SV(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,vV(["init"])).pipe(fV(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;nE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];nE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ti(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let f=vt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,Yd.default)(this.trackUrls).map(d=>d.track);if(!r||!a||vr(e,n[0].quality,(c=(0,lE.default)(n,-1))==null?void 0:c.quality)){i();return}let o=e.max?bV(r,e.max):!0,u=e.min?mV(r,e.min):!0;o&&u||i(e)}};import{assertNever as dE,debounce as wV,merge as pE,observableFrom as AV,Subscription as RV,map as hE,ValueSubject as PV,ErrorCategory as Xd,VideoQuality as kV}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as IV}from"@vkontakte/videoplayer-shared/es2018";var cE=["stun:videostun.mycdn.me:80"],EV=1e3,xV=3,Kd=()=>null,cu=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=Kd;this.externalStopCallback=Kd;this.externalErrorCallback=Kd;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:cE}]};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:IV.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),EV)}normalizeOptions(e={}){let t={stunServerList:cE,maxRetryNumber:xV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Wa=class{constructor(e){this.videoState=new j("stopped");this.maxSeekBackTime$=new PV(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),$(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"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return dE(e)}};this.subscription=new RV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Be(e.container,e.tuning),this.liveStreamClient=new cu(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:Xd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(pE(this.videoState.stateChangeStarted$.pipe(hE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(hE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=_e(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(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(we(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 dE(n.to)}},i)).add(pE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,AV(["init"])).pipe(wV(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(Te(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:kV.INVARIANT}),this.video.srcObject=e,$(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Xd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qr=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 za,assertNonNullable as oi,ErrorCategory as du,filter as vE,isNonNullable as yE,isNullable as VV,map as _V,merge as OV,once as FV,Subject as le,Subscription as TE,ValueSubject as q,flattenObject as Jd}from"@vkontakte/videoplayer-shared/es2018";import{Observable as LV,map as fE,Subscription as $V,Subject as MV}from"@vkontakte/videoplayer-shared/es2018";var mE=s=>new LV(e=>{let t=new $V,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(fE(({from:l,to:c})=>`${l}-${c}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(fE(({type:l})=>l!==void 0)),n=new MV,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as DV,Subscription as CV,combine as BV,filter as gE,once as SE}from"@vkontakte/videoplayer-shared/es2018";function bE(){return new(window.AudioContext||window.webkitAudioContext)}var Ga=class Ga{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ee;this.subscriptions=new CV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(gE(a=>!!a.type),SE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){F.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(BV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(gE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),SE()).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=bE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Ga.errorId,category:DV.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ga.errorId} exception`,thrown:e})}};Ga.errorId="VolumeMultiplierManager";var Wr=Ga;var NV={chunkDuration:5e3,maxParallelRequests:5},Ya=class{constructor(e){this.current$=new q({type:void 0});this.providerError$=new le;this.noAvailableProvidersError$=new le;this.volumeMultiplierError$=new le;this.providerOutput={position$:new q(0),duration$:new q(1/0),volume$:new q({muted:!1,volume:1}),availableVideoStreams$:new q([]),currentVideoStream$:new q(void 0),availableVideoTracks$:new q([]),currentVideoTrack$:new q(void 0),availableVideoCodecs$:new q([]),availableAudioStreams$:new q([]),currentAudioStream$:new q(void 0),availableAudioTracks$:new q([]),availableAudioCodecs$:new q([]),currentVideoSegmentLength$:new q(0),currentAudioSegmentLength$:new q(0),isAudioAvailable$:new q(!0),autoVideoTrackLimitingAvailable$:new q(!1),autoVideoTrackLimits$:new q(void 0),currentBuffer$:new q(void 0),isBuffering$:new q(!0),error$:new le,fetcherError$:new le,fetcherRecoverableError$:new le,warning$:new le,willSeekEvent$:new le,soundProhibitedEvent$:new le,seekedEvent$:new le,loopedEvent$:new le,endedEvent$:new le,manifestRequested$:new le,manifestReceived$:new le,firstBytesRequested$:new le,firstBytesReceived$:new le,firstBytesEvent$:new le,loadedMetadataEvent$:new le,firstFrameEvent$:new le,canplay$:new le,isLive$:new q(void 0),isLiveEnded$:new q(null),canPlayLiveTailBuffer$:new q(!1),isLowLatency$:new q(!1),canChangePlaybackSpeed$:new q(!0),liveTime$:new q(void 0),liveBufferTime$:new q(void 0),liveLatency$:new q(void 0),severeStallOccurred$:new le,availableTextTracks$:new q([]),currentTextTrack$:new q(void 0),hostname$:new q(void 0),httpConnectionType$:new q(void 0),httpConnectionReused$:new q(void 0),inPiP$:new q(!1),inFullscreen$:new q(!1),element$:new q(void 0),elementVisible$:new q(!0),availableSources$:new q(void 0),is3DVideo$:new q(!1),playbackState$:new q(""),getCurrentTime$:new q(null)};this.subscription=new TE;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=gc([...pI(this.params.tuning),...dI(this.params.tuning)]).filter(l=>yE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Zd.default)(r,l)),...t.filter(l=>(0,Zd.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Jd(a)),this.screenFormatsIterator=new Qr(a);let n=[...ld(!0),...ld(!1)];this.chromecastFormatsIterator=new Qr(n.filter(l=>yE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Wr.isSupported()&&(this.volumeMultiplierManager=new Wr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Qr(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(VV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:du.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return za(e)}}createScreenProvider(e){var u,l;let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let c=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return oi(c),this.params.tuning.useNewDashProvider?new qa({...o,source:c,sourceHls:d,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):new Ra({...o,source:c,sourceHls:d,forceVideoCodec:(l=this.videoCodecsIterator)==null?void 0:l.getValue()})}case"DASH_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return oi(c),this.params.tuning.useNewDashProvider?new Ua({...o,source:c}):new Pa({...o,source:c})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let c=this.applyFailoverHost(t[e]);return oi(c),new Ha({...o,source:c})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return oi(c),new ja({...o,source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let c=this.applyFailoverHost(t[e]);return oi(c),new Qa({...o,source:c})}case"DASH_LIVE":{let c=this.applyFailoverHost(t[e]);return oi(c),new ay({...o,source:c,config:{...NV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let c=this.applyFailoverHost(t[e]);return oi(c),new Wa({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 za(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return oi(o),new ws({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return za(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return za(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 za(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,EE.default)((0,IE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new TE,t=!1,i=0;return e.add(OV(this.providerOutput.error$.pipe(vE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),mE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(_V(r=>({id:`ProviderHangup:${r}`,category:du.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(vE(({to:a})=>a==="playing"),FV()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===du.NETWORK,u=r.category===du.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,f=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:f,canReinitProvider:c},c?(i++,this.reinitProvider()):f?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Jd(n)):this.tracer.error("providerError",Jd(n))})),e}};import{fromEvent as pu,once as qV,combine as UV,Subscription as xE,ValueSubject as ep,map as jV,filter as HV,isNonNullable as hu,now as We,safeStorage as tp}from"@vkontakte/videoplayer-shared/es2018";var QV=5e3,wE="one_video_throughput",AE="one_video_rtt",Vt=window.navigator.connection,RE=()=>{let s=Vt==null?void 0:Vt.downlink;if(hu(s)&&s!==10)return s*1e3},PE=()=>{let s=Vt==null?void 0:Vt.rtt;if(hu(s)&&s!==3e3)return s},kE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},ip=class s{constructor(e){this.subscription=new xE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(wE)||(e.useBrowserEstimation?RE():void 0)||QV,i=(a=(r=s.load(AE))!=null?r:e.useBrowserEstimation?PE():void 0)!=null?a:0;if(this.throughput$=new ep(t),this.rtt$=new ep(i),this.rttAdjustedThroughput$=new ep(kE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ct.getSmoothedValue(t,-1,e),this.rtt=Ct.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=RE();u&&this.throughput.next(u);let l=PE();hu(l)&&this.rtt.next(l)};Vt&&"onchange"in Vt&&this.subscription.add(pu(Vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{tp.set(wE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{tp.set(AE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(UV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(jV(({throughput:n,rtt:o})=>kE(n,o,e.rttPenaltyRequestSize)),HV(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 xE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(pu(e,"progress").pipe(qV()).subscribe(a=>{t=a.loaded,i=We()}));break;case 1:case 0:r.add(pu(e,"loadstart").subscribe(()=>{t=0,i=We()}));break}r.add(pu(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.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,a=We(),n=0,o=We(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,We()-a,1),this.concurrentDownloads.delete(e);else if(d){if(t){let f=We();if(f-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||f-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let h=o-a;h&&this.addRawSpeed(n,h,1,t),n=d.byteLength,a=We()}else n+=d.byteLength;o=We()}else r+=d.byteLength,n+=d.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(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=tp.get(e);if(hu(t))return(i=parseInt(t,10))!=null?i:void 0}},LE=ip;import{fillWithDefault as WV,VideoQuality as fu}from"@vkontakte/videoplayer-shared/es2018";var $E={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:fu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:fu.Q_720P,trafficSavingLimit:fu.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:fu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,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},ME=s=>{var e;return{...WV(s,$E),configName:[...(e=s.configName)!=null?e:[],...$E.configName]}};import{assertNonNullable as sp,combine as _t,ErrorCategory as mu,filter as U,filterChanged as K,fromEvent as ap,isNonNullable as VE,isNullable as ZV,Logger as e_,map as z,mapTo as _E,merge as ui,now as bu,once as H,Subject as W,Subscription as OE,tap as np,ValueSubject as C,isHigher as t_,isInvariantQuality as FE,flattenObject as li,throttle as op,getTraceSubscriptionMethod as NE,TracerFactory as i_,InternalsExposure as r_,getPlayerId as s_}from"@vkontakte/videoplayer-shared/es2018";import{merge as GV,map as zV,filter as DE,isNonNullable as YV}from"@vkontakte/videoplayer-shared/es2018";var rp=({seekState:s,position$:e})=>GV(s.stateChangeEnded$.pipe(zV(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),DE(YV)),e.pipe(DE(()=>s.getState().state==="none")));import{assertNonNullable as KV}from"@vkontakte/videoplayer-shared/es2018";var CE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return KV(e,`Wrong container or containerId {${s.container}}`),e};import{filter as XV,once as JV}from"@vkontakte/videoplayer-shared/es2018";var BE=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(XV(r=>r.length>0),JV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var gu=class{constructor(e={configName:[]},t=i_.createRootTracer(!1),i){this.subscription=new OE;this.logger=new e_;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}),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 W,ready$:new W,started$:new W,playing$:new W,paused$:new W,stopped$:new W,willReady$:new W,willStart$:new W,willResume$:new W,willPause$:new W,willStop$:new W,willDestruct$:new W,watchCoverageRecord$:new W,watchCoverageLive$:new W,managedError$:new W,fatalError$:new W,fetcherRecoverableError$:new W,ended$:new W,looped$:new W,seeked$:new W,willSeek$:new W,autoplaySoundProhibited$:new W,manifestRequested$:new W,manifestReceived$:new W,firstBytesRequested$:new W,firstBytesReceived$:new W,firstBytes$:new W,loadedMetadata$:new W,firstFrame$:new W,canplay$:new W,log$:new W,fetcherError$:new W,severeStallOccured$:new W};this.experimental={element$:new C(void 0),tuningConfigName$:new C([]),enableDebugTelemetry$:new C(!1),dumpTelemetry:Lv,getCurrentTime$:new C(null)};if(this.initLogs(),this.tuning=ME(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,up.default)(this.info).forEach(r=>r.setSuppressErrors(!0)),(0,up.default)(this.events).forEach(r=>r.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new yn({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new LE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new r_("core",s_(i==null?void 0:i.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,a,n)=>{let o=Reflect.get(r,a,n);return typeof o!="function"?o:(...u)=>{try{return o.apply(r,u)}catch(l){let c=u.map(p=>JSON.stringify(p,(h,m)=>{let g=typeof m;return(0,qE.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),d=`Player.${String(a)}`,f=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:mu.WTF,message:f,thrown:l}),l}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",li(o)),this.domContainer=CE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Ya({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?F.isInited$.pipe(U(n=>!!n),H()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),ap(document,"visibilitychange").pipe(H()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{sp(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(U(i=>i.length>0),H()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",li(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.desiredState.playbackRate.startTransitionTo(e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",li(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{var t;BE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{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.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(U(e=>e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(ZV(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return VE(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(ui(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(Mv(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(U(({from:e})=>e==="stopped"),H()).subscribe(()=>{this.initedAt=bu(),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",li(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:mu.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(H()).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",li(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(_t({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)=>FE(u)?1:FE(l)?-1:t_(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(U(n=>VE(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.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(np(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(_t({hasLiveOffsetByPaused:ui(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(_t({atLiveEdge:_t({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:rp({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(),np(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(_t({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(),np(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(rp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ui(e.providerOutput.endedEvent$.pipe(_E(!0)),e.providerOutput.seekedEvent$.pipe(_E(!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:mu.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(H()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(H()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(H()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(H()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(H(),z(n=>n!=null?n:bu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(H(),z(()=>bu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(H(),z(()=>bu()-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(U(({to:n})=>n==="playing"),H()).subscribe(()=>i.next(!1)));let r=0,a=ui(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(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ui(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(ui(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(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 OE;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(U(i=>i.length>0),H()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=vt(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(ui(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;sp(this.providerContainer),sp(e),kv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Pv(i)),this.providerContainer.current$.subscribe(({type:i})=>ks("provider",i)),e.duration$.subscribe(i=>ks("duration",i)),e.availableVideoTracks$.pipe(U(i=>!!i.length),H()).subscribe(i=>ks("tracks",i)),this.events.fatalError$.subscribe(new Pe("fatalError")),this.events.managedError$.subscribe(new Pe("managedError")),e.position$.subscribe(new Pe("position")),e.currentVideoTrack$.pipe(z(i=>i==null?void 0:i.quality)).subscribe(new Pe("quality")),this.info.currentBuffer$.subscribe(new Pe("buffer")),e.isBuffering$.subscribe(new Pe("isBuffering"))].forEach(i=>this.subscription.add(i)),ks("codecs",F.video.supportedCodecs)}initTracerSubscription(){let e=NE(this.tracer.log.bind(this.tracer)),t=NE(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(_t({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(U(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),K((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(U(i=>i>0),K()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(U(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(_t({currentBuffer:this.info.currentBuffer$.pipe(U(i=>i.end>0),K((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(K())}).pipe(op(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(_t({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(U(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),op(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(K(),U(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(K(),U(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(),U(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(_t({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(U(({throughputEstimation:i,rtt:r})=>!!i&&!!r),op(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(K(),U(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:mu.DOM,message:String(r)})})};this.subscription.add(ui(ap(document,"visibilitychange"),ap(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",li({quality:t,availableTracks:li(e),track:li(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&&!Vs()}};import{Subscription as kJ,Observable as LJ,Subject as $J,ValueSubject as MJ,VideoQuality as DJ}from"@vkontakte/videoplayer-shared/es2018";var CJ=`@vkontakte/videoplayer-core@${zp}`;export{cn as ChromecastState,Eu as HttpConnectionType,LJ as Observable,Me as PlaybackState,gu as Player,dn as PredefinedQualityLimits,CJ as SDK_VERSION,$J as Subject,kJ as Subscription,xu as Surface,zp as VERSION,MJ as ValueSubject,At as VideoFormat,DJ as VideoQuality,Y$ as areValidLiveRecordSources,F as clientChecker,xs as isMobile};
|