@vkontakte/videoplayer-core 2.0.108-dev.7ca5c32c.0 → 2.0.108-dev.9969cb23.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 +42 -21
- package/es2015.esm.js +42 -21
- package/es2018.cjs.js +42 -21
- package/es2018.esm.js +41 -20
- package/esnext.cjs.js +42 -21
- package/esnext.esm.js +42 -21
- package/evergreen.esm.js +42 -21
- package/package.json +2 -2
- package/types/player/Player.d.ts +3 -3
- package/types/player/types.d.ts +5 -6
- package/types/providers/DashProvider/baseDashProvider.d.ts +3 -2
- package/types/providers/DashProvider/lib/LiveTextManager.d.ts +22 -0
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -0
- package/types/providers/DashProvider/lib/player.d.ts +3 -1
- package/types/providers/DashProvider/lib/types.d.ts +6 -0
- package/types/providers/DashProvider/lib/utils.d.ts +3 -5
- package/types/utils/autoSelectTrack.d.ts +29 -0
- package/types/utils/tuningConfig.d.ts +6 -0
- package/types/utils/autoSelectVideoTrack.d.ts +0 -26
package/esnext.cjs.js
CHANGED
|
@@ -1,40 +1,61 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.108-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.108-dev.9969cb23.0
|
|
3
|
+
* Mon, 09 Sep 2024 08:50:20 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var km=Object.create;var aa=Object.defineProperty;var Am=Object.getOwnPropertyDescriptor;var wm=Object.getOwnPropertyNames;var Rm=Object.getPrototypeOf,Lm=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),$m=(i,e)=>{for(var t in e)aa(i,t,{get:e[t],enumerable:!0})},zo=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of wm(e))!Lm.call(i,a)&&a!==t&&aa(i,a,{get:()=>e[a],enumerable:!(r=Am(e,a))||r.enumerable});return i};var Fe=(i,e,t)=>(t=i!=null?km(Rm(i)):{},zo(e||!i||!i.__esModule?aa(t,"default",{value:i,enumerable:!0}):t,i)),Mm=i=>zo(aa({},"__esModule",{value:!0}),i);var Pe=m((Qx,Jo)=>{"use strict";Jo.exports=function(i){try{return!!i()}catch{return!0}}});var $r=m((Wx,Xo)=>{"use strict";var Dm=Pe();Xo.exports=!Dm(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var me=m((Yx,tu)=>{"use strict";var Zo=$r(),eu=Function.prototype,Es=eu.call,Om=Zo&&eu.bind.bind(Es,Es);tu.exports=Zo?Om:function(i){return function(){return Es.apply(i,arguments)}}});var Xt=m((zx,iu)=>{"use strict";var ru=me(),Bm=ru({}.toString),Vm=ru("".slice);iu.exports=function(i){return Vm(Bm(i),8,-1)}});var su=m((Kx,au)=>{"use strict";var _m=me(),Nm=Pe(),Fm=Xt(),xs=Object,qm=_m("".split);au.exports=Nm(function(){return!xs("z").propertyIsEnumerable(0)})?function(i){return Fm(i)==="String"?qm(i,""):xs(i)}:xs});var Zt=m((Jx,nu)=>{"use strict";nu.exports=function(i){return i==null}});var Mr=m((Xx,ou)=>{"use strict";var Um=Zt(),Hm=TypeError;ou.exports=function(i){if(Um(i))throw new Hm("Can't call method on "+i);return i}});var er=m((Zx,uu)=>{"use strict";var jm=su(),Gm=Mr();uu.exports=function(i){return jm(Gm(i))}});var Ps=m((eP,lu)=>{"use strict";lu.exports=function(){}});var Lt=m((tP,cu)=>{"use strict";cu.exports={}});var ie=m((ks,du)=>{"use strict";var Cr=function(i){return i&&i.Math===Math&&i};du.exports=Cr(typeof globalThis=="object"&&globalThis)||Cr(typeof window=="object"&&window)||Cr(typeof self=="object"&&self)||Cr(typeof global=="object"&&global)||Cr(typeof ks=="object"&&ks)||function(){return this}()||Function("return this")()});var re=m((rP,pu)=>{"use strict";var As=typeof document=="object"&&document.all;pu.exports=typeof As>"u"&&As!==void 0?function(i){return typeof i=="function"||i===As}:function(i){return typeof i=="function"}});var mu=m((iP,fu)=>{"use strict";var Qm=ie(),Wm=re(),hu=Qm.WeakMap;fu.exports=Wm(hu)&&/native code/.test(String(hu))});var Le=m((aP,bu)=>{"use strict";var Ym=re();bu.exports=function(i){return typeof i=="object"?i!==null:Ym(i)}});var $e=m((sP,Su)=>{"use strict";var zm=Pe();Su.exports=!zm(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ua=m((nP,vu)=>{"use strict";var Km=ie(),gu=Le(),ws=Km.document,Jm=gu(ws)&&gu(ws.createElement);vu.exports=function(i){return Jm?ws.createElement(i):{}}});var Rs=m((oP,yu)=>{"use strict";var Xm=$e(),Zm=Pe(),eb=ua();yu.exports=!Xm&&!Zm(function(){return Object.defineProperty(eb("div"),"a",{get:function(){return 7}}).a!==7})});var Ls=m((uP,Tu)=>{"use strict";var tb=$e(),rb=Pe();Tu.exports=tb&&rb(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=m((lP,Iu)=>{"use strict";var ib=Le(),ab=String,sb=TypeError;Iu.exports=function(i){if(ib(i))return i;throw new sb(ab(i)+" is not an object")}});var ke=m((cP,Eu)=>{"use strict";var nb=$r(),la=Function.prototype.call;Eu.exports=nb?la.bind(la):function(){return la.apply(la,arguments)}});var ca=m((dP,xu)=>{"use strict";xu.exports={}});var rt=m((pP,ku)=>{"use strict";var $s=ca(),Ms=ie(),ob=re(),Pu=function(i){return ob(i)?i:void 0};ku.exports=function(i,e){return arguments.length<2?Pu($s[i])||Pu(Ms[i]):$s[i]&&$s[i][e]||Ms[i]&&Ms[i][e]}});var Dr=m((hP,Au)=>{"use strict";var ub=me();Au.exports=ub({}.isPrototypeOf)});var tr=m((fP,Lu)=>{"use strict";var lb=ie(),wu=lb.navigator,Ru=wu&&wu.userAgent;Lu.exports=Ru?String(Ru):""});var Ds=m((mP,Bu)=>{"use strict";var Ou=ie(),Cs=tr(),$u=Ou.process,Mu=Ou.Deno,Cu=$u&&$u.versions||Mu&&Mu.version,Du=Cu&&Cu.v8,qe,da;Du&&(qe=Du.split("."),da=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!da&&Cs&&(qe=Cs.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=Cs.match(/Chrome\/(\d+)/),qe&&(da=+qe[1])));Bu.exports=da});var Os=m((bP,_u)=>{"use strict";var Vu=Ds(),cb=Pe(),db=ie(),pb=db.String;_u.exports=!!Object.getOwnPropertySymbols&&!cb(function(){var i=Symbol("symbol detection");return!pb(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Vu&&Vu<41})});var Bs=m((SP,Nu)=>{"use strict";var hb=Os();Nu.exports=hb&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Vs=m((gP,Fu)=>{"use strict";var fb=rt(),mb=re(),bb=Dr(),Sb=Bs(),gb=Object;Fu.exports=Sb?function(i){return typeof i=="symbol"}:function(i){var e=fb("Symbol");return mb(e)&&bb(e.prototype,gb(i))}});var Or=m((vP,qu)=>{"use strict";var vb=String;qu.exports=function(i){try{return vb(i)}catch{return"Object"}}});var it=m((yP,Uu)=>{"use strict";var yb=re(),Tb=Or(),Ib=TypeError;Uu.exports=function(i){if(yb(i))return i;throw new Ib(Tb(i)+" is not a function")}});var Br=m((TP,Hu)=>{"use strict";var Eb=it(),xb=Zt();Hu.exports=function(i,e){var t=i[e];return xb(t)?void 0:Eb(t)}});var Gu=m((IP,ju)=>{"use strict";var _s=ke(),Ns=re(),Fs=Le(),Pb=TypeError;ju.exports=function(i,e){var t,r;if(e==="string"&&Ns(t=i.toString)&&!Fs(r=_s(t,i))||Ns(t=i.valueOf)&&!Fs(r=_s(t,i))||e!=="string"&&Ns(t=i.toString)&&!Fs(r=_s(t,i)))return r;throw new Pb("Can't convert object to primitive value")}});var Ue=m((EP,Qu)=>{"use strict";Qu.exports=!0});var zu=m((xP,Yu)=>{"use strict";var Wu=ie(),kb=Object.defineProperty;Yu.exports=function(i,e){try{kb(Wu,i,{value:e,configurable:!0,writable:!0})}catch{Wu[i]=e}return e}});var Vr=m((PP,Xu)=>{"use strict";var Ab=Ue(),wb=ie(),Rb=zu(),Ku="__core-js_shared__",Ju=Xu.exports=wb[Ku]||Rb(Ku,{});(Ju.versions||(Ju.versions=[])).push({version:"3.38.0",mode:Ab?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var qs=m((kP,el)=>{"use strict";var Zu=Vr();el.exports=function(i,e){return Zu[i]||(Zu[i]=e||{})}});var _r=m((AP,tl)=>{"use strict";var Lb=Mr(),$b=Object;tl.exports=function(i){return $b(Lb(i))}});var He=m((wP,rl)=>{"use strict";var Mb=me(),Cb=_r(),Db=Mb({}.hasOwnProperty);rl.exports=Object.hasOwn||function(e,t){return Db(Cb(e),t)}});var Us=m((RP,il)=>{"use strict";var Ob=me(),Bb=0,Vb=Math.random(),_b=Ob(1 .toString);il.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+_b(++Bb+Vb,36)}});var pe=m((LP,sl)=>{"use strict";var Nb=ie(),Fb=qs(),al=He(),qb=Us(),Ub=Os(),Hb=Bs(),rr=Nb.Symbol,Hs=Fb("wks"),jb=Hb?rr.for||rr:rr&&rr.withoutSetter||qb;sl.exports=function(i){return al(Hs,i)||(Hs[i]=Ub&&al(rr,i)?rr[i]:jb("Symbol."+i)),Hs[i]}});var ll=m(($P,ul)=>{"use strict";var Gb=ke(),nl=Le(),ol=Vs(),Qb=Br(),Wb=Gu(),Yb=pe(),zb=TypeError,Kb=Yb("toPrimitive");ul.exports=function(i,e){if(!nl(i)||ol(i))return i;var t=Qb(i,Kb),r;if(t){if(e===void 0&&(e="default"),r=Gb(t,i,e),!nl(r)||ol(r))return r;throw new zb("Can't convert object to primitive value")}return e===void 0&&(e="number"),Wb(i,e)}});var js=m((MP,cl)=>{"use strict";var Jb=ll(),Xb=Vs();cl.exports=function(i){var e=Jb(i,"string");return Xb(e)?e:e+""}});var $t=m(pl=>{"use strict";var Zb=$e(),eS=Rs(),tS=Ls(),pa=ze(),dl=js(),rS=TypeError,Gs=Object.defineProperty,iS=Object.getOwnPropertyDescriptor,Qs="enumerable",Ws="configurable",Ys="writable";pl.f=Zb?tS?function(e,t,r){if(pa(e),t=dl(t),pa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Ys in r&&!r[Ys]){var a=iS(e,t);a&&a[Ys]&&(e[t]=r.value,r={configurable:Ws in r?r[Ws]:a[Ws],enumerable:Qs in r?r[Qs]:a[Qs],writable:!1})}return Gs(e,t,r)}:Gs:function(e,t,r){if(pa(e),t=dl(t),pa(r),eS)try{return Gs(e,t,r)}catch{}if("get"in r||"set"in r)throw new rS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Nr=m((DP,hl)=>{"use strict";hl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var ir=m((OP,fl)=>{"use strict";var aS=$e(),sS=$t(),nS=Nr();fl.exports=aS?function(i,e,t){return sS.f(i,e,nS(1,t))}:function(i,e,t){return i[e]=t,i}});var ha=m((BP,bl)=>{"use strict";var oS=qs(),uS=Us(),ml=oS("keys");bl.exports=function(i){return ml[i]||(ml[i]=uS(i))}});var fa=m((VP,Sl)=>{"use strict";Sl.exports={}});var Xs=m((_P,yl)=>{"use strict";var lS=mu(),vl=ie(),cS=Le(),dS=ir(),zs=He(),Ks=Vr(),pS=ha(),hS=fa(),gl="Object already initialized",Js=vl.TypeError,fS=vl.WeakMap,ma,Fr,ba,mS=function(i){return ba(i)?Fr(i):ma(i,{})},bS=function(i){return function(e){var t;if(!cS(e)||(t=Fr(e)).type!==i)throw new Js("Incompatible receiver, "+i+" required");return t}};lS||Ks.state?(je=Ks.state||(Ks.state=new fS),je.get=je.get,je.has=je.has,je.set=je.set,ma=function(i,e){if(je.has(i))throw new Js(gl);return e.facade=i,je.set(i,e),e},Fr=function(i){return je.get(i)||{}},ba=function(i){return je.has(i)}):(Mt=pS("state"),hS[Mt]=!0,ma=function(i,e){if(zs(i,Mt))throw new Js(gl);return e.facade=i,dS(i,Mt,e),e},Fr=function(i){return zs(i,Mt)?i[Mt]:{}},ba=function(i){return zs(i,Mt)});var je,Mt;yl.exports={set:ma,get:Fr,has:ba,enforce:mS,getterFor:bS}});var Zs=m((NP,xl)=>{"use strict";var SS=$r(),El=Function.prototype,Tl=El.apply,Il=El.call;xl.exports=typeof Reflect=="object"&&Reflect.apply||(SS?Il.bind(Tl):function(){return Il.apply(Tl,arguments)})});var en=m((FP,Pl)=>{"use strict";var gS=Xt(),vS=me();Pl.exports=function(i){if(gS(i)==="Function")return vS(i)}});var Rl=m(wl=>{"use strict";var kl={}.propertyIsEnumerable,Al=Object.getOwnPropertyDescriptor,yS=Al&&!kl.call({1:2},1);wl.f=yS?function(e){var t=Al(this,e);return!!t&&t.enumerable}:kl});var Ml=m($l=>{"use strict";var TS=$e(),IS=ke(),ES=Rl(),xS=Nr(),PS=er(),kS=js(),AS=He(),wS=Rs(),Ll=Object.getOwnPropertyDescriptor;$l.f=TS?Ll:function(e,t){if(e=PS(e),t=kS(t),wS)try{return Ll(e,t)}catch{}if(AS(e,t))return xS(!IS(ES.f,e,t),e[t])}});var tn=m((HP,Cl)=>{"use strict";var RS=Pe(),LS=re(),$S=/#|\.prototype\./,qr=function(i,e){var t=CS[MS(i)];return t===OS?!0:t===DS?!1:LS(e)?RS(e):!!e},MS=qr.normalize=function(i){return String(i).replace($S,".").toLowerCase()},CS=qr.data={},DS=qr.NATIVE="N",OS=qr.POLYFILL="P";Cl.exports=qr});var Ur=m((jP,Ol)=>{"use strict";var Dl=en(),BS=it(),VS=$r(),_S=Dl(Dl.bind);Ol.exports=function(i,e){return BS(i),e===void 0?i:VS?_S(i,e):function(){return i.apply(e,arguments)}}});var Me=m((GP,Vl)=>{"use strict";var Hr=ie(),NS=Zs(),FS=en(),qS=re(),US=Ml().f,HS=tn(),ar=ca(),jS=Ur(),sr=ir(),Bl=He();Vr();var GS=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return NS(i,this,arguments)};return e.prototype=i.prototype,e};Vl.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Hr:a?Hr[t]:Hr[t]&&Hr[t].prototype,o=r?ar:ar[t]||sr(ar,t,{})[t],l=o.prototype,u,d,c,h,f,b,S,y,I;for(h in e)u=HS(r?h:t+(a?".":"#")+h,i.forced),d=!u&&n&&Bl(n,h),b=o[h],d&&(i.dontCallGetSet?(I=US(n,h),S=I&&I.value):S=n[h]),f=d&&S?S:e[h],!(!u&&!s&&typeof b==typeof f)&&(i.bind&&d?y=jS(f,Hr):i.wrap&&d?y=GS(f):s&&qS(f)?y=FS(f):y=f,(i.sham||f&&f.sham||b&&b.sham)&&sr(y,"sham",!0),sr(o,h,y),s&&(c=t+"Prototype",Bl(ar,c)||sr(ar,c,{}),sr(ar[c],h,f),i.real&&l&&(u||!l[h])&&sr(l,h,f)))}});var Fl=m((QP,Nl)=>{"use strict";var rn=$e(),QS=He(),_l=Function.prototype,WS=rn&&Object.getOwnPropertyDescriptor,an=QS(_l,"name"),YS=an&&function(){}.name==="something",zS=an&&(!rn||rn&&WS(_l,"name").configurable);Nl.exports={EXISTS:an,PROPER:YS,CONFIGURABLE:zS}});var Ul=m((WP,ql)=>{"use strict";var KS=Math.ceil,JS=Math.floor;ql.exports=Math.trunc||function(e){var t=+e;return(t>0?JS:KS)(t)}});var Sa=m((YP,Hl)=>{"use strict";var XS=Ul();Hl.exports=function(i){var e=+i;return e!==e||e===0?0:XS(e)}});var Gl=m((zP,jl)=>{"use strict";var ZS=Sa(),eg=Math.max,tg=Math.min;jl.exports=function(i,e){var t=ZS(i);return t<0?eg(t+e,0):tg(t,e)}});var Wl=m((KP,Ql)=>{"use strict";var rg=Sa(),ig=Math.min;Ql.exports=function(i){var e=rg(i);return e>0?ig(e,9007199254740991):0}});var ga=m((JP,Yl)=>{"use strict";var ag=Wl();Yl.exports=function(i){return ag(i.length)}});var Jl=m((XP,Kl)=>{"use strict";var sg=er(),ng=Gl(),og=ga(),zl=function(i){return function(e,t,r){var a=sg(e),s=og(a);if(s===0)return!i&&-1;var n=ng(r,s),o;if(i&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};Kl.exports={includes:zl(!0),indexOf:zl(!1)}});var ec=m((ZP,Zl)=>{"use strict";var ug=me(),sn=He(),lg=er(),cg=Jl().indexOf,dg=fa(),Xl=ug([].push);Zl.exports=function(i,e){var t=lg(i),r=0,a=[],s;for(s in t)!sn(dg,s)&&sn(t,s)&&Xl(a,s);for(;e.length>r;)sn(t,s=e[r++])&&(~cg(a,s)||Xl(a,s));return a}});var nn=m((ek,tc)=>{"use strict";tc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var ic=m((tk,rc)=>{"use strict";var pg=ec(),hg=nn();rc.exports=Object.keys||function(e){return pg(e,hg)}});var sc=m(ac=>{"use strict";var fg=$e(),mg=Ls(),bg=$t(),Sg=ze(),gg=er(),vg=ic();ac.f=fg&&!mg?Object.defineProperties:function(e,t){Sg(e);for(var r=gg(t),a=vg(t),s=a.length,n=0,o;s>n;)bg.f(e,o=a[n++],r[o]);return e}});var on=m((ik,nc)=>{"use strict";var yg=rt();nc.exports=yg("document","documentElement")});var dn=m((ak,hc)=>{"use strict";var Tg=ze(),Ig=sc(),oc=nn(),Eg=fa(),xg=on(),Pg=ua(),kg=ha(),uc=">",lc="<",ln="prototype",cn="script",dc=kg("IE_PROTO"),un=function(){},pc=function(i){return lc+cn+uc+i+lc+"/"+cn+uc},cc=function(i){i.write(pc("")),i.close();var e=i.parentWindow.Object;return i=null,e},Ag=function(){var i=Pg("iframe"),e="java"+cn+":",t;return i.style.display="none",xg.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(pc("document.F=Object")),t.close(),t.F},va,ya=function(){try{va=new ActiveXObject("htmlfile")}catch{}ya=typeof document<"u"?document.domain&&va?cc(va):Ag():cc(va);for(var i=oc.length;i--;)delete ya[ln][oc[i]];return ya()};Eg[dc]=!0;hc.exports=Object.create||function(e,t){var r;return e!==null?(un[ln]=Tg(e),r=new un,un[ln]=null,r[dc]=e):r=ya(),t===void 0?r:Ig.f(r,t)}});var mc=m((sk,fc)=>{"use strict";var wg=Pe();fc.exports=!wg(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var hn=m((nk,Sc)=>{"use strict";var Rg=He(),Lg=re(),$g=_r(),Mg=ha(),Cg=mc(),bc=Mg("IE_PROTO"),pn=Object,Dg=pn.prototype;Sc.exports=Cg?pn.getPrototypeOf:function(i){var e=$g(i);if(Rg(e,bc))return e[bc];var t=e.constructor;return Lg(t)&&e instanceof t?t.prototype:e instanceof pn?Dg:null}});var nr=m((ok,gc)=>{"use strict";var Og=ir();gc.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Og(i,e,t),i}});var Sn=m((uk,Tc)=>{"use strict";var Bg=Pe(),Vg=re(),_g=Le(),Ng=dn(),vc=hn(),Fg=nr(),qg=pe(),Ug=Ue(),bn=qg("iterator"),yc=!1,at,fn,mn;[].keys&&(mn=[].keys(),"next"in mn?(fn=vc(vc(mn)),fn!==Object.prototype&&(at=fn)):yc=!0);var Hg=!_g(at)||Bg(function(){var i={};return at[bn].call(i)!==i});Hg?at={}:Ug&&(at=Ng(at));Vg(at[bn])||Fg(at,bn,function(){return this});Tc.exports={IteratorPrototype:at,BUGGY_SAFARI_ITERATORS:yc}});var Ta=m((lk,Ec)=>{"use strict";var jg=pe(),Gg=jg("toStringTag"),Ic={};Ic[Gg]="z";Ec.exports=String(Ic)==="[object z]"});var jr=m((ck,xc)=>{"use strict";var Qg=Ta(),Wg=re(),Ia=Xt(),Yg=pe(),zg=Yg("toStringTag"),Kg=Object,Jg=Ia(function(){return arguments}())==="Arguments",Xg=function(i,e){try{return i[e]}catch{}};xc.exports=Qg?Ia:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Xg(e=Kg(i),zg))=="string"?t:Jg?Ia(e):(r=Ia(e))==="Object"&&Wg(e.callee)?"Arguments":r}});var kc=m((dk,Pc)=>{"use strict";var Zg=Ta(),ev=jr();Pc.exports=Zg?{}.toString:function(){return"[object "+ev(this)+"]"}});var Gr=m((pk,wc)=>{"use strict";var tv=Ta(),rv=$t().f,iv=ir(),av=He(),sv=kc(),nv=pe(),Ac=nv("toStringTag");wc.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(av(a,Ac)||rv(a,Ac,{configurable:!0,value:e}),r&&!tv&&iv(a,"toString",sv))}});var Lc=m((hk,Rc)=>{"use strict";var ov=Sn().IteratorPrototype,uv=dn(),lv=Nr(),cv=Gr(),dv=Lt(),pv=function(){return this};Rc.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=uv(ov,{next:lv(+!r,t)}),cv(i,a,!1,!0),dv[a]=pv,i}});var Mc=m((fk,$c)=>{"use strict";var hv=me(),fv=it();$c.exports=function(i,e,t){try{return hv(fv(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Dc=m((mk,Cc)=>{"use strict";var mv=Le();Cc.exports=function(i){return mv(i)||i===null}});var Bc=m((bk,Oc)=>{"use strict";var bv=Dc(),Sv=String,gv=TypeError;Oc.exports=function(i){if(bv(i))return i;throw new gv("Can't set "+Sv(i)+" as a prototype")}});var gn=m((Sk,Vc)=>{"use strict";var vv=Mc(),yv=Le(),Tv=Mr(),Iv=Bc();Vc.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=vv(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Tv(a),Iv(s),yv(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Yc=m((gk,Wc)=>{"use strict";var Ev=Me(),xv=ke(),Ea=Ue(),Gc=Fl(),Pv=re(),kv=Lc(),_c=hn(),Nc=gn(),Av=Gr(),wv=ir(),vn=nr(),Rv=pe(),Fc=Lt(),Qc=Sn(),Lv=Gc.PROPER,$v=Gc.CONFIGURABLE,qc=Qc.IteratorPrototype,xa=Qc.BUGGY_SAFARI_ITERATORS,Qr=Rv("iterator"),Uc="keys",Wr="values",Hc="entries",jc=function(){return this};Wc.exports=function(i,e,t,r,a,s,n){kv(t,e,r);var o=function(I){if(I===a&&h)return h;if(!xa&&I&&I in d)return d[I];switch(I){case Uc:return function(){return new t(this,I)};case Wr:return function(){return new t(this,I)};case Hc:return function(){return new t(this,I)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,d=i.prototype,c=d[Qr]||d["@@iterator"]||a&&d[a],h=!xa&&c||o(a),f=e==="Array"&&d.entries||c,b,S,y;if(f&&(b=_c(f.call(new i)),b!==Object.prototype&&b.next&&(!Ea&&_c(b)!==qc&&(Nc?Nc(b,qc):Pv(b[Qr])||vn(b,Qr,jc)),Av(b,l,!0,!0),Ea&&(Fc[l]=jc))),Lv&&a===Wr&&c&&c.name!==Wr&&(!Ea&&$v?wv(d,"name",Wr):(u=!0,h=function(){return xv(c,this)})),a)if(S={values:o(Wr),keys:s?h:o(Uc),entries:o(Hc)},n)for(y in S)(xa||u||!(y in d))&&vn(d,y,S[y]);else Ev({target:e,proto:!0,forced:xa||u},S);return(!Ea||n)&&d[Qr]!==h&&vn(d,Qr,h,{name:a}),Fc[e]=h,S}});var Kc=m((vk,zc)=>{"use strict";zc.exports=function(i,e){return{value:i,done:e}}});var Tn=m((yk,td)=>{"use strict";var Mv=er(),yn=Ps(),Jc=Lt(),Zc=Xs(),Cv=$t().f,Dv=Yc(),Pa=Kc(),Ov=Ue(),Bv=$e(),ed="Array Iterator",Vv=Zc.set,_v=Zc.getterFor(ed);td.exports=Dv(Array,"Array",function(i,e){Vv(this,{type:ed,target:Mv(i),index:0,kind:e})},function(){var i=_v(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,Pa(void 0,!0);switch(i.kind){case"keys":return Pa(t,!1);case"values":return Pa(e[t],!1)}return Pa([t,e[t]],!1)},"values");var Xc=Jc.Arguments=Jc.Array;yn("keys");yn("values");yn("entries");if(!Ov&&Bv&&Xc.name!=="values")try{Cv(Xc,"name",{value:"values"})}catch{}});var id=m((Tk,rd)=>{"use strict";var Nv=pe(),Fv=Lt(),qv=Nv("iterator"),Uv=Array.prototype;rd.exports=function(i){return i!==void 0&&(Fv.Array===i||Uv[qv]===i)}});var In=m((Ik,sd)=>{"use strict";var Hv=jr(),ad=Br(),jv=Zt(),Gv=Lt(),Qv=pe(),Wv=Qv("iterator");sd.exports=function(i){if(!jv(i))return ad(i,Wv)||ad(i,"@@iterator")||Gv[Hv(i)]}});var od=m((Ek,nd)=>{"use strict";var Yv=ke(),zv=it(),Kv=ze(),Jv=Or(),Xv=In(),Zv=TypeError;nd.exports=function(i,e){var t=arguments.length<2?Xv(i):e;if(zv(t))return Kv(Yv(t,i));throw new Zv(Jv(i)+" is not iterable")}});var cd=m((xk,ld)=>{"use strict";var ey=ke(),ud=ze(),ty=Br();ld.exports=function(i,e,t){var r,a;ud(i);try{if(r=ty(i,"return"),!r){if(e==="throw")throw t;return t}r=ey(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return ud(r),t}});var Aa=m((Pk,fd)=>{"use strict";var ry=Ur(),iy=ke(),ay=ze(),sy=Or(),ny=id(),oy=ga(),dd=Dr(),uy=od(),ly=In(),pd=cd(),cy=TypeError,ka=function(i,e){this.stopped=i,this.result=e},hd=ka.prototype;fd.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),l=ry(e,r),u,d,c,h,f,b,S,y=function(O){return u&&pd(u,"normal",O),new ka(!0,O)},I=function(O){return a?(ay(O),o?l(O[0],O[1],y):l(O[0],O[1])):o?l(O,y):l(O)};if(s)u=i.iterator;else if(n)u=i;else{if(d=ly(i),!d)throw new cy(sy(i)+" is not iterable");if(ny(d)){for(c=0,h=oy(i);h>c;c++)if(f=I(i[c]),f&&dd(hd,f))return f;return new ka(!1)}u=uy(i,d)}for(b=s?i.next:u.next;!(S=iy(b,u)).done;){try{f=I(S.value)}catch(O){pd(u,"throw",O)}if(typeof f=="object"&&f&&dd(hd,f))return f}return new ka(!1)}});var bd=m((kk,md)=>{"use strict";var dy=$e(),py=$t(),hy=Nr();md.exports=function(i,e,t){dy?py.f(i,e,hy(0,t)):i[e]=t}});var Sd=m(()=>{"use strict";var fy=Me(),my=Aa(),by=bd();fy({target:"Object",stat:!0},{fromEntries:function(e){var t={};return my(e,function(r,a){by(t,r,a)},{AS_ENTRIES:!0}),t}})});var vd=m((Rk,gd)=>{"use strict";Tn();Sd();var Sy=ca();gd.exports=Sy.Object.fromEntries});var Td=m((Lk,yd)=>{"use strict";yd.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 Ed=m(()=>{"use strict";Tn();var gy=Td(),vy=ie(),yy=Gr(),Id=Lt();for(wa in gy)yy(vy[wa],wa),Id[wa]=Id.Array;var wa});var Pd=m((Ck,xd)=>{"use strict";var Ty=vd();Ed();xd.exports=Ty});var En=m((Dk,kd)=>{"use strict";var Iy=Pd();kd.exports=Iy});var Ad=m(()=>{"use strict"});var xn=m((Vk,wd)=>{"use strict";var Yr=ie(),Ey=tr(),xy=Xt(),Ra=function(i){return Ey.slice(0,i.length)===i};wd.exports=function(){return Ra("Bun/")?"BUN":Ra("Cloudflare-Workers")?"CLOUDFLARE":Ra("Deno/")?"DENO":Ra("Node.js/")?"NODE":Yr.Bun&&typeof Bun.version=="string"?"BUN":Yr.Deno&&typeof Deno.version=="object"?"DENO":xy(Yr.process)==="process"?"NODE":Yr.window&&Yr.document?"BROWSER":"REST"}()});var La=m((_k,Rd)=>{"use strict";var Py=xn();Rd.exports=Py==="NODE"});var $d=m((Nk,Ld)=>{"use strict";var ky=$t();Ld.exports=function(i,e,t){return ky.f(i,e,t)}});var Dd=m((Fk,Cd)=>{"use strict";var Ay=rt(),wy=$d(),Ry=pe(),Ly=$e(),Md=Ry("species");Cd.exports=function(i){var e=Ay(i);Ly&&e&&!e[Md]&&wy(e,Md,{configurable:!0,get:function(){return this}})}});var Bd=m((qk,Od)=>{"use strict";var $y=Dr(),My=TypeError;Od.exports=function(i,e){if($y(e,i))return i;throw new My("Incorrect invocation")}});var kn=m((Uk,Vd)=>{"use strict";var Cy=me(),Dy=re(),Pn=Vr(),Oy=Cy(Function.toString);Dy(Pn.inspectSource)||(Pn.inspectSource=function(i){return Oy(i)});Vd.exports=Pn.inspectSource});var Hd=m((Hk,Ud)=>{"use strict";var By=me(),Vy=Pe(),_d=re(),_y=jr(),Ny=rt(),Fy=kn(),Nd=function(){},Fd=Ny("Reflect","construct"),An=/^\s*(?:class|function)\b/,qy=By(An.exec),Uy=!An.test(Nd),zr=function(e){if(!_d(e))return!1;try{return Fd(Nd,[],e),!0}catch{return!1}},qd=function(e){if(!_d(e))return!1;switch(_y(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Uy||!!qy(An,Fy(e))}catch{return!0}};qd.sham=!0;Ud.exports=!Fd||Vy(function(){var i;return zr(zr.call)||!zr(Object)||!zr(function(){i=!0})||i})?qd:zr});var Gd=m((jk,jd)=>{"use strict";var Hy=Hd(),jy=Or(),Gy=TypeError;jd.exports=function(i){if(Hy(i))return i;throw new Gy(jy(i)+" is not a constructor")}});var wn=m((Gk,Wd)=>{"use strict";var Qd=ze(),Qy=Gd(),Wy=Zt(),Yy=pe(),zy=Yy("species");Wd.exports=function(i,e){var t=Qd(i).constructor,r;return t===void 0||Wy(r=Qd(t)[zy])?e:Qy(r)}});var zd=m((Qk,Yd)=>{"use strict";var Ky=me();Yd.exports=Ky([].slice)});var Jd=m((Wk,Kd)=>{"use strict";var Jy=TypeError;Kd.exports=function(i,e){if(i<e)throw new Jy("Not enough arguments");return i}});var Rn=m((Yk,Xd)=>{"use strict";var Xy=tr();Xd.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Xy)});var _n=m((zk,op)=>{"use strict";var Ae=ie(),Zy=Zs(),eT=Ur(),Zd=re(),tT=He(),np=Pe(),ep=on(),rT=zd(),tp=ua(),iT=Jd(),aT=Rn(),sT=La(),On=Ae.setImmediate,Bn=Ae.clearImmediate,nT=Ae.process,Ln=Ae.Dispatch,oT=Ae.Function,rp=Ae.MessageChannel,uT=Ae.String,$n=0,Kr={},ip="onreadystatechange",Jr,Ct,Mn,Cn;np(function(){Jr=Ae.location});var Vn=function(i){if(tT(Kr,i)){var e=Kr[i];delete Kr[i],e()}},Dn=function(i){return function(){Vn(i)}},ap=function(i){Vn(i.data)},sp=function(i){Ae.postMessage(uT(i),Jr.protocol+"//"+Jr.host)};(!On||!Bn)&&(On=function(e){iT(arguments.length,1);var t=Zd(e)?e:oT(e),r=rT(arguments,1);return Kr[++$n]=function(){Zy(t,void 0,r)},Ct($n),$n},Bn=function(e){delete Kr[e]},sT?Ct=function(i){nT.nextTick(Dn(i))}:Ln&&Ln.now?Ct=function(i){Ln.now(Dn(i))}:rp&&!aT?(Mn=new rp,Cn=Mn.port2,Mn.port1.onmessage=ap,Ct=eT(Cn.postMessage,Cn)):Ae.addEventListener&&Zd(Ae.postMessage)&&!Ae.importScripts&&Jr&&Jr.protocol!=="file:"&&!np(sp)?(Ct=sp,Ae.addEventListener("message",ap,!1)):ip in tp("script")?Ct=function(i){ep.appendChild(tp("script"))[ip]=function(){ep.removeChild(this),Vn(i)}}:Ct=function(i){setTimeout(Dn(i),0)});op.exports={set:On,clear:Bn}});var cp=m((Kk,lp)=>{"use strict";var up=ie(),lT=$e(),cT=Object.getOwnPropertyDescriptor;lp.exports=function(i){if(!lT)return up[i];var e=cT(up,i);return e&&e.value}});var Nn=m((Jk,pp)=>{"use strict";var dp=function(){this.head=null,this.tail=null};dp.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};pp.exports=dp});var fp=m((Xk,hp)=>{"use strict";var dT=tr();hp.exports=/ipad|iphone|ipod/i.test(dT)&&typeof Pebble<"u"});var bp=m((Zk,mp)=>{"use strict";var pT=tr();mp.exports=/web0s(?!.*chrome)/i.test(pT)});var Ep=m((eA,Ip)=>{"use strict";var ur=ie(),hT=cp(),Sp=Ur(),Fn=_n().set,fT=Nn(),mT=Rn(),bT=fp(),ST=bp(),qn=La(),gp=ur.MutationObserver||ur.WebKitMutationObserver,vp=ur.document,yp=ur.process,$a=ur.Promise,jn=hT("queueMicrotask"),or,Un,Hn,Ma,Tp;jn||(Xr=new fT,Zr=function(){var i,e;for(qn&&(i=yp.domain)&&i.exit();e=Xr.get();)try{e()}catch(t){throw Xr.head&&or(),t}i&&i.enter()},!mT&&!qn&&!ST&&gp&&vp?(Un=!0,Hn=vp.createTextNode(""),new gp(Zr).observe(Hn,{characterData:!0}),or=function(){Hn.data=Un=!Un}):!bT&&$a&&$a.resolve?(Ma=$a.resolve(void 0),Ma.constructor=$a,Tp=Sp(Ma.then,Ma),or=function(){Tp(Zr)}):qn?or=function(){yp.nextTick(Zr)}:(Fn=Sp(Fn,ur),or=function(){Fn(Zr)}),jn=function(i){Xr.head||or(),Xr.add(i)});var Xr,Zr;Ip.exports=jn});var Pp=m((tA,xp)=>{"use strict";xp.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var Ca=m((rA,kp)=>{"use strict";kp.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Dt=m((iA,Ap)=>{"use strict";var gT=ie();Ap.exports=gT.Promise});var lr=m((aA,$p)=>{"use strict";var vT=ie(),ei=Dt(),yT=re(),TT=tn(),IT=kn(),ET=pe(),wp=xn(),xT=Ue(),Gn=Ds(),Rp=ei&&ei.prototype,PT=ET("species"),Qn=!1,Lp=yT(vT.PromiseRejectionEvent),kT=TT("Promise",function(){var i=IT(ei),e=i!==String(ei);if(!e&&Gn===66||xT&&!(Rp.catch&&Rp.finally))return!0;if(!Gn||Gn<51||!/native code/.test(i)){var t=new ei(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[PT]=r,Qn=t.then(function(){})instanceof r,!Qn)return!0}return!e&&(wp==="BROWSER"||wp==="DENO")&&!Lp});$p.exports={CONSTRUCTOR:kT,REJECTION_EVENT:Lp,SUBCLASSING:Qn}});var cr=m((sA,Cp)=>{"use strict";var Mp=it(),AT=TypeError,wT=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new AT("Bad Promise constructor");e=r,t=a}),this.resolve=Mp(e),this.reject=Mp(t)};Cp.exports.f=function(i){return new wT(i)}});var Xp=m(()=>{"use strict";var RT=Me(),LT=Ue(),Va=La(),vt=ie(),fr=ke(),Dp=nr(),Op=gn(),$T=Gr(),MT=Dd(),CT=it(),Ba=re(),DT=Le(),OT=Bd(),BT=wn(),Fp=_n().set,Jn=Ep(),VT=Pp(),_T=Ca(),NT=Nn(),qp=Xs(),_a=Dt(),Xn=lr(),Up=cr(),Na="Promise",Hp=Xn.CONSTRUCTOR,FT=Xn.REJECTION_EVENT,qT=Xn.SUBCLASSING,Wn=qp.getterFor(Na),UT=qp.set,dr=_a&&_a.prototype,Ot=_a,Da=dr,jp=vt.TypeError,Yn=vt.document,Zn=vt.process,zn=Up.f,HT=zn,jT=!!(Yn&&Yn.createEvent&&vt.dispatchEvent),Gp="unhandledrejection",GT="rejectionhandled",Bp=0,Qp=1,QT=2,eo=1,Wp=2,Oa,Vp,WT,_p,Yp=function(i){var e;return DT(i)&&Ba(e=i.then)?e:!1},zp=function(i,e){var t=e.value,r=e.state===Qp,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,d;try{a?(r||(e.rejection===Wp&&zT(e),e.rejection=eo),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),d=!0)),l===i.promise?n(new jp("Promise-chain cycle")):(u=Yp(l))?fr(u,l,s,n):s(l)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},Kp=function(i,e){i.notified||(i.notified=!0,Jn(function(){for(var t=i.reactions,r;r=t.get();)zp(r,i);i.notified=!1,e&&!i.rejection&&YT(i)}))},Jp=function(i,e,t){var r,a;jT?(r=Yn.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),vt.dispatchEvent(r)):r={promise:e,reason:t},!FT&&(a=vt["on"+i])?a(r):i===Gp&&VT("Unhandled promise rejection",t)},YT=function(i){fr(Fp,vt,function(){var e=i.facade,t=i.value,r=Np(i),a;if(r&&(a=_T(function(){Va?Zn.emit("unhandledRejection",t,e):Jp(Gp,e,t)}),i.rejection=Va||Np(i)?Wp:eo,a.error))throw a.value})},Np=function(i){return i.rejection!==eo&&!i.parent},zT=function(i){fr(Fp,vt,function(){var e=i.facade;Va?Zn.emit("rejectionHandled",e):Jp(GT,e,i.value)})},pr=function(i,e,t){return function(r){i(e,r,t)}},hr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=QT,Kp(i,!0))},Kn=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new jp("Promise can't be resolved itself");var r=Yp(e);r?Jn(function(){var a={done:!1};try{fr(r,e,pr(Kn,a,i),pr(hr,a,i))}catch(s){hr(a,s,i)}}):(i.value=e,i.state=Qp,Kp(i,!1))}catch(a){hr({done:!1},a,i)}}};if(Hp&&(Ot=function(e){OT(this,Da),CT(e),fr(Oa,this);var t=Wn(this);try{e(pr(Kn,t),pr(hr,t))}catch(r){hr(t,r)}},Da=Ot.prototype,Oa=function(e){UT(this,{type:Na,done:!1,notified:!1,parent:!1,reactions:new NT,rejection:!1,state:Bp,value:void 0})},Oa.prototype=Dp(Da,"then",function(e,t){var r=Wn(this),a=zn(BT(this,Ot));return r.parent=!0,a.ok=Ba(e)?e:!0,a.fail=Ba(t)&&t,a.domain=Va?Zn.domain:void 0,r.state===Bp?r.reactions.add(a):Jn(function(){zp(a,r)}),a.promise}),Vp=function(){var i=new Oa,e=Wn(i);this.promise=i,this.resolve=pr(Kn,e),this.reject=pr(hr,e)},Up.f=zn=function(i){return i===Ot||i===WT?new Vp(i):HT(i)},!LT&&Ba(_a)&&dr!==Object.prototype)){_p=dr.then,qT||Dp(dr,"then",function(e,t){var r=this;return new Ot(function(a,s){fr(_p,r,a,s)}).then(e,t)},{unsafe:!0});try{delete dr.constructor}catch{}Op&&Op(dr,Da)}RT({global:!0,constructor:!0,wrap:!0,forced:Hp},{Promise:Ot});$T(Ot,Na,!1,!0);MT(Na)});var ih=m((uA,rh)=>{"use strict";var KT=pe(),eh=KT("iterator"),th=!1;try{Zp=0,to={next:function(){return{done:!!Zp++}},return:function(){th=!0}},to[eh]=function(){return this},Array.from(to,function(){throw 2})}catch{}var Zp,to;rh.exports=function(i,e){try{if(!e&&!th)return!1}catch{return!1}var t=!1;try{var r={};r[eh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var ro=m((lA,ah)=>{"use strict";var JT=Dt(),XT=ih(),ZT=lr().CONSTRUCTOR;ah.exports=ZT||!XT(function(i){JT.all(i).then(void 0,function(){})})});var sh=m(()=>{"use strict";var eI=Me(),tI=ke(),rI=it(),iI=cr(),aI=Ca(),sI=Aa(),nI=ro();eI({target:"Promise",stat:!0,forced:nI},{all:function(e){var t=this,r=iI.f(t),a=r.resolve,s=r.reject,n=aI(function(){var o=rI(t.resolve),l=[],u=0,d=1;sI(e,function(c){var h=u++,f=!1;d++,tI(o,t,c).then(function(b){f||(f=!0,l[h]=b,--d||a(l))},s)}),--d||a(l)});return n.error&&s(n.value),r.promise}})});var oh=m(()=>{"use strict";var oI=Me(),uI=Ue(),lI=lr().CONSTRUCTOR,ao=Dt(),cI=rt(),dI=re(),pI=nr(),nh=ao&&ao.prototype;oI({target:"Promise",proto:!0,forced:lI,real:!0},{catch:function(i){return this.then(void 0,i)}});!uI&&dI(ao)&&(io=cI("Promise").prototype.catch,nh.catch!==io&&pI(nh,"catch",io,{unsafe:!0}));var io});var uh=m(()=>{"use strict";var hI=Me(),fI=ke(),mI=it(),bI=cr(),SI=Ca(),gI=Aa(),vI=ro();hI({target:"Promise",stat:!0,forced:vI},{race:function(e){var t=this,r=bI.f(t),a=r.reject,s=SI(function(){var n=mI(t.resolve);gI(e,function(o){fI(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var lh=m(()=>{"use strict";var yI=Me(),TI=cr(),II=lr().CONSTRUCTOR;yI({target:"Promise",stat:!0,forced:II},{reject:function(e){var t=TI.f(this),r=t.reject;return r(e),t.promise}})});var so=m((gA,ch)=>{"use strict";var EI=ze(),xI=Le(),PI=cr();ch.exports=function(i,e){if(EI(i),xI(e)&&e.constructor===i)return e;var t=PI.f(i),r=t.resolve;return r(e),t.promise}});var hh=m(()=>{"use strict";var kI=Me(),AI=rt(),dh=Ue(),wI=Dt(),ph=lr().CONSTRUCTOR,RI=so(),LI=AI("Promise"),$I=dh&&!ph;kI({target:"Promise",stat:!0,forced:dh||ph},{resolve:function(e){return RI($I&&this===LI?wI:this,e)}})});var fh=m(()=>{"use strict";Xp();sh();oh();uh();lh();hh()});var gh=m(()=>{"use strict";var MI=Me(),CI=Ue(),Fa=Dt(),DI=Pe(),bh=rt(),Sh=re(),OI=wn(),mh=so(),BI=nr(),oo=Fa&&Fa.prototype,VI=!!Fa&&DI(function(){oo.finally.call({then:function(){}},function(){})});MI({target:"Promise",proto:!0,real:!0,forced:VI},{finally:function(i){var e=OI(this,bh("Promise")),t=Sh(i);return this.then(t?function(r){return mh(e,i()).then(function(){return r})}:i,t?function(r){return mh(e,i()).then(function(){throw r})}:i)}});!CI&&Sh(Fa)&&(no=bh("Promise").prototype.finally,oo.finally!==no&&BI(oo,"finally",no,{unsafe:!0}));var no});var qa=m((PA,vh)=>{"use strict";var _I=rt();vh.exports=_I});var Th=m((kA,yh)=>{"use strict";Ad();fh();gh();var NI=qa();yh.exports=NI("Promise","finally")});var Eh=m((AA,Ih)=>{"use strict";var FI=Th();Ih.exports=FI});var Ua=m((wA,xh)=>{"use strict";var qI=Eh();xh.exports=qI});var Dh=m(()=>{"use strict";var zI=Me(),KI=_r(),JI=ga(),XI=Sa(),ZI=Ps();zI({target:"Array",proto:!0},{at:function(e){var t=KI(this),r=JI(t),a=XI(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});ZI("at")});var Bh=m((kw,Oh)=>{"use strict";Dh();var eE=qa();Oh.exports=eE("Array","at")});var _h=m((Aw,Vh)=>{"use strict";var tE=Bh();Vh.exports=tE});var ri=m((ww,Nh)=>{"use strict";var rE=_h();Nh.exports=rE});var bf=m(()=>{"use strict"});var Sf=m(()=>{"use strict"});var vf=m((bM,gf)=>{"use strict";var NE=Le(),FE=Xt(),qE=pe(),UE=qE("match");gf.exports=function(i){var e;return NE(i)&&((e=i[UE])!==void 0?!!e:FE(i)==="RegExp")}});var Tf=m((SM,yf)=>{"use strict";var HE=jr(),jE=String;yf.exports=function(i){if(HE(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return jE(i)}});var Ef=m((gM,If)=>{"use strict";var GE=ze();If.exports=function(){var i=GE(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var kf=m((vM,Pf)=>{"use strict";var QE=ke(),WE=He(),YE=Dr(),zE=Ef(),xf=RegExp.prototype;Pf.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in xf)&&!WE(i,"flags")&&YE(xf,i)?QE(zE,i):e}});var wf=m((yM,Af)=>{"use strict";var $o=me(),KE=_r(),JE=Math.floor,Ro=$o("".charAt),XE=$o("".replace),Lo=$o("".slice),ZE=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,ex=/\$([$&'`]|\d{1,2})/g;Af.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=ex;return a!==void 0&&(a=KE(a),l=ZE),XE(s,l,function(u,d){var c;switch(Ro(d,0)){case"$":return"$";case"&":return i;case"`":return Lo(e,0,t);case"'":return Lo(e,n);case"<":c=a[Lo(d,1,-1)];break;default:var h=+d;if(h===0)return u;if(h>o){var f=JE(h/10);return f===0?u:f<=o?r[f-1]===void 0?Ro(d,1):r[f-1]+Ro(d,1):u}c=r[h-1]}return c===void 0?"":c})}});var $f=m(()=>{"use strict";var tx=Me(),rx=ke(),Co=me(),Rf=Mr(),ix=re(),ax=Zt(),sx=vf(),Er=Tf(),nx=Br(),ox=kf(),ux=wf(),lx=pe(),cx=Ue(),dx=lx("replace"),px=TypeError,Mo=Co("".indexOf),hx=Co("".replace),Lf=Co("".slice),fx=Math.max;tx({target:"String",proto:!0},{replaceAll:function(e,t){var r=Rf(this),a,s,n,o,l,u,d,c,h,f,b=0,S="";if(!ax(e)){if(a=sx(e),a&&(s=Er(Rf(ox(e))),!~Mo(s,"g")))throw new px("`.replaceAll` does not allow non-global regexes");if(n=nx(e,dx),n)return rx(n,e,r,t);if(cx&&a)return hx(Er(r),e,t)}for(o=Er(r),l=Er(e),u=ix(t),u||(t=Er(t)),d=l.length,c=fx(1,d),h=Mo(o,l);h!==-1;)f=u?Er(t(l,h,o)):ux(l,o,h,[],void 0,t),S+=Lf(o,b,h)+f,b=h+d,h=h+c>o.length?-1:Mo(o,l,h+c);return b<o.length&&(S+=Lf(o,b)),S}})});var Cf=m((EM,Mf)=>{"use strict";bf();Sf();$f();var mx=qa();Mf.exports=mx("String","replaceAll")});var Of=m((xM,Df)=>{"use strict";var bx=Cf();Df.exports=bx});var Vf=m((PM,Bf)=>{"use strict";var Sx=Of();Bf.exports=Sx});var Mx={};$m(Mx,{ChromecastState:()=>Lr,HttpConnectionType:()=>sa,Observable:()=>et.Observable,PlaybackState:()=>de,Player:()=>Xi,SDK_VERSION:()=>$x,Subject:()=>et.Subject,Subscription:()=>et.Subscription,Surface:()=>na,VERSION:()=>Is,ValueSubject:()=>et.ValueSubject,VideoFormat:()=>tt,VideoQuality:()=>et.VideoQuality});module.exports=Mm(Mx);var Is="2.0.108-dev.7ca5c32c.0";var de=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(de||{}),tt=(P=>(P.MPEG="MPEG",P.DASH="DASH",P.DASH_SEP="DASH_SEP",P.DASH_SEP_VK="DASH_SEP",P.DASH_WEBM="DASH_WEBM",P.DASH_WEBM_AV1="DASH_WEBM_AV1",P.DASH_STREAMS="DASH_STREAMS",P.DASH_WEBM_VK="DASH_WEBM",P.DASH_ONDEMAND="DASH_ONDEMAND",P.DASH_ONDEMAND_VK="DASH_ONDEMAND",P.DASH_LIVE="DASH_LIVE",P.DASH_LIVE_CMAF="DASH_LIVE_CMAF",P.DASH_LIVE_WEBM="DASH_LIVE_WEBM",P.HLS="HLS",P.HLS_ONDEMAND="HLS_ONDEMAND",P.HLS_JS="HLS",P.HLS_LIVE="HLS_LIVE",P.HLS_LIVE_CMAF="HLS_LIVE_CMAF",P.WEB_RTC_LIVE="WEB_RTC_LIVE",P))(tt||{});var Lr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Lr||{}),sa=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(sa||{});var na=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(na||{});var F=require("@vkontakte/videoplayer-shared");var Ko=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var oa=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;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 r=(0,F.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Ko("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,F.assertNever)(a.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,F.map)(a=>a.castState)),(0,F.observableFrom)([r.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(Cm),(0,F.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();(0,F.assertNonNullable)(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;((0,F.isNullable)(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?(0,F.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Cm=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,F.assertNever)(i)}};var nm=Fe(En(),1);var wh=Fe(Ua(),1);var uo=require("@vkontakte/videoplayer-shared");var ce=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,uo.assertNever)(t)}return i},lo=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:(0,uo.assertNever)(e)}};var k=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};var Ke=require("@vkontakte/videoplayer-shared"),U=class{constructor(e){this.transitionStarted$=new Ke.Subject;this.transitionEnded$=new Ke.Subject;this.transitionUpdated$=new Ke.Subject;this.forceChanged$=new Ke.Subject;this.stateChangeStarted$=(0,Ke.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Ke.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,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:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,Ke.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Ph=require("@vkontakte/videoplayer-shared"),kh=i=>{switch(i){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Ph.assertNever)(i)}};var L=require("@vkontakte/videoplayer-shared");var UI=5,HI=5,jI=500,Ah=7e3,ti=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.Subscription;this.videoState=new U("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}default:(0,L.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(kh(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 L.Subscription;this.subscription.add(e),this.subscription.add((0,L.merge)(this.videoState.stateChangeStarted$.pipe((0,L.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,L.map)(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new L.Subject;e.add(a.pipe((0,L.debounce)(jI)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>UI)&&a.next(o),s=o})),e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<HI&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,L.assertNever)(n)}}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=(0,L.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,L.observableFrom)(["init"])).pipe((0,L.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?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),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];(0,L.assertNonNullable)(u);let d=(0,L.getHighestQuality)(Object.keys(u));(0,L.assertNonNullable)(d);let c=u[d];(0,L.assertNonNullable)(c),r=c,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];(0,L.assertNonNullable)(u),r=u.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let u=t[e];(0,L.assertNonNullable)(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];(0,L.assertNonNullable)(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];(0,L.assertNonNullable)(u),r=ce(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",d=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.ErrorCategory.VIDEO_PIPELINE,message:u,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,L.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:l}=this.params.meta;return(0,L.isNonNullable)(o)&&(n.metadata.title=o),(0,L.isNonNullable)(l)&&(n.metadata.subtitle=l),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add((0,L.timeout)(Ah).subscribe(()=>s(`timeout(${Ah})`)))});(0,wh.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var fo=require("@vkontakte/videoplayer-shared");var Rh=require("@vkontakte/videoplayer-shared"),Lh=i=>{try{i.pause(),i.playbackRate=0,(0,Rh.clearVideoElement)(i),i.remove()}catch(e){console.error(e)}};var Ha=require("@vkontakte/videoplayer-shared"),co=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)}},po=window.WeakMap?new WeakMap:new co,ho=window.WeakMap?new WeakMap:new Map,GI=(i,e=20)=>{let t=0;return(0,Ha.fromEvent)(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},be=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?(0,fo.clearVideoElement)(t):(t=document.createElement("video"),i.appendChild(t)),po.set(t,r);let a=new Ha.Subscription;return a.add(GI(t,e)),ho.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Se=i=>{ho.get(i)?.unsubscribe(),ho.delete(i);let t=po.get(i);po.delete(i),t?(0,fo.clearVideoElement)(i):Lh(i)};var $=require("@vkontakte/videoplayer-shared");var yt=require("@vkontakte/videoplayer-shared"),ja=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=(0,yt.isNullable)(a),u=new yt.Subscription;return a&&u.add(a.subscribe(d=>{let c=i.getState();r(d,c)&&i.setState(d)},s)),r(o,n)||(t(n),l&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),l&&i.setState(d.to)},s)),u},Je=(i,e,t)=>ja(e,()=>i.loop,r=>{(0,yt.isNonNullable)(r)&&(i.loop=r)},{onError:t}),ge=(i,e,t,r)=>ja(e,()=>({muted:i.muted,volume:i.volume}),a=>{(0,yt.isNonNullable)(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),Ce=(i,e,t,r)=>ja(e,()=>i.playbackRate,a=>{(0,yt.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),Tt=ja;var QI=i=>["__",i.language,i.label].join("|"),WI=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},mo=class i{constructor(){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:$.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Tt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,$.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Tt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,$.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Tt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:a})),this.subscription.add(Tt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,$.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,$.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,$.filterChanged)()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add((0,$.fromEvent)(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;(0,$.isNonNullable)(t.align)&&(a.align=t.align),(0,$.isNonNullable)(t.position)&&(a.position=t.position),(0,$.isNonNullable)(t.size)&&(a.size=t.size),(0,$.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:QI(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.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(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!WI(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,$.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,$.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.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)}},De=mo;var nt=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 $h=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},bo=i=>{let e=$h(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Mh=i=>{let e=$h(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var M=require("@vkontakte/videoplayer-shared");var YI=3,Ch=(i,e,t=YI)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let l=s-1;l>=0;l--)i.end(l)+t>=r&&(r=i.start(l));for(let l=s+1;l<i.length;l++)i.start(l)-t<=a&&(a=i.end(l))}}return{from:r,to:a}};var ve=i=>{let e=P=>(0,M.fromEvent)(i,P).pipe((0,M.mapTo)(void 0)),r=(0,M.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>(0,M.fromEvent)(i,P))).pipe((0,M.map)(P=>P.type==="ended"?i.readyState<2:i.readyState<3),(0,M.filterChanged)()),a=(0,M.merge)((0,M.fromEvent)(i,"progress"),(0,M.fromEvent)(i,"timeupdate")).pipe((0,M.map)(()=>Ch(i.buffered,i.currentTime))),s=M.clientChecker.isSafari?(0,M.combine)({play:e("play").pipe((0,M.once)()),playing:e("playing")}).pipe((0,M.mapTo)(void 0)):e("playing"),n=(0,M.fromEvent)(i,"volumechange").pipe((0,M.map)(()=>({muted:i.muted,volume:i.volume}))),o=(0,M.fromEvent)(i,"ratechange").pipe((0,M.map)(()=>i.playbackRate)),l=(0,M.fromEvent)(i,"error").pipe((0,M.filter)(()=>!!(i.error||i.played.length)),(0,M.map)(()=>{let P=i.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:M.ErrorCategory.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=(0,M.fromEvent)(i,"timeupdate").pipe((0,M.map)(()=>i.currentTime)),d=new M.Subject,c=.3,h;u.subscribe(P=>{i.loop&&(0,M.isNonNullable)(h)&&(0,M.isNonNullable)(P)&&h>=i.duration-c&&P<=c&&d.next(h),h=P});let f=e("pause").pipe((0,M.filter)(()=>!i.error&&h!==i.duration)),b=(0,M.fromEvent)(i,"enterpictureinpicture"),S=(0,M.fromEvent)(i,"leavepictureinpicture"),y=new M.ValueSubject(Mh(i));b.subscribe(()=>y.next(!0)),S.subscribe(()=>y.next(!1));let I=new M.ValueSubject(bo(i));return(0,M.fromEvent)(i,"fullscreenchange").pipe((0,M.map)(()=>bo(i))).subscribe(I),{playing$:s,pause$:f,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:(0,M.fromEvent)(i,"durationchange").pipe((0,M.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:y,inFullscreen$:I}};var ot=require("@vkontakte/videoplayer-shared"),It=i=>{switch(i){case"mobile":return ot.VideoQuality.Q_144P;case"lowest":return ot.VideoQuality.Q_240P;case"low":return ot.VideoQuality.Q_360P;case"sd":case"medium":return ot.VideoQuality.Q_480P;case"hd":case"high":return ot.VideoQuality.Q_720P;case"fullhd":case"full":return ot.VideoQuality.Q_1080P;case"quadhd":case"quad":return ot.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ot.VideoQuality.Q_2160P}};var go=Fe(ri(),1),j=require("@vkontakte/videoplayer-shared");var So=!1,ut={},Fh=i=>{So=i},qh=()=>{ut={}},Uh=i=>{i(ut)},ii=(i,e)=>{So&&(ut.meta=ut.meta??{},ut.meta[i]=e)},he=class{constructor(e){this.name=e}next(e){if(!So)return;ut.series=ut.series??{};let t=ut.series[this.name]??[];t.push([Date.now(),e]),ut.series[this.name]=t}};var iE=new he("best_bitrate"),aE=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Ga=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,j.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},sE='Assertion "ABR Tracks is empty array" failed',nE=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:d,abrLogger:c})=>{(0,j.assertNotEmptyArray)(i,sE);let h=r.usePixelRatio?window.devicePixelRatio??1:1,f=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},b=f&&(0,j.videoSizeToQuality)(f),S=r.considerPlaybackRate&&(0,j.isNonNullable)(o)?o:1,y=i.filter(w=>!(0,j.isInvariantQuality)(w.quality)).sort((w,C)=>(0,j.isHigher)(w.quality,C.quality)?-1:1),I=(0,go.default)(y,-1)?.quality,O=(0,go.default)(y,0)?.quality,P=(0,j.isNullable)(a)||(0,j.isNonNullable)(a.min)&&(0,j.isNonNullable)(a.max)&&(0,j.isLower)(a.max,a.min)||(0,j.isNonNullable)(a.min)&&O&&(0,j.isHigher)(a.min,O)||(0,j.isNonNullable)(a.max)&&I&&(0,j.isLower)(a.max,I),T=S*aE(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),x={},A=y.filter(w=>(b?(0,j.isLower)(w.quality,b):!0)?((0,j.isNonNullable)(t)&&isFinite(t)&&(0,j.isNonNullable)(w.bitrate)?t-s>=w.bitrate*T:!0)?r.lazyQualitySwitch&&(0,j.isNonNullable)(r.minBufferToSwitchUp)&&l&&!(0,j.isInvariantQuality)(l.quality)&&(n??0)<r.minBufferToSwitchUp&&(0,j.isHigher)(w.quality,l.quality)?(x[w.quality]="Buffer",!1):!!d&&(0,j.isHigherOrEqual)(w.quality,d)?(x[w.quality]="DroppedFramesLimit",!1):P||((0,j.isNullable)(a.max)||(0,j.isLowerOrEqual)(w.quality,a.max))&&((0,j.isNullable)(a.min)||(0,j.isHigherOrEqual)(w.quality,a.min))?!0:(x[w.quality]="FitsQualityLimits",!1):(x[w.quality]="FitsThroughput",!1):(x[w.quality]="FitsContainer",!1))[0];A&&A.bitrate&&iE.next(A.bitrate);let Q=A??y[Math.ceil((y.length-1)/2)]??i[0];Q.quality!==u?.last?.quality&&c({message:`
|
|
7
|
-
[
|
|
8
|
-
|
|
6
|
+
"use strict";var Bm=Object.create;var ga=Object.defineProperty;var Vm=Object.getOwnPropertyDescriptor;var Om=Object.getOwnPropertyNames;var _m=Object.getPrototypeOf,Nm=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Fm=(i,e)=>{for(var t in e)ga(i,t,{get:e[t],enumerable:!0})},su=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Om(e))!Nm.call(i,a)&&a!==t&&ga(i,a,{get:()=>e[a],enumerable:!(r=Vm(e,a))||r.enumerable});return i};var We=(i,e,t)=>(t=i!=null?Bm(_m(i)):{},su(e||!i||!i.__esModule?ga(t,"default",{value:i,enumerable:!0}):t,i)),qm=i=>su(ga({},"__esModule",{value:!0}),i);var ke=m((Xx,ou)=>{"use strict";ou.exports=function(i){try{return!!i()}catch{return!0}}});var qr=m((Zx,uu)=>{"use strict";var Hm=ke();uu.exports=!Hm(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var Se=m((eP,du)=>{"use strict";var cu=qr(),lu=Function.prototype,Ms=lu.call,jm=cu&&lu.bind.bind(Ms,Ms);du.exports=cu?jm:function(i){return function(){return Ms.apply(i,arguments)}}});var ur=m((tP,hu)=>{"use strict";var pu=Se(),Gm=pu({}.toString),Wm=pu("".slice);hu.exports=function(i){return Wm(Gm(i),8,-1)}});var mu=m((rP,fu)=>{"use strict";var Ym=Se(),Qm=ke(),zm=ur(),Cs=Object,Km=Ym("".split);fu.exports=Qm(function(){return!Cs("z").propertyIsEnumerable(0)})?function(i){return zm(i)==="String"?Km(i,""):Cs(i)}:Cs});var cr=m((iP,bu)=>{"use strict";bu.exports=function(i){return i==null}});var Ur=m((aP,gu)=>{"use strict";var Jm=cr(),Xm=TypeError;gu.exports=function(i){if(Jm(i))throw new Xm("Can't call method on "+i);return i}});var lr=m((sP,Su)=>{"use strict";var Zm=mu(),eb=Ur();Su.exports=function(i){return Zm(eb(i))}});var Ds=m((nP,vu)=>{"use strict";vu.exports=function(){}});var qt=m((oP,yu)=>{"use strict";yu.exports={}});var ie=m((Bs,Tu)=>{"use strict";var Hr=function(i){return i&&i.Math===Math&&i};Tu.exports=Hr(typeof globalThis=="object"&&globalThis)||Hr(typeof window=="object"&&window)||Hr(typeof self=="object"&&self)||Hr(typeof global=="object"&&global)||Hr(typeof Bs=="object"&&Bs)||function(){return this}()||Function("return this")()});var re=m((uP,Iu)=>{"use strict";var Vs=typeof document=="object"&&document.all;Iu.exports=typeof Vs>"u"&&Vs!==void 0?function(i){return typeof i=="function"||i===Vs}:function(i){return typeof i=="function"}});var Pu=m((cP,xu)=>{"use strict";var tb=ie(),rb=re(),Eu=tb.WeakMap;xu.exports=rb(Eu)&&/native code/.test(String(Eu))});var De=m((lP,Au)=>{"use strict";var ib=re();Au.exports=function(i){return typeof i=="object"?i!==null:ib(i)}});var Be=m((dP,ku)=>{"use strict";var ab=ke();ku.exports=!ab(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ta=m((pP,Ru)=>{"use strict";var sb=ie(),wu=De(),Os=sb.document,nb=wu(Os)&&wu(Os.createElement);Ru.exports=function(i){return nb?Os.createElement(i):{}}});var _s=m((hP,$u)=>{"use strict";var ob=Be(),ub=ke(),cb=Ta();$u.exports=!ob&&!ub(function(){return Object.defineProperty(cb("div"),"a",{get:function(){return 7}}).a!==7})});var Ns=m((fP,Lu)=>{"use strict";var lb=Be(),db=ke();Lu.exports=lb&&db(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var it=m((mP,Mu)=>{"use strict";var pb=De(),hb=String,fb=TypeError;Mu.exports=function(i){if(pb(i))return i;throw new fb(hb(i)+" is not an object")}});var we=m((bP,Cu)=>{"use strict";var mb=qr(),Ia=Function.prototype.call;Cu.exports=mb?Ia.bind(Ia):function(){return Ia.apply(Ia,arguments)}});var Ea=m((gP,Du)=>{"use strict";Du.exports={}});var pt=m((SP,Vu)=>{"use strict";var Fs=Ea(),qs=ie(),bb=re(),Bu=function(i){return bb(i)?i:void 0};Vu.exports=function(i,e){return arguments.length<2?Bu(Fs[i])||Bu(qs[i]):Fs[i]&&Fs[i][e]||qs[i]&&qs[i][e]}});var jr=m((vP,Ou)=>{"use strict";var gb=Se();Ou.exports=gb({}.isPrototypeOf)});var dr=m((yP,Fu)=>{"use strict";var Sb=ie(),_u=Sb.navigator,Nu=_u&&_u.userAgent;Fu.exports=Nu?String(Nu):""});var Hs=m((TP,Wu)=>{"use strict";var Gu=ie(),Us=dr(),qu=Gu.process,Uu=Gu.Deno,Hu=qu&&qu.versions||Uu&&Uu.version,ju=Hu&&Hu.v8,Ye,xa;ju&&(Ye=ju.split("."),xa=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!xa&&Us&&(Ye=Us.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=Us.match(/Chrome\/(\d+)/),Ye&&(xa=+Ye[1])));Wu.exports=xa});var js=m((IP,Qu)=>{"use strict";var Yu=Hs(),vb=ke(),yb=ie(),Tb=yb.String;Qu.exports=!!Object.getOwnPropertySymbols&&!vb(function(){var i=Symbol("symbol detection");return!Tb(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Yu&&Yu<41})});var Gs=m((EP,zu)=>{"use strict";var Ib=js();zu.exports=Ib&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Ws=m((xP,Ku)=>{"use strict";var Eb=pt(),xb=re(),Pb=jr(),Ab=Gs(),kb=Object;Ku.exports=Ab?function(i){return typeof i=="symbol"}:function(i){var e=Eb("Symbol");return xb(e)&&Pb(e.prototype,kb(i))}});var Gr=m((PP,Ju)=>{"use strict";var wb=String;Ju.exports=function(i){try{return wb(i)}catch{return"Object"}}});var ht=m((AP,Xu)=>{"use strict";var Rb=re(),$b=Gr(),Lb=TypeError;Xu.exports=function(i){if(Rb(i))return i;throw new Lb($b(i)+" is not a function")}});var Wr=m((kP,Zu)=>{"use strict";var Mb=ht(),Cb=cr();Zu.exports=function(i,e){var t=i[e];return Cb(t)?void 0:Mb(t)}});var tc=m((wP,ec)=>{"use strict";var Ys=we(),Qs=re(),zs=De(),Db=TypeError;ec.exports=function(i,e){var t,r;if(e==="string"&&Qs(t=i.toString)&&!zs(r=Ys(t,i))||Qs(t=i.valueOf)&&!zs(r=Ys(t,i))||e!=="string"&&Qs(t=i.toString)&&!zs(r=Ys(t,i)))return r;throw new Db("Can't convert object to primitive value")}});var Qe=m((RP,rc)=>{"use strict";rc.exports=!0});var sc=m(($P,ac)=>{"use strict";var ic=ie(),Bb=Object.defineProperty;ac.exports=function(i,e){try{Bb(ic,i,{value:e,configurable:!0,writable:!0})}catch{ic[i]=e}return e}});var Yr=m((LP,uc)=>{"use strict";var Vb=Qe(),Ob=ie(),_b=sc(),nc="__core-js_shared__",oc=uc.exports=Ob[nc]||_b(nc,{});(oc.versions||(oc.versions=[])).push({version:"3.38.0",mode:Vb?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Ks=m((MP,lc)=>{"use strict";var cc=Yr();lc.exports=function(i,e){return cc[i]||(cc[i]=e||{})}});var Qr=m((CP,dc)=>{"use strict";var Nb=Ur(),Fb=Object;dc.exports=function(i){return Fb(Nb(i))}});var ze=m((DP,pc)=>{"use strict";var qb=Se(),Ub=Qr(),Hb=qb({}.hasOwnProperty);pc.exports=Object.hasOwn||function(e,t){return Hb(Ub(e),t)}});var Js=m((BP,hc)=>{"use strict";var jb=Se(),Gb=0,Wb=Math.random(),Yb=jb(1 .toString);hc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Yb(++Gb+Wb,36)}});var me=m((VP,mc)=>{"use strict";var Qb=ie(),zb=Ks(),fc=ze(),Kb=Js(),Jb=js(),Xb=Gs(),pr=Qb.Symbol,Xs=zb("wks"),Zb=Xb?pr.for||pr:pr&&pr.withoutSetter||Kb;mc.exports=function(i){return fc(Xs,i)||(Xs[i]=Jb&&fc(pr,i)?pr[i]:Zb("Symbol."+i)),Xs[i]}});var vc=m((OP,Sc)=>{"use strict";var eg=we(),bc=De(),gc=Ws(),tg=Wr(),rg=tc(),ig=me(),ag=TypeError,sg=ig("toPrimitive");Sc.exports=function(i,e){if(!bc(i)||gc(i))return i;var t=tg(i,sg),r;if(t){if(e===void 0&&(e="default"),r=eg(t,i,e),!bc(r)||gc(r))return r;throw new ag("Can't convert object to primitive value")}return e===void 0&&(e="number"),rg(i,e)}});var Zs=m((_P,yc)=>{"use strict";var ng=vc(),og=Ws();yc.exports=function(i){var e=ng(i,"string");return og(e)?e:e+""}});var Ut=m(Ic=>{"use strict";var ug=Be(),cg=_s(),lg=Ns(),Pa=it(),Tc=Zs(),dg=TypeError,en=Object.defineProperty,pg=Object.getOwnPropertyDescriptor,tn="enumerable",rn="configurable",an="writable";Ic.f=ug?lg?function(e,t,r){if(Pa(e),t=Tc(t),Pa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&an in r&&!r[an]){var a=pg(e,t);a&&a[an]&&(e[t]=r.value,r={configurable:rn in r?r[rn]:a[rn],enumerable:tn in r?r[tn]:a[tn],writable:!1})}return en(e,t,r)}:en:function(e,t,r){if(Pa(e),t=Tc(t),Pa(r),cg)try{return en(e,t,r)}catch{}if("get"in r||"set"in r)throw new dg("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var zr=m((FP,Ec)=>{"use strict";Ec.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var hr=m((qP,xc)=>{"use strict";var hg=Be(),fg=Ut(),mg=zr();xc.exports=hg?function(i,e,t){return fg.f(i,e,mg(1,t))}:function(i,e,t){return i[e]=t,i}});var Aa=m((UP,Ac)=>{"use strict";var bg=Ks(),gg=Js(),Pc=bg("keys");Ac.exports=function(i){return Pc[i]||(Pc[i]=gg(i))}});var ka=m((HP,kc)=>{"use strict";kc.exports={}});var un=m((jP,$c)=>{"use strict";var Sg=Pu(),Rc=ie(),vg=De(),yg=hr(),sn=ze(),nn=Yr(),Tg=Aa(),Ig=ka(),wc="Object already initialized",on=Rc.TypeError,Eg=Rc.WeakMap,wa,Kr,Ra,xg=function(i){return Ra(i)?Kr(i):wa(i,{})},Pg=function(i){return function(e){var t;if(!vg(e)||(t=Kr(e)).type!==i)throw new on("Incompatible receiver, "+i+" required");return t}};Sg||nn.state?(Ke=nn.state||(nn.state=new Eg),Ke.get=Ke.get,Ke.has=Ke.has,Ke.set=Ke.set,wa=function(i,e){if(Ke.has(i))throw new on(wc);return e.facade=i,Ke.set(i,e),e},Kr=function(i){return Ke.get(i)||{}},Ra=function(i){return Ke.has(i)}):(Ht=Tg("state"),Ig[Ht]=!0,wa=function(i,e){if(sn(i,Ht))throw new on(wc);return e.facade=i,yg(i,Ht,e),e},Kr=function(i){return sn(i,Ht)?i[Ht]:{}},Ra=function(i){return sn(i,Ht)});var Ke,Ht;$c.exports={set:wa,get:Kr,has:Ra,enforce:xg,getterFor:Pg}});var cn=m((GP,Dc)=>{"use strict";var Ag=qr(),Cc=Function.prototype,Lc=Cc.apply,Mc=Cc.call;Dc.exports=typeof Reflect=="object"&&Reflect.apply||(Ag?Mc.bind(Lc):function(){return Mc.apply(Lc,arguments)})});var ln=m((WP,Bc)=>{"use strict";var kg=ur(),wg=Se();Bc.exports=function(i){if(kg(i)==="Function")return wg(i)}});var Nc=m(_c=>{"use strict";var Vc={}.propertyIsEnumerable,Oc=Object.getOwnPropertyDescriptor,Rg=Oc&&!Vc.call({1:2},1);_c.f=Rg?function(e){var t=Oc(this,e);return!!t&&t.enumerable}:Vc});var Uc=m(qc=>{"use strict";var $g=Be(),Lg=we(),Mg=Nc(),Cg=zr(),Dg=lr(),Bg=Zs(),Vg=ze(),Og=_s(),Fc=Object.getOwnPropertyDescriptor;qc.f=$g?Fc:function(e,t){if(e=Dg(e),t=Bg(t),Og)try{return Fc(e,t)}catch{}if(Vg(e,t))return Cg(!Lg(Mg.f,e,t),e[t])}});var dn=m((zP,Hc)=>{"use strict";var _g=ke(),Ng=re(),Fg=/#|\.prototype\./,Jr=function(i,e){var t=Ug[qg(i)];return t===jg?!0:t===Hg?!1:Ng(e)?_g(e):!!e},qg=Jr.normalize=function(i){return String(i).replace(Fg,".").toLowerCase()},Ug=Jr.data={},Hg=Jr.NATIVE="N",jg=Jr.POLYFILL="P";Hc.exports=Jr});var Xr=m((KP,Gc)=>{"use strict";var jc=ln(),Gg=ht(),Wg=qr(),Yg=jc(jc.bind);Gc.exports=function(i,e){return Gg(i),e===void 0?i:Wg?Yg(i,e):function(){return i.apply(e,arguments)}}});var Ve=m((JP,Yc)=>{"use strict";var Zr=ie(),Qg=cn(),zg=ln(),Kg=re(),Jg=Uc().f,Xg=dn(),fr=Ea(),Zg=Xr(),mr=hr(),Wc=ze();Yr();var eS=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return Qg(i,this,arguments)};return e.prototype=i.prototype,e};Yc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Zr:a?Zr[t]:Zr[t]&&Zr[t].prototype,o=r?fr:fr[t]||mr(fr,t,{})[t],c=o.prototype,u,d,l,p,f,b,g,y,E;for(p in e)u=Xg(r?p:t+(a?".":"#")+p,i.forced),d=!u&&n&&Wc(n,p),b=o[p],d&&(i.dontCallGetSet?(E=Jg(n,p),g=E&&E.value):g=n[p]),f=d&&g?g:e[p],!(!u&&!s&&typeof b==typeof f)&&(i.bind&&d?y=Zg(f,Zr):i.wrap&&d?y=eS(f):s&&Kg(f)?y=zg(f):y=f,(i.sham||f&&f.sham||b&&b.sham)&&mr(y,"sham",!0),mr(o,p,y),s&&(l=t+"Prototype",Wc(fr,l)||mr(fr,l,{}),mr(fr[l],p,f),i.real&&c&&(u||!c[p])&&mr(c,p,f)))}});var Kc=m((XP,zc)=>{"use strict";var pn=Be(),tS=ze(),Qc=Function.prototype,rS=pn&&Object.getOwnPropertyDescriptor,hn=tS(Qc,"name"),iS=hn&&function(){}.name==="something",aS=hn&&(!pn||pn&&rS(Qc,"name").configurable);zc.exports={EXISTS:hn,PROPER:iS,CONFIGURABLE:aS}});var Xc=m((ZP,Jc)=>{"use strict";var sS=Math.ceil,nS=Math.floor;Jc.exports=Math.trunc||function(e){var t=+e;return(t>0?nS:sS)(t)}});var $a=m((eA,Zc)=>{"use strict";var oS=Xc();Zc.exports=function(i){var e=+i;return e!==e||e===0?0:oS(e)}});var tl=m((tA,el)=>{"use strict";var uS=$a(),cS=Math.max,lS=Math.min;el.exports=function(i,e){var t=uS(i);return t<0?cS(t+e,0):lS(t,e)}});var il=m((rA,rl)=>{"use strict";var dS=$a(),pS=Math.min;rl.exports=function(i){var e=dS(i);return e>0?pS(e,9007199254740991):0}});var La=m((iA,al)=>{"use strict";var hS=il();al.exports=function(i){return hS(i.length)}});var ol=m((aA,nl)=>{"use strict";var fS=lr(),mS=tl(),bS=La(),sl=function(i){return function(e,t,r){var a=fS(e),s=bS(a);if(s===0)return!i&&-1;var n=mS(r,s),o;if(i&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};nl.exports={includes:sl(!0),indexOf:sl(!1)}});var ll=m((sA,cl)=>{"use strict";var gS=Se(),fn=ze(),SS=lr(),vS=ol().indexOf,yS=ka(),ul=gS([].push);cl.exports=function(i,e){var t=SS(i),r=0,a=[],s;for(s in t)!fn(yS,s)&&fn(t,s)&&ul(a,s);for(;e.length>r;)fn(t,s=e[r++])&&(~vS(a,s)||ul(a,s));return a}});var mn=m((nA,dl)=>{"use strict";dl.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var hl=m((oA,pl)=>{"use strict";var TS=ll(),IS=mn();pl.exports=Object.keys||function(e){return TS(e,IS)}});var ml=m(fl=>{"use strict";var ES=Be(),xS=Ns(),PS=Ut(),AS=it(),kS=lr(),wS=hl();fl.f=ES&&!xS?Object.defineProperties:function(e,t){AS(e);for(var r=kS(t),a=wS(t),s=a.length,n=0,o;s>n;)PS.f(e,o=a[n++],r[o]);return e}});var bn=m((cA,bl)=>{"use strict";var RS=pt();bl.exports=RS("document","documentElement")});var yn=m((lA,El)=>{"use strict";var $S=it(),LS=ml(),gl=mn(),MS=ka(),CS=bn(),DS=Ta(),BS=Aa(),Sl=">",vl="<",Sn="prototype",vn="script",Tl=BS("IE_PROTO"),gn=function(){},Il=function(i){return vl+vn+Sl+i+vl+"/"+vn+Sl},yl=function(i){i.write(Il("")),i.close();var e=i.parentWindow.Object;return i=null,e},VS=function(){var i=DS("iframe"),e="java"+vn+":",t;return i.style.display="none",CS.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Il("document.F=Object")),t.close(),t.F},Ma,Ca=function(){try{Ma=new ActiveXObject("htmlfile")}catch{}Ca=typeof document<"u"?document.domain&&Ma?yl(Ma):VS():yl(Ma);for(var i=gl.length;i--;)delete Ca[Sn][gl[i]];return Ca()};MS[Tl]=!0;El.exports=Object.create||function(e,t){var r;return e!==null?(gn[Sn]=$S(e),r=new gn,gn[Sn]=null,r[Tl]=e):r=Ca(),t===void 0?r:LS.f(r,t)}});var Pl=m((dA,xl)=>{"use strict";var OS=ke();xl.exports=!OS(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var In=m((pA,kl)=>{"use strict";var _S=ze(),NS=re(),FS=Qr(),qS=Aa(),US=Pl(),Al=qS("IE_PROTO"),Tn=Object,HS=Tn.prototype;kl.exports=US?Tn.getPrototypeOf:function(i){var e=FS(i);if(_S(e,Al))return e[Al];var t=e.constructor;return NS(t)&&e instanceof t?t.prototype:e instanceof Tn?HS:null}});var br=m((hA,wl)=>{"use strict";var jS=hr();wl.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:jS(i,e,t),i}});var An=m((fA,Ll)=>{"use strict";var GS=ke(),WS=re(),YS=De(),QS=yn(),Rl=In(),zS=br(),KS=me(),JS=Qe(),Pn=KS("iterator"),$l=!1,ft,En,xn;[].keys&&(xn=[].keys(),"next"in xn?(En=Rl(Rl(xn)),En!==Object.prototype&&(ft=En)):$l=!0);var XS=!YS(ft)||GS(function(){var i={};return ft[Pn].call(i)!==i});XS?ft={}:JS&&(ft=QS(ft));WS(ft[Pn])||zS(ft,Pn,function(){return this});Ll.exports={IteratorPrototype:ft,BUGGY_SAFARI_ITERATORS:$l}});var Da=m((mA,Cl)=>{"use strict";var ZS=me(),ev=ZS("toStringTag"),Ml={};Ml[ev]="z";Cl.exports=String(Ml)==="[object z]"});var ei=m((bA,Dl)=>{"use strict";var tv=Da(),rv=re(),Ba=ur(),iv=me(),av=iv("toStringTag"),sv=Object,nv=Ba(function(){return arguments}())==="Arguments",ov=function(i,e){try{return i[e]}catch{}};Dl.exports=tv?Ba:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=ov(e=sv(i),av))=="string"?t:nv?Ba(e):(r=Ba(e))==="Object"&&rv(e.callee)?"Arguments":r}});var Vl=m((gA,Bl)=>{"use strict";var uv=Da(),cv=ei();Bl.exports=uv?{}.toString:function(){return"[object "+cv(this)+"]"}});var ti=m((SA,_l)=>{"use strict";var lv=Da(),dv=Ut().f,pv=hr(),hv=ze(),fv=Vl(),mv=me(),Ol=mv("toStringTag");_l.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(hv(a,Ol)||dv(a,Ol,{configurable:!0,value:e}),r&&!lv&&pv(a,"toString",fv))}});var Fl=m((vA,Nl)=>{"use strict";var bv=An().IteratorPrototype,gv=yn(),Sv=zr(),vv=ti(),yv=qt(),Tv=function(){return this};Nl.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=gv(bv,{next:Sv(+!r,t)}),vv(i,a,!1,!0),yv[a]=Tv,i}});var Ul=m((yA,ql)=>{"use strict";var Iv=Se(),Ev=ht();ql.exports=function(i,e,t){try{return Iv(Ev(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var jl=m((TA,Hl)=>{"use strict";var xv=De();Hl.exports=function(i){return xv(i)||i===null}});var Wl=m((IA,Gl)=>{"use strict";var Pv=jl(),Av=String,kv=TypeError;Gl.exports=function(i){if(Pv(i))return i;throw new kv("Can't set "+Av(i)+" as a prototype")}});var kn=m((EA,Yl)=>{"use strict";var wv=Ul(),Rv=De(),$v=Ur(),Lv=Wl();Yl.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=wv(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return $v(a),Lv(s),Rv(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var ad=m((xA,id)=>{"use strict";var Mv=Ve(),Cv=we(),Va=Qe(),td=Kc(),Dv=re(),Bv=Fl(),Ql=In(),zl=kn(),Vv=ti(),Ov=hr(),wn=br(),_v=me(),Kl=qt(),rd=An(),Nv=td.PROPER,Fv=td.CONFIGURABLE,Jl=rd.IteratorPrototype,Oa=rd.BUGGY_SAFARI_ITERATORS,ri=_v("iterator"),Xl="keys",ii="values",Zl="entries",ed=function(){return this};id.exports=function(i,e,t,r,a,s,n){Bv(t,e,r);var o=function(E){if(E===a&&p)return p;if(!Oa&&E&&E in d)return d[E];switch(E){case Xl:return function(){return new t(this,E)};case ii:return function(){return new t(this,E)};case Zl:return function(){return new t(this,E)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,l=d[ri]||d["@@iterator"]||a&&d[a],p=!Oa&&l||o(a),f=e==="Array"&&d.entries||l,b,g,y;if(f&&(b=Ql(f.call(new i)),b!==Object.prototype&&b.next&&(!Va&&Ql(b)!==Jl&&(zl?zl(b,Jl):Dv(b[ri])||wn(b,ri,ed)),Vv(b,c,!0,!0),Va&&(Kl[c]=ed))),Nv&&a===ii&&l&&l.name!==ii&&(!Va&&Fv?Ov(d,"name",ii):(u=!0,p=function(){return Cv(l,this)})),a)if(g={values:o(ii),keys:s?p:o(Xl),entries:o(Zl)},n)for(y in g)(Oa||u||!(y in d))&&wn(d,y,g[y]);else Mv({target:e,proto:!0,forced:Oa||u},g);return(!Va||n)&&d[ri]!==p&&wn(d,ri,p,{name:a}),Kl[e]=p,g}});var nd=m((PA,sd)=>{"use strict";sd.exports=function(i,e){return{value:i,done:e}}});var $n=m((AA,dd)=>{"use strict";var qv=lr(),Rn=Ds(),od=qt(),cd=un(),Uv=Ut().f,Hv=ad(),_a=nd(),jv=Qe(),Gv=Be(),ld="Array Iterator",Wv=cd.set,Yv=cd.getterFor(ld);dd.exports=Hv(Array,"Array",function(i,e){Wv(this,{type:ld,target:qv(i),index:0,kind:e})},function(){var i=Yv(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,_a(void 0,!0);switch(i.kind){case"keys":return _a(t,!1);case"values":return _a(e[t],!1)}return _a([t,e[t]],!1)},"values");var ud=od.Arguments=od.Array;Rn("keys");Rn("values");Rn("entries");if(!jv&&Gv&&ud.name!=="values")try{Uv(ud,"name",{value:"values"})}catch{}});var hd=m((kA,pd)=>{"use strict";var Qv=me(),zv=qt(),Kv=Qv("iterator"),Jv=Array.prototype;pd.exports=function(i){return i!==void 0&&(zv.Array===i||Jv[Kv]===i)}});var Ln=m((wA,md)=>{"use strict";var Xv=ei(),fd=Wr(),Zv=cr(),ey=qt(),ty=me(),ry=ty("iterator");md.exports=function(i){if(!Zv(i))return fd(i,ry)||fd(i,"@@iterator")||ey[Xv(i)]}});var gd=m((RA,bd)=>{"use strict";var iy=we(),ay=ht(),sy=it(),ny=Gr(),oy=Ln(),uy=TypeError;bd.exports=function(i,e){var t=arguments.length<2?oy(i):e;if(ay(t))return sy(iy(t,i));throw new uy(ny(i)+" is not iterable")}});var yd=m(($A,vd)=>{"use strict";var cy=we(),Sd=it(),ly=Wr();vd.exports=function(i,e,t){var r,a;Sd(i);try{if(r=ly(i,"return"),!r){if(e==="throw")throw t;return t}r=cy(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Sd(r),t}});var Fa=m((LA,xd)=>{"use strict";var dy=Xr(),py=we(),hy=it(),fy=Gr(),my=hd(),by=La(),Td=jr(),gy=gd(),Sy=Ln(),Id=yd(),vy=TypeError,Na=function(i,e){this.stopped=i,this.result=e},Ed=Na.prototype;xd.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),c=dy(e,r),u,d,l,p,f,b,g,y=function(C){return u&&Id(u,"normal",C),new Na(!0,C)},E=function(C){return a?(hy(C),o?c(C[0],C[1],y):c(C[0],C[1])):o?c(C,y):c(C)};if(s)u=i.iterator;else if(n)u=i;else{if(d=Sy(i),!d)throw new vy(fy(i)+" is not iterable");if(my(d)){for(l=0,p=by(i);p>l;l++)if(f=E(i[l]),f&&Td(Ed,f))return f;return new Na(!1)}u=gy(i,d)}for(b=s?i.next:u.next;!(g=py(b,u)).done;){try{f=E(g.value)}catch(C){Id(u,"throw",C)}if(typeof f=="object"&&f&&Td(Ed,f))return f}return new Na(!1)}});var Ad=m((MA,Pd)=>{"use strict";var yy=Be(),Ty=Ut(),Iy=zr();Pd.exports=function(i,e,t){yy?Ty.f(i,e,Iy(0,t)):i[e]=t}});var kd=m(()=>{"use strict";var Ey=Ve(),xy=Fa(),Py=Ad();Ey({target:"Object",stat:!0},{fromEntries:function(e){var t={};return xy(e,function(r,a){Py(t,r,a)},{AS_ENTRIES:!0}),t}})});var Rd=m((BA,wd)=>{"use strict";$n();kd();var Ay=Ea();wd.exports=Ay.Object.fromEntries});var Ld=m((VA,$d)=>{"use strict";$d.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 Cd=m(()=>{"use strict";$n();var ky=Ld(),wy=ie(),Ry=ti(),Md=qt();for(qa in ky)Ry(wy[qa],qa),Md[qa]=Md.Array;var qa});var Bd=m((NA,Dd)=>{"use strict";var $y=Rd();Cd();Dd.exports=$y});var Mn=m((FA,Vd)=>{"use strict";var Ly=Bd();Vd.exports=Ly});var Od=m(()=>{"use strict"});var Cn=m((HA,_d)=>{"use strict";var ai=ie(),My=dr(),Cy=ur(),Ua=function(i){return My.slice(0,i.length)===i};_d.exports=function(){return Ua("Bun/")?"BUN":Ua("Cloudflare-Workers")?"CLOUDFLARE":Ua("Deno/")?"DENO":Ua("Node.js/")?"NODE":ai.Bun&&typeof Bun.version=="string"?"BUN":ai.Deno&&typeof Deno.version=="object"?"DENO":Cy(ai.process)==="process"?"NODE":ai.window&&ai.document?"BROWSER":"REST"}()});var Ha=m((jA,Nd)=>{"use strict";var Dy=Cn();Nd.exports=Dy==="NODE"});var qd=m((GA,Fd)=>{"use strict";var By=Ut();Fd.exports=function(i,e,t){return By.f(i,e,t)}});var jd=m((WA,Hd)=>{"use strict";var Vy=pt(),Oy=qd(),_y=me(),Ny=Be(),Ud=_y("species");Hd.exports=function(i){var e=Vy(i);Ny&&e&&!e[Ud]&&Oy(e,Ud,{configurable:!0,get:function(){return this}})}});var Wd=m((YA,Gd)=>{"use strict";var Fy=jr(),qy=TypeError;Gd.exports=function(i,e){if(Fy(e,i))return i;throw new qy("Incorrect invocation")}});var Bn=m((QA,Yd)=>{"use strict";var Uy=Se(),Hy=re(),Dn=Yr(),jy=Uy(Function.toString);Hy(Dn.inspectSource)||(Dn.inspectSource=function(i){return jy(i)});Yd.exports=Dn.inspectSource});var Zd=m((zA,Xd)=>{"use strict";var Gy=Se(),Wy=ke(),Qd=re(),Yy=ei(),Qy=pt(),zy=Bn(),zd=function(){},Kd=Qy("Reflect","construct"),Vn=/^\s*(?:class|function)\b/,Ky=Gy(Vn.exec),Jy=!Vn.test(zd),si=function(e){if(!Qd(e))return!1;try{return Kd(zd,[],e),!0}catch{return!1}},Jd=function(e){if(!Qd(e))return!1;switch(Yy(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jy||!!Ky(Vn,zy(e))}catch{return!0}};Jd.sham=!0;Xd.exports=!Kd||Wy(function(){var i;return si(si.call)||!si(Object)||!si(function(){i=!0})||i})?Jd:si});var tp=m((KA,ep)=>{"use strict";var Xy=Zd(),Zy=Gr(),eT=TypeError;ep.exports=function(i){if(Xy(i))return i;throw new eT(Zy(i)+" is not a constructor")}});var On=m((JA,ip)=>{"use strict";var rp=it(),tT=tp(),rT=cr(),iT=me(),aT=iT("species");ip.exports=function(i,e){var t=rp(i).constructor,r;return t===void 0||rT(r=rp(t)[aT])?e:tT(r)}});var sp=m((XA,ap)=>{"use strict";var sT=Se();ap.exports=sT([].slice)});var op=m((ZA,np)=>{"use strict";var nT=TypeError;np.exports=function(i,e){if(i<e)throw new nT("Not enough arguments");return i}});var _n=m((ek,up)=>{"use strict";var oT=dr();up.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(oT)});var Yn=m((tk,gp)=>{"use strict";var Re=ie(),uT=cn(),cT=Xr(),cp=re(),lT=ze(),bp=ke(),lp=bn(),dT=sp(),dp=Ta(),pT=op(),hT=_n(),fT=Ha(),jn=Re.setImmediate,Gn=Re.clearImmediate,mT=Re.process,Nn=Re.Dispatch,bT=Re.Function,pp=Re.MessageChannel,gT=Re.String,Fn=0,ni={},hp="onreadystatechange",oi,jt,qn,Un;bp(function(){oi=Re.location});var Wn=function(i){if(lT(ni,i)){var e=ni[i];delete ni[i],e()}},Hn=function(i){return function(){Wn(i)}},fp=function(i){Wn(i.data)},mp=function(i){Re.postMessage(gT(i),oi.protocol+"//"+oi.host)};(!jn||!Gn)&&(jn=function(e){pT(arguments.length,1);var t=cp(e)?e:bT(e),r=dT(arguments,1);return ni[++Fn]=function(){uT(t,void 0,r)},jt(Fn),Fn},Gn=function(e){delete ni[e]},fT?jt=function(i){mT.nextTick(Hn(i))}:Nn&&Nn.now?jt=function(i){Nn.now(Hn(i))}:pp&&!hT?(qn=new pp,Un=qn.port2,qn.port1.onmessage=fp,jt=cT(Un.postMessage,Un)):Re.addEventListener&&cp(Re.postMessage)&&!Re.importScripts&&oi&&oi.protocol!=="file:"&&!bp(mp)?(jt=mp,Re.addEventListener("message",fp,!1)):hp in dp("script")?jt=function(i){lp.appendChild(dp("script"))[hp]=function(){lp.removeChild(this),Wn(i)}}:jt=function(i){setTimeout(Hn(i),0)});gp.exports={set:jn,clear:Gn}});var yp=m((rk,vp)=>{"use strict";var Sp=ie(),ST=Be(),vT=Object.getOwnPropertyDescriptor;vp.exports=function(i){if(!ST)return Sp[i];var e=vT(Sp,i);return e&&e.value}});var Qn=m((ik,Ip)=>{"use strict";var Tp=function(){this.head=null,this.tail=null};Tp.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};Ip.exports=Tp});var xp=m((ak,Ep)=>{"use strict";var yT=dr();Ep.exports=/ipad|iphone|ipod/i.test(yT)&&typeof Pebble<"u"});var Ap=m((sk,Pp)=>{"use strict";var TT=dr();Pp.exports=/web0s(?!.*chrome)/i.test(TT)});var Cp=m((nk,Mp)=>{"use strict";var Sr=ie(),IT=yp(),kp=Xr(),zn=Yn().set,ET=Qn(),xT=_n(),PT=xp(),AT=Ap(),Kn=Ha(),wp=Sr.MutationObserver||Sr.WebKitMutationObserver,Rp=Sr.document,$p=Sr.process,ja=Sr.Promise,Zn=IT("queueMicrotask"),gr,Jn,Xn,Ga,Lp;Zn||(ui=new ET,ci=function(){var i,e;for(Kn&&(i=$p.domain)&&i.exit();e=ui.get();)try{e()}catch(t){throw ui.head&&gr(),t}i&&i.enter()},!xT&&!Kn&&!AT&&wp&&Rp?(Jn=!0,Xn=Rp.createTextNode(""),new wp(ci).observe(Xn,{characterData:!0}),gr=function(){Xn.data=Jn=!Jn}):!PT&&ja&&ja.resolve?(Ga=ja.resolve(void 0),Ga.constructor=ja,Lp=kp(Ga.then,Ga),gr=function(){Lp(ci)}):Kn?gr=function(){$p.nextTick(ci)}:(zn=kp(zn,Sr),gr=function(){zn(ci)}),Zn=function(i){ui.head||gr(),ui.add(i)});var ui,ci;Mp.exports=Zn});var Bp=m((ok,Dp)=>{"use strict";Dp.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var Wa=m((uk,Vp)=>{"use strict";Vp.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Gt=m((ck,Op)=>{"use strict";var kT=ie();Op.exports=kT.Promise});var vr=m((lk,qp)=>{"use strict";var wT=ie(),li=Gt(),RT=re(),$T=dn(),LT=Bn(),MT=me(),_p=Cn(),CT=Qe(),eo=Hs(),Np=li&&li.prototype,DT=MT("species"),to=!1,Fp=RT(wT.PromiseRejectionEvent),BT=$T("Promise",function(){var i=LT(li),e=i!==String(li);if(!e&&eo===66||CT&&!(Np.catch&&Np.finally))return!0;if(!eo||eo<51||!/native code/.test(i)){var t=new li(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[DT]=r,to=t.then(function(){})instanceof r,!to)return!0}return!e&&(_p==="BROWSER"||_p==="DENO")&&!Fp});qp.exports={CONSTRUCTOR:BT,REJECTION_EVENT:Fp,SUBCLASSING:to}});var yr=m((dk,Hp)=>{"use strict";var Up=ht(),VT=TypeError,OT=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new VT("Bad Promise constructor");e=r,t=a}),this.resolve=Up(e),this.reject=Up(t)};Hp.exports.f=function(i){return new OT(i)}});var uh=m(()=>{"use strict";var _T=Ve(),NT=Qe(),Ka=Ha(),$t=ie(),xr=we(),jp=br(),Gp=kn(),FT=ti(),qT=jd(),UT=ht(),za=re(),HT=De(),jT=Wd(),GT=On(),Kp=Yn().set,no=Cp(),WT=Bp(),YT=Wa(),QT=Qn(),Jp=un(),Ja=Gt(),oo=vr(),Xp=yr(),Xa="Promise",Zp=oo.CONSTRUCTOR,zT=oo.REJECTION_EVENT,KT=oo.SUBCLASSING,ro=Jp.getterFor(Xa),JT=Jp.set,Tr=Ja&&Ja.prototype,Wt=Ja,Ya=Tr,eh=$t.TypeError,io=$t.document,uo=$t.process,ao=Xp.f,XT=ao,ZT=!!(io&&io.createEvent&&$t.dispatchEvent),th="unhandledrejection",eI="rejectionhandled",Wp=0,rh=1,tI=2,co=1,ih=2,Qa,Yp,rI,Qp,ah=function(i){var e;return HT(i)&&za(e=i.then)?e:!1},sh=function(i,e){var t=e.value,r=e.state===rh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,c,u,d;try{a?(r||(e.rejection===ih&&aI(e),e.rejection=co),a===!0?c=t:(o&&o.enter(),c=a(t),o&&(o.exit(),d=!0)),c===i.promise?n(new eh("Promise-chain cycle")):(u=ah(c))?xr(u,c,s,n):s(c)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},nh=function(i,e){i.notified||(i.notified=!0,no(function(){for(var t=i.reactions,r;r=t.get();)sh(r,i);i.notified=!1,e&&!i.rejection&&iI(i)}))},oh=function(i,e,t){var r,a;ZT?(r=io.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),$t.dispatchEvent(r)):r={promise:e,reason:t},!zT&&(a=$t["on"+i])?a(r):i===th&&WT("Unhandled promise rejection",t)},iI=function(i){xr(Kp,$t,function(){var e=i.facade,t=i.value,r=zp(i),a;if(r&&(a=YT(function(){Ka?uo.emit("unhandledRejection",t,e):oh(th,e,t)}),i.rejection=Ka||zp(i)?ih:co,a.error))throw a.value})},zp=function(i){return i.rejection!==co&&!i.parent},aI=function(i){xr(Kp,$t,function(){var e=i.facade;Ka?uo.emit("rejectionHandled",e):oh(eI,e,i.value)})},Ir=function(i,e,t){return function(r){i(e,r,t)}},Er=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=tI,nh(i,!0))},so=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new eh("Promise can't be resolved itself");var r=ah(e);r?no(function(){var a={done:!1};try{xr(r,e,Ir(so,a,i),Ir(Er,a,i))}catch(s){Er(a,s,i)}}):(i.value=e,i.state=rh,nh(i,!1))}catch(a){Er({done:!1},a,i)}}};if(Zp&&(Wt=function(e){jT(this,Ya),UT(e),xr(Qa,this);var t=ro(this);try{e(Ir(so,t),Ir(Er,t))}catch(r){Er(t,r)}},Ya=Wt.prototype,Qa=function(e){JT(this,{type:Xa,done:!1,notified:!1,parent:!1,reactions:new QT,rejection:!1,state:Wp,value:void 0})},Qa.prototype=jp(Ya,"then",function(e,t){var r=ro(this),a=ao(GT(this,Wt));return r.parent=!0,a.ok=za(e)?e:!0,a.fail=za(t)&&t,a.domain=Ka?uo.domain:void 0,r.state===Wp?r.reactions.add(a):no(function(){sh(a,r)}),a.promise}),Yp=function(){var i=new Qa,e=ro(i);this.promise=i,this.resolve=Ir(so,e),this.reject=Ir(Er,e)},Xp.f=ao=function(i){return i===Wt||i===rI?new Yp(i):XT(i)},!NT&&za(Ja)&&Tr!==Object.prototype)){Qp=Tr.then,KT||jp(Tr,"then",function(e,t){var r=this;return new Wt(function(a,s){xr(Qp,r,a,s)}).then(e,t)},{unsafe:!0});try{delete Tr.constructor}catch{}Gp&&Gp(Tr,Ya)}_T({global:!0,constructor:!0,wrap:!0,forced:Zp},{Promise:Wt});FT(Wt,Xa,!1,!0);qT(Xa)});var hh=m((fk,ph)=>{"use strict";var sI=me(),lh=sI("iterator"),dh=!1;try{ch=0,lo={next:function(){return{done:!!ch++}},return:function(){dh=!0}},lo[lh]=function(){return this},Array.from(lo,function(){throw 2})}catch{}var ch,lo;ph.exports=function(i,e){try{if(!e&&!dh)return!1}catch{return!1}var t=!1;try{var r={};r[lh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var po=m((mk,fh)=>{"use strict";var nI=Gt(),oI=hh(),uI=vr().CONSTRUCTOR;fh.exports=uI||!oI(function(i){nI.all(i).then(void 0,function(){})})});var mh=m(()=>{"use strict";var cI=Ve(),lI=we(),dI=ht(),pI=yr(),hI=Wa(),fI=Fa(),mI=po();cI({target:"Promise",stat:!0,forced:mI},{all:function(e){var t=this,r=pI.f(t),a=r.resolve,s=r.reject,n=hI(function(){var o=dI(t.resolve),c=[],u=0,d=1;fI(e,function(l){var p=u++,f=!1;d++,lI(o,t,l).then(function(b){f||(f=!0,c[p]=b,--d||a(c))},s)}),--d||a(c)});return n.error&&s(n.value),r.promise}})});var gh=m(()=>{"use strict";var bI=Ve(),gI=Qe(),SI=vr().CONSTRUCTOR,fo=Gt(),vI=pt(),yI=re(),TI=br(),bh=fo&&fo.prototype;bI({target:"Promise",proto:!0,forced:SI,real:!0},{catch:function(i){return this.then(void 0,i)}});!gI&&yI(fo)&&(ho=vI("Promise").prototype.catch,bh.catch!==ho&&TI(bh,"catch",ho,{unsafe:!0}));var ho});var Sh=m(()=>{"use strict";var II=Ve(),EI=we(),xI=ht(),PI=yr(),AI=Wa(),kI=Fa(),wI=po();II({target:"Promise",stat:!0,forced:wI},{race:function(e){var t=this,r=PI.f(t),a=r.reject,s=AI(function(){var n=xI(t.resolve);kI(e,function(o){EI(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var vh=m(()=>{"use strict";var RI=Ve(),$I=yr(),LI=vr().CONSTRUCTOR;RI({target:"Promise",stat:!0,forced:LI},{reject:function(e){var t=$I.f(this),r=t.reject;return r(e),t.promise}})});var mo=m((xk,yh)=>{"use strict";var MI=it(),CI=De(),DI=yr();yh.exports=function(i,e){if(MI(i),CI(e)&&e.constructor===i)return e;var t=DI.f(i),r=t.resolve;return r(e),t.promise}});var Eh=m(()=>{"use strict";var BI=Ve(),VI=pt(),Th=Qe(),OI=Gt(),Ih=vr().CONSTRUCTOR,_I=mo(),NI=VI("Promise"),FI=Th&&!Ih;BI({target:"Promise",stat:!0,forced:Th||Ih},{resolve:function(e){return _I(FI&&this===NI?OI:this,e)}})});var xh=m(()=>{"use strict";uh();mh();gh();Sh();vh();Eh()});var wh=m(()=>{"use strict";var qI=Ve(),UI=Qe(),Za=Gt(),HI=ke(),Ah=pt(),kh=re(),jI=On(),Ph=mo(),GI=br(),go=Za&&Za.prototype,WI=!!Za&&HI(function(){go.finally.call({then:function(){}},function(){})});qI({target:"Promise",proto:!0,real:!0,forced:WI},{finally:function(i){var e=jI(this,Ah("Promise")),t=kh(i);return this.then(t?function(r){return Ph(e,i()).then(function(){return r})}:i,t?function(r){return Ph(e,i()).then(function(){throw r})}:i)}});!UI&&kh(Za)&&(bo=Ah("Promise").prototype.finally,go.finally!==bo&&GI(go,"finally",bo,{unsafe:!0}));var bo});var es=m((Lk,Rh)=>{"use strict";var YI=pt();Rh.exports=YI});var Lh=m((Mk,$h)=>{"use strict";Od();xh();wh();var QI=es();$h.exports=QI("Promise","finally")});var Ch=m((Ck,Mh)=>{"use strict";var zI=Lh();Mh.exports=zI});var ts=m((Dk,Dh)=>{"use strict";var KI=Ch();Dh.exports=KI});var jh=m(()=>{"use strict";var aE=Ve(),sE=Qr(),nE=La(),oE=$a(),uE=Ds();aE({target:"Array",proto:!0},{at:function(e){var t=sE(this),r=nE(t),a=oE(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});uE("at")});var Wh=m((Mw,Gh)=>{"use strict";jh();var cE=es();Gh.exports=cE("Array","at")});var Qh=m((Cw,Yh)=>{"use strict";var lE=Wh();Yh.exports=lE});var pi=m((Dw,zh)=>{"use strict";var dE=Qh();zh.exports=dE});var Lf=m(()=>{"use strict"});var Mf=m(()=>{"use strict"});var Df=m((IM,Cf)=>{"use strict";var GE=De(),WE=ur(),YE=me(),QE=YE("match");Cf.exports=function(i){var e;return GE(i)&&((e=i[QE])!==void 0?!!e:WE(i)==="RegExp")}});var Vf=m((EM,Bf)=>{"use strict";var zE=ei(),KE=String;Bf.exports=function(i){if(zE(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return KE(i)}});var _f=m((xM,Of)=>{"use strict";var JE=it();Of.exports=function(){var i=JE(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var qf=m((PM,Ff)=>{"use strict";var XE=we(),ZE=ze(),ex=jr(),tx=_f(),Nf=RegExp.prototype;Ff.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Nf)&&!ZE(i,"flags")&&ex(Nf,i)?XE(tx,i):e}});var Hf=m((AM,Uf)=>{"use strict";var Fo=Se(),rx=Qr(),ix=Math.floor,_o=Fo("".charAt),ax=Fo("".replace),No=Fo("".slice),sx=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,nx=/\$([$&'`]|\d{1,2})/g;Uf.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,c=nx;return a!==void 0&&(a=rx(a),c=sx),ax(s,c,function(u,d){var l;switch(_o(d,0)){case"$":return"$";case"&":return i;case"`":return No(e,0,t);case"'":return No(e,n);case"<":l=a[No(d,1,-1)];break;default:var p=+d;if(p===0)return u;if(p>o){var f=ix(p/10);return f===0?u:f<=o?r[f-1]===void 0?_o(d,1):r[f-1]+_o(d,1):u}l=r[p-1]}return l===void 0?"":l})}});var Wf=m(()=>{"use strict";var ox=Ve(),ux=we(),Uo=Se(),jf=Ur(),cx=re(),lx=cr(),dx=Df(),Cr=Vf(),px=Wr(),hx=qf(),fx=Hf(),mx=me(),bx=Qe(),gx=mx("replace"),Sx=TypeError,qo=Uo("".indexOf),vx=Uo("".replace),Gf=Uo("".slice),yx=Math.max;ox({target:"String",proto:!0},{replaceAll:function(e,t){var r=jf(this),a,s,n,o,c,u,d,l,p,f,b=0,g="";if(!lx(e)){if(a=dx(e),a&&(s=Cr(jf(hx(e))),!~qo(s,"g")))throw new Sx("`.replaceAll` does not allow non-global regexes");if(n=px(e,gx),n)return ux(n,e,r,t);if(bx&&a)return vx(Cr(r),e,t)}for(o=Cr(r),c=Cr(e),u=cx(t),u||(t=Cr(t)),d=c.length,l=yx(1,d),p=qo(o,c);p!==-1;)f=u?Cr(t(c,p,o)):fx(c,o,p,[],void 0,t),g+=Gf(o,b,p)+f,b=p+d,p=p+l>o.length?-1:qo(o,c,p+l);return b<o.length&&(g+=Gf(o,b)),g}})});var Qf=m((RM,Yf)=>{"use strict";Lf();Mf();Wf();var Tx=es();Yf.exports=Tx("String","replaceAll")});var Kf=m(($M,zf)=>{"use strict";var Ix=Qf();zf.exports=Ix});var Xf=m((LM,Jf)=>{"use strict";var Ex=Kf();Jf.exports=Ex});var _x={};Fm(_x,{ChromecastState:()=>Fr,HttpConnectionType:()=>Sa,Observable:()=>ut.Observable,PlaybackState:()=>fe,Player:()=>la,SDK_VERSION:()=>Ox,Subject:()=>ut.Subject,Subscription:()=>ut.Subscription,Surface:()=>va,VERSION:()=>Ls,ValueSubject:()=>ut.ValueSubject,VideoFormat:()=>dt,VideoQuality:()=>ut.VideoQuality});module.exports=qm(_x);var Ls="2.0.108-dev.9969cb23.0";var fe=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(fe||{}),dt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(dt||{});var Fr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Fr||{}),Sa=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Sa||{});var va=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(va||{});var F=require("@vkontakte/videoplayer-shared");var nu=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var ya=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;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 r=(0,F.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||nu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,F.assertNever)(a.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,F.map)(a=>a.castState)),(0,F.observableFrom)([r.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(Um),(0,F.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();(0,F.assertNonNullable)(o);let c=o.getCastDevice(),u=o.getMediaSession()?.media?.contentId;((0,F.isNullable)(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?(0,F.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Um=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,F.assertNever)(i)}};var vm=We(Mn(),1);var _h=We(ts(),1);var So=require("@vkontakte/videoplayer-shared");var de=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,So.assertNever)(t)}return i},vo=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:(0,So.assertNever)(e)}};var A=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};var at=require("@vkontakte/videoplayer-shared"),H=class{constructor(e){this.transitionStarted$=new at.Subject;this.transitionEnded$=new at.Subject;this.transitionUpdated$=new at.Subject;this.forceChanged$=new at.Subject;this.stateChangeStarted$=(0,at.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,at.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,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:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,at.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Bh=require("@vkontakte/videoplayer-shared"),Vh=i=>{switch(i){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Bh.assertNever)(i)}};var R=require("@vkontakte/videoplayer-shared");var JI=5,XI=5,ZI=500,Oh=7e3,di=class{constructor(e){this.subscription=new R.Subscription;this.loadMediaTimeoutSubscription=new R.Subscription;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}default:(0,R.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Vh(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 R.Subscription;this.subscription.add(e),this.subscription.add((0,R.merge)(this.videoState.stateChangeStarted$.pipe((0,R.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,R.map)(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new R.Subject;e.add(a.pipe((0,R.debounce)(ZI)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>JI)&&a.next(o),s=o})),e.add((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<XI&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,R.assertNever)(n)}}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=(0,R.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,R.observableFrom)(["init"])).pipe((0,R.debounce)(0));t(r,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"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?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),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];(0,R.assertNonNullable)(u);let d=(0,R.getHighestQuality)(Object.keys(u));(0,R.assertNonNullable)(d);let l=u[d];(0,R.assertNonNullable)(l),r=l,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];(0,R.assertNonNullable)(u),r=u.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let u=t[e];(0,R.assertNonNullable)(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];(0,R.assertNonNullable)(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];(0,R.assertNonNullable)(u),r=de(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",d=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.ErrorCategory.VIDEO_PIPELINE,message:u,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,R.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:c}=this.params.meta;return(0,R.isNonNullable)(o)&&(n.metadata.title=o),(0,R.isNonNullable)(c)&&(n.metadata.subtitle=c),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add((0,R.timeout)(Oh).subscribe(()=>s(`timeout(${Oh})`)))});(0,_h.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:R.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Eo=require("@vkontakte/videoplayer-shared");var Nh=require("@vkontakte/videoplayer-shared"),Fh=i=>{try{i.pause(),i.playbackRate=0,(0,Nh.clearVideoElement)(i),i.remove()}catch(e){console.error(e)}};var rs=require("@vkontakte/videoplayer-shared"),yo=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},To=window.WeakMap?new WeakMap:new yo,Io=window.WeakMap?new WeakMap:new Map,eE=(i,e=20)=>{let t=0;return(0,rs.fromEvent)(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},ve=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?(0,Eo.clearVideoElement)(t):(t=document.createElement("video"),i.appendChild(t)),To.set(t,r);let a=new rs.Subscription;return a.add(eE(t,e)),Io.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ye=i=>{Io.get(i)?.unsubscribe(),Io.delete(i);let t=To.get(i);To.delete(i),t?(0,Eo.clearVideoElement)(i):Fh(i)};var $=require("@vkontakte/videoplayer-shared");var Lt=require("@vkontakte/videoplayer-shared"),is=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),c=(0,Lt.isNullable)(a),u=new Lt.Subscription;return a&&u.add(a.subscribe(d=>{let l=i.getState();r(d,l)&&i.setState(d)},s)),r(o,n)||(t(n),c&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),c&&i.setState(d.to)},s)),u},st=(i,e,t)=>is(e,()=>i.loop,r=>{(0,Lt.isNonNullable)(r)&&(i.loop=r)},{onError:t}),Te=(i,e,t,r)=>is(e,()=>({muted:i.muted,volume:i.volume}),a=>{(0,Lt.isNonNullable)(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),Oe=(i,e,t,r)=>is(e,()=>i.playbackRate,a=>{(0,Lt.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),Mt=is;var tE=i=>["__",i.language,i.label].join("|"),rE=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},xo=class i{constructor(){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:$.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Mt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,$.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Mt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,$.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Mt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:a})),this.subscription.add(Mt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,$.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,$.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,$.filterChanged)()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add((0,$.fromEvent)(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;(0,$.isNonNullable)(t.align)&&(a.align=t.align),(0,$.isNonNullable)(t.position)&&(a.position=t.position),(0,$.isNonNullable)(t.size)&&(a.size=t.size),(0,$.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:tE(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.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(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!rE(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,$.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,$.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.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)}},_e=xo;var bt=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 qh=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Po=i=>{let e=qh(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Uh=i=>{let e=qh(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var M=require("@vkontakte/videoplayer-shared");var iE=3,Hh=(i,e,t=iE)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let c=s-1;c>=0;c--)i.end(c)+t>=r&&(r=i.start(c));for(let c=s+1;c<i.length;c++)i.start(c)-t<=a&&(a=i.end(c))}}return{from:r,to:a}};var Ie=i=>{let e=x=>(0,M.fromEvent)(i,x).pipe((0,M.mapTo)(void 0)),r=(0,M.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,M.fromEvent)(i,x))).pipe((0,M.map)(x=>x.type==="ended"?i.readyState<2:i.readyState<3),(0,M.filterChanged)()),a=(0,M.merge)((0,M.fromEvent)(i,"progress"),(0,M.fromEvent)(i,"timeupdate")).pipe((0,M.map)(()=>Hh(i.buffered,i.currentTime))),s=M.clientChecker.isSafari?(0,M.combine)({play:e("play").pipe((0,M.once)()),playing:e("playing")}).pipe((0,M.mapTo)(void 0)):e("playing"),n=(0,M.fromEvent)(i,"volumechange").pipe((0,M.map)(()=>({muted:i.muted,volume:i.volume}))),o=(0,M.fromEvent)(i,"ratechange").pipe((0,M.map)(()=>i.playbackRate)),c=(0,M.fromEvent)(i,"error").pipe((0,M.filter)(()=>!!(i.error||i.played.length)),(0,M.map)(()=>{let x=i.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:M.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=(0,M.fromEvent)(i,"timeupdate").pipe((0,M.map)(()=>i.currentTime)),d=new M.Subject,l=.3,p;u.subscribe(x=>{i.loop&&(0,M.isNonNullable)(p)&&(0,M.isNonNullable)(x)&&p>=i.duration-l&&x<=l&&d.next(p),p=x});let f=e("pause").pipe((0,M.filter)(()=>!i.error&&p!==i.duration)),b=(0,M.fromEvent)(i,"enterpictureinpicture"),g=(0,M.fromEvent)(i,"leavepictureinpicture"),y=new M.ValueSubject(Uh(i));b.subscribe(()=>y.next(!0)),g.subscribe(()=>y.next(!1));let E=new M.ValueSubject(Po(i));return(0,M.fromEvent)(i,"fullscreenchange").pipe((0,M.map)(()=>Po(i))).subscribe(E),{playing$:s,pause$:f,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:(0,M.fromEvent)(i,"durationchange").pipe((0,M.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:y,inFullscreen$:E}};var gt=require("@vkontakte/videoplayer-shared"),Ct=i=>{switch(i){case"mobile":return gt.VideoQuality.Q_144P;case"lowest":return gt.VideoQuality.Q_240P;case"low":return gt.VideoQuality.Q_360P;case"sd":case"medium":return gt.VideoQuality.Q_480P;case"hd":case"high":return gt.VideoQuality.Q_720P;case"fullhd":case"full":return gt.VideoQuality.Q_1080P;case"quadhd":case"quad":return gt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return gt.VideoQuality.Q_2160P}};var Yt=We(pi(),1),V=require("@vkontakte/videoplayer-shared");var Ao=!1,St={},Kh=i=>{Ao=i},Jh=()=>{St={}},Xh=i=>{i(St)},hi=(i,e)=>{Ao&&(St.meta=St.meta??{},St.meta[i]=e)},be=class{constructor(e){this.name=e}next(e){if(!Ao)return;St.series=St.series??{};let t=St.series[this.name]??[];t.push([Date.now(),e]),St.series[this.name]=t}};var pE=new be("best_bitrate"),ef=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var ko=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),fi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,V.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},tf='Assertion "ABR Tracks is empty array" failed',as=(i,e,t,r)=>{let a=[...e].sort(ko(1)),s=[...t].sort(ko(1)),n=s.filter(c=>(0,V.isNonNullable)(c.bitrate)&&(0,V.isNonNullable)(i.bitrate)?i.bitrate/c.bitrate>r:!0),o=(0,Yt.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,Yt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Yt.default)(n,-1):(0,Yt.default)(s,0)},Zh=i=>"quality"in i,rf=(i,e,t,r)=>{let a=t&&r&&r.history[t.id]&&(0,V.now)()-r.history[t.id]<=i.trackCooldown&&(!r.last||t.id!==r.last.id);if(t?.id&&r&&!a&&r.recordSelection(t),a&&r?.last){let s=r.last;r?.recordSwitch(s);let n=Zh(s)?"video":"audio",o=Zh(s)?s.quality:s.bitrate;return e({message:`
|
|
7
|
+
[last ${n} selected] ${o}
|
|
8
|
+
`}),s}return r?.recordSwitch(t),t},Dt=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:c,history:u,visible:d,droppedVideoMaxQualityLimit:l,abrLogger:p})=>{(0,V.assertNotEmptyArray)(i,tf);let f=r.usePixelRatio?window.devicePixelRatio??1:1,b=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*r.containerSizeFactor,height:e.height*f*r.containerSizeFactor},g=b&&(0,V.videoSizeToQuality)(b),y=r.considerPlaybackRate&&(0,V.isNonNullable)(o)?o:1,E=i.filter(D=>!(0,V.isInvariantQuality)(D.quality)).sort((D,B)=>(0,V.isHigher)(D.quality,B.quality)?-1:1),C=(0,Yt.default)(E,-1)?.quality,x=(0,Yt.default)(E,0)?.quality,T=(0,V.isNullable)(a)||(0,V.isNonNullable)(a.min)&&(0,V.isNonNullable)(a.max)&&(0,V.isLower)(a.max,a.min)||(0,V.isNonNullable)(a.min)&&x&&(0,V.isHigher)(a.min,x)||(0,V.isNonNullable)(a.max)&&C&&(0,V.isLower)(a.max,C),P=y*ef(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),k={},z=E.filter(D=>{if(!(g?(0,V.isLower)(D.quality,g):!0))return k[D.quality]="FitsContainer",!1;if(!((0,V.isNonNullable)(t)&&isFinite(t)&&(0,V.isNonNullable)(D.bitrate)?t-s>=D.bitrate*P:!0))return k[D.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,V.isNonNullable)(r.minBufferToSwitchUp)&&c&&!(0,V.isInvariantQuality)(c.quality)&&(n??0)<r.minBufferToSwitchUp&&(0,V.isHigher)(D.quality,c.quality))return k[D.quality]="Buffer",!1;if(!!l&&(0,V.isHigherOrEqual)(D.quality,l))return k[D.quality]="DroppedFramesLimit",!1;let ge=T||((0,V.isNullable)(a.max)||(0,V.isLowerOrEqual)(D.quality,a.max))&&((0,V.isNullable)(a.min)||(0,V.isHigherOrEqual)(D.quality,a.min)),w=(0,V.isNonNullable)(d)&&!d?(0,V.isLowerOrEqual)(D.quality,r.backgroundVideoQualityLimit):!0;return!ge||!w?(k[D.quality]="FitsQualityLimits",!1):!0})[0];z&&z.bitrate&&pE.next(z.bitrate);let X=z??E[Math.ceil((E.length-1)/2)]??i[0];return X.quality!==u?.last?.quality&&p({message:`
|
|
9
|
+
[VIDEO TRACKS ABR]
|
|
10
|
+
[available video tracks]
|
|
11
|
+
${i.map(D=>`{ id: ${D.id}, quality: ${D.quality}, bitrate: ${D.bitrate} }`).join(`
|
|
9
12
|
`)}
|
|
10
13
|
|
|
11
14
|
[tuning]
|
|
12
|
-
${Object.entries(r??{}).map(([
|
|
15
|
+
${Object.entries(r??{}).map(([D,B])=>`${D}: ${B}`).join(`
|
|
13
16
|
`)}
|
|
14
17
|
|
|
15
18
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
19
|
+
containerQualityLimit: ${g},
|
|
17
20
|
throughput: ${t},
|
|
18
21
|
reserve: ${s},
|
|
19
22
|
playbackRate: ${o},
|
|
20
|
-
playbackRateFactor: ${
|
|
23
|
+
playbackRateFactor: ${y},
|
|
21
24
|
forwardBufferHealth: ${n},
|
|
22
|
-
bitrateFactor: ${
|
|
25
|
+
bitrateFactor: ${P},
|
|
23
26
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
24
|
-
droppedVideoMaxQualityLimit: ${
|
|
25
|
-
limitsAreInvalid: ${
|
|
27
|
+
droppedVideoMaxQualityLimit: ${l},
|
|
28
|
+
limitsAreInvalid: ${T},
|
|
26
29
|
maxQualityLimit: ${a?.max},
|
|
27
30
|
minQualityLimit: ${a?.min},
|
|
28
31
|
|
|
29
|
-
[limited tracks]
|
|
30
|
-
${Object.entries(
|
|
32
|
+
[limited video tracks]
|
|
33
|
+
${Object.entries(k).map(([D,B])=>`${D}: ${B}`).join(`
|
|
31
34
|
`)||"All tracks are available"}
|
|
32
35
|
|
|
33
|
-
[best track] ${
|
|
34
|
-
[selected track] ${
|
|
35
|
-
`});let
|
|
36
|
-
[
|
|
37
|
-
`}),w}return u?.recordSwitch(Q),Q},Et=nE;var oe=i=>new URL(i).hostname;var V=require("@vkontakte/videoplayer-shared");var Hh=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},ye=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Hh(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Hh(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};var we=require("@vkontakte/videoplayer-shared");var Xe=require("@vkontakte/videoplayer-shared");function ue(){return(0,Xe.now)()}function vo(i){return ue()-i}function yo(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,l=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return l&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function jh(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function mr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,d,c,h=!1,f="arraybuffer",b=7e3,S=2e3,y=()=>{if(l)return;(0,Xe.assertNonNullable)(d);let N=vo(d),ee;if(N<S){ee=S-N,setTimeout(y,ee);return}S*=2,S>b&&(S=b),n&&n.abort(),n=new a,G()},I=N=>(s=N,C),O=N=>(c=N,C),P=()=>(f="json",C),T=()=>{if(!l){if(--u>=0){y(),r&&r();return}l=!0,c&&c(),t&&t()}},x=N=>(h=N,C),G=()=>{d=ue(),n=new a,n.open("get",i);let N=0,ee,Ve=0,Ee=()=>((0,Xe.assertNonNullable)(d),Math.max(d,Math.max(ee||0,Ve||0)));if(s&&n.addEventListener("progress",R=>{let B=ue();s.updateChunk&&R.loaded>N&&(s.updateChunk(Ee(),R.loaded-N),N=R.loaded,ee=B)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(l)return;(0,Xe.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&s){let B=n.response.byteLength-N;B&&s.updateChunk&&s.updateChunk(Ee(),B)}n.responseType==="json"&&!Object.values(n.response).length?T():(c&&c(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),h){let R=()=>{(0,Xe.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Ve=ue(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=f,n.send(),C},C={withBitrateReporting:I,withParallel:x,withJSONResponse:P,withRetryCount:N=>(u=N,C),withRetryInterval:(N,ee)=>((0,Xe.isNonNullable)(N)&&(S=N),(0,Xe.isNonNullable)(ee)&&(b=ee),C),withTimeout:N=>(o=N,C),withFinally:O,send:G,abort:()=>{n&&(n.abort(),n=void 0),l=!0,c&&c()}};return C}var ai=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,r){return{start:e,end:t,bytes:r}}_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 r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let l=s.bytes*n/o;a+=l,s.start=t,s.bytes-=l}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} 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,r){return this.intervals.push(this._createInterval(e,t,r)),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 si=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ue(),a=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=l=>{e._complete=1,e._responseData=l,e._downloadTime=ue()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=mr(t,s,()=>a("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=ue()}_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=ue();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!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(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Qa=1e4,To=3;var uE=6e4,lE=10,cE=1,dE=500,ni=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=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.params=e,this.chunkRateEstimator=new ai(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=yo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,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=yo(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,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.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,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,we.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{jh(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new si(To,Qa,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,l=null,u=null,d=!1,c=()=>{let T=s&&(!d||d===this.rep);return T||t("Not running!"),T},h=(T,x,G)=>{l&&l.abort(),l=mr(this.urlResolver.resolve(T,!1),x,G,()=>this._retryCallback()).withTimeout(Qa).withBitrateReporting(this.bitrateSwitcher).withRetryCount(To).withFinally(()=>{l=null}).send()},f=(T,x,G)=>{(0,we.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),x,G,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=T=>{let x=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${x}=>${T}`),r.playbackRate=T)},S=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}let G=ue()-1e4,A=0;for(let X=0;X<this.bufferStates.length;X++){let w=this.bufferStates[X];T=Math.min(T,w.buf),w.ts<G&&A++}this.bufferStates.splice(0,A),t(`update playback rate; minBuffer=${T} drop=${A} jitter=${this.sourceJitter}`);let Q=T-cE;this.sourceJitter>=0?Q-=this.sourceJitter/2:this.sourceJitter-=1,Q>3?b(1.15):Q>1?b(1.1):Q>.3?b(1.05):b(1)}},I=T=>{let x,G=()=>x&&x.start?x.start.length:0,A=R=>x.start[R]/1e3,Q=R=>x.dur[R]/1e3,X=R=>x.fragIndex+R,w=(R,B)=>({chunkIdx:X(R),startTS:A(R),dur:Q(R),discontinuity:B}),C=()=>{let R=0;if(x&&x.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,se=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,le=B;this.sourceJitter>1&&(le+=this.sourceJitter-1);let xe=x.dur.length-1;for(;xe>=0&&(le-=x.dur[xe],!(le<=0));--xe);R=Math.min(xe,x.dur.length-1-se),R=Math.max(R,0)}return w(R,!0)},N=R=>{let B=G();if(!(B<=0)){if((0,we.isNonNullable)(R)){for(let se=0;se<B;se++)if(A(se)>R)return w(se)}return C()}},ee=R=>{let B=G(),se=R?R.chunkIdx+1:0,le=se-x.fragIndex;if(!(B<=0)){if(!R||le<0||le-B>lE)return t(`Resync: offset=${le} bChunks=${B} chunk=`+JSON.stringify(R)),C();if(!(le>=B))return w(se-x.fragIndex,!1)}},Ve=(R,B,se)=>{u&&u.abort(),u=mr(this.urlResolver.resolve(R,!0,this.lowLatency),B,se,()=>this._retryCallback()).withTimeout(Qa).withRetryCount(To).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(R,B)=>{Ve(T,se=>{if(!c())return;x=se;let le=!!x.lowLatency;le!==this.lowLatency&&S(le);let xe=0;for(let We=0;We<x.dur.length;++We)xe+=x.dur[We];xe>0&&((0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(xe/x.dur.length)),a({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,R(N(B))},()=>this._handleNetworkError())},nextChunk:ee}},O=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),(0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:T=>{let{videoElement:x,logger:G}=this.params,A=I(e.jidxUrl),Q,X,w,C,N=0,ee,Ve,Ee,R=()=>{ee&&(clearTimeout(ee),ee=void 0);let z=Math.max(dE,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=N+z,fe=ue(),_e=Math.min(1e4,ne-fe);N=fe;let bt=()=>{u||c()&&A.seek(()=>{c()&&(N=ue(),B(),R())})};_e>0?ee=window.setTimeout(()=>{this.paused?R():bt()},_e):bt()},B=()=>{let z;for(;z=A.nextChunk(C);)C=z,Wt(z);let ne=A.nextChunk(w);if(ne){if(w&&ne.discontinuity){G("Detected discontinuity; restarting playback"),this.paused?R():(O(),this._initPlayerWith(e));return}We(ne)}else R()},se=(z,ne)=>{if(!c()||!this.sourceBuffer)return;let fe,_e,bt,Yt=St=>{window.setTimeout(()=>{c()&&se(z,ne)},St)};if(this.sourceBuffer.updating)G("Source buffer is updating; delaying appendBuffer"),Yt(100);else{let St=ue(),zt=x.currentTime;!this.paused&&x.buffered.length>1&&Ve===zt&&St-Ee>500&&(G("Stall suspected; trying to fix"),this._fixupStall()),Ve!==zt&&(Ve=zt,Ee=St);let Ar=this._getBufferSizeSec();if(Ar>30)G(`Buffered ${Ar} seconds; delaying appendBuffer`),Yt(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:St,buf:Ar}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(Zi){if(Zi.name==="QuotaExceededError")G("QuotaExceededError; delaying appendBuffer"),bt=this.sourceBuffer.buffered.length,bt!==0&&(fe=this.sourceBuffer.buffered.start(0),_e=zt,_e-fe>4&&this.sourceBuffer.remove(fe,_e-3)),Yt(1e3);else throw Zi}}},le=()=>{X&&Q&&(G([`Appending chunk, sz=${X.byteLength}:`,JSON.stringify(w)]),se(X,function(){X=null,B()}))},xe=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),We=z=>{c()&&f(xe(z),(ne,fe)=>{if(c()){if(fe/=1e3,X=ne,w=z,n=z.startTS,fe){let _e=Math.min(10,z.dur/fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*_e:_e}le()}},()=>this._handleNetworkError())},Wt=z=>{c()&&((0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(xe(z),!1)))},Pt=z=>{c()&&(e.cachedHeader=z,se(z,()=>{Q=!0,le()}))};s=!0,A.seek(z=>{if(c()){if(N=ue(),!z){R();return}C=z,!(0,we.isNullable)(T)||z.startTS>T?We(z):(w=z,B())}},T),e.cachedHeader?Pt(e.cachedHeader):h(e.headerUrl,Pt,()=>this._handleNetworkError())},stop:O,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,we.isNonNullable)(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,we.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,we.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=c=>{if(!this.autoQuality)return;let h,f,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),b=c/this.bitrate,f>10&&b>.8||f>15&&b>.5||f>20&&b>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(h,f)=>{let b=ue();if(this.chunkRateEstimator.addInterval(h,b,f)){let y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:b-h,speed:y}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,l=!0,u=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(l&&c>o&&vo(n)<3e4)return;r(c)}l=this.autoQuality};return{updateChunk:(c,h)=>{let f=s.updateChunk(c,h);return f&&u(),f},notifySwitch:c=>{let h=ue();c<o&&(n=h),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=mr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Qa).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;ye(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((l,u)=>{l.video&&a.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=u,o.push(l))}),o.sort(function(l,u){return l.video&&u.video?u.video.height-l.video.height:u.bitrate-l.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({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))},uE))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var te=require("@vkontakte/videoplayer-shared"),Io=class{constructor(){this.onDroopedVideoFramesLimit$=new te.Subject;this.subscription=new te.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new te.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,te.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,te.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,te.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,te.interval)(this.droppedFramesChecker.checkTime).pipe((0,te.filter)(()=>this.playing),(0,te.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,te.debounce)(this.droppedFramesChecker.checkTime)),r=(0,te.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>(0,te.isLower)(r,a)?-1:1)?.[0]?.[0];return 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}},Wa=Io;var Ya=require("@vkontakte/videoplayer-shared"),Gh=require("@vkontakte/videoplayer-shared");var oi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var pE=(i,e)=>new Ya.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||oi()))},{...r,...e});a.observe(i);let s=(0,Gh.fromEvent)(document,"visibilitychange").pipe((0,Ya.map)(n=>!document.hidden||oi())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Oe=pE;var hE=["paused","playing","ready"],fE=["paused","playing","ready"],ui=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new U("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new De;this.droppedFramesManager=new Wa;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new nt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:V.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=It(a.name)??(0,V.videoSizeToQuality)(a.video),o=a.bitrate/1e3,l={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:l};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,V.isNonNullable)(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);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(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="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(fE.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&hE.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ce(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let l=a?.from;l&&l==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="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 l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.dash.reinit(ce(this.params.source.url,l))}return;default:return(0,V.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:V.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,V.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),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(oe(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ve(this.video);this.subscription.add(this.representations$.pipe((0,V.map)(a=>a.map(({track:s})=>s)),(0,V.filter)(a=>!!a.length),(0,V.once)()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:a}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,V.filterChanged)(),(0,V.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,V.combine)({zeroTime:this.zeroTime$.pipe((0,V.filter)(V.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Je(this.video,this.params.desiredState.isLooped,t)).add(ge(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ce(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Oe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,V.videoQualityToHeight)(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,V.assertNever)(a.to)}},t)).add((0,V.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.observableFrom)(["init"])).pipe((0,V.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Se(this.video)}createLiveDashPlayer(){let e=new ni({videoElement:this.video,videoState:this.videoState,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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&(0,V.isNonNullable)(t)?t:Et(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let u=e.find(({track:d})=>d.id===s)?.representation;(0,V.assertNonNullable)(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;(0,V.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ce(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Qh=ui;var lt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var D=require("@vkontakte/videoplayer-shared");var za=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];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}},br=class extends za{constructor(){super(),this.listeners||za.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)}},li=class{constructor(){Object.defineProperty(this,"signal",{value:new br,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(li.prototype[Symbol.toStringTag]="AbortController",br.prototype[Symbol.toStringTag]="AbortSignal");function Ka(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Eo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Ka({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let h=new t(u,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let d=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let h=new Promise((f,b)=>{d.addEventListener("abort",()=>b(c),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([h,n(l,u)])}return n(l,u)},Request:s}}var ci=Ka({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Wh=ci?Eo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ct=ci?Wh.fetch:window.fetch,HR=ci?Wh.Request:window.Request,dt=ci?li:window.AbortController,jR=ci?br:window.AbortSignal;var Kh=Fe(ri(),1);var pt=()=>window.ManagedMediaSource||window.MediaSource,Ja=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Yh=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),zh=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Ze=require("@vkontakte/videoplayer-shared"),Za=document.createElement("video"),SE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',gE='video/mp4; codecs="hev1.1.6.L93.B0"',Jh='video/webm; codecs="vp09.00.10.08"',Xh='video/webm; codecs="av01.0.00M.08"',vE='audio/mp4; codecs="mp4a.40.2"',yE='audio/webm; codecs="opus"',Bt={mms:Ja(),mse:Yh(),hls:!!(Za.canPlayType?.("application/x-mpegurl")||Za.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Te={mp4:!!Za.canPlayType?.("video/mp4"),webm:!!Za.canPlayType?.("video/webm"),cmaf:!0},Ie={h264:!!pt()?.isTypeSupported?.(SE),h265:!!pt()?.isTypeSupported?.(gE),vp9:!!pt()?.isTypeSupported?.(Jh),av1:!!pt()?.isTypeSupported?.(Xh),aac:!!pt()?.isTypeSupported?.(vE),opus:!!pt()?.isTypeSupported?.(yE)},Sr=(Ie.h264||Ie.h265)&&Ie.aac,Vt,TE=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Xh}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Jh}})]);Vt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{TE()}catch(i){console.error(i)}var gr=Bt.hls&&Te.mp4,Zh=()=>Object.keys(Ie).filter(i=>Ie[i]),ef=(i,e=!1,t=!1)=>{let r=Bt.mse||Bt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Te.mp4&&Sr;case"DASH_WEBM":return r&&Te.webm&&Ie.vp9&&Ie.opus;case"DASH_WEBM_AV1":return r&&Te.webm&&Ie.av1&&Ie.opus;case"DASH_STREAMS":return r&&(Te.mp4&&Sr||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return Bt.mse&&Te.mp4&&Sr;case"DASH_LIVE_CMAF":return r&&Te.mp4&&Sr&&Te.cmaf;case"DASH_ONDEMAND":return r&&Te.mp4&&Sr;case"HLS":case"HLS_ONDEMAND":return gr||e&&Bt.mse&&Te.mp4&&Sr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return gr;case"MPEG":return Te.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Bt.webrtc&&Bt.ws&&Ie.h264&&(Te.mp4||Te.webm);default:return(0,Ze.assertNever)(a)}})},Xa=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Vt?Vt[t].smooth?[t,e]:Vt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Vt?Vt[t].powerEfficient?[t,e]:Vt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,Ze.assertNever)(i)}return[e,t]},tf=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Xa(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ze.clientChecker.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",...Xa(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Xa(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Xa(i),...a,"HLS","HLS_ONDEMAND"];default:(0,Ze.assertNever)(e)}return gr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},rf=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o,l=Ze.clientChecker.isMac&&Ze.clientChecker.isSafari;if(Ze.clientChecker.isAndroid)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,Ze.assertNever)(i)}else gr&&!l?o=n:l?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},xo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],af=i=>{if(i.size!==0){if(i.size===1)return i.values().next().value.split(".").at(0);for(let e of i){let t=(0,Kh.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};var vr=require("@vkontakte/videoplayer-shared"),sf=i=>{if(!i)return{id:"EmptyResponse",category:vr.ErrorCategory.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:vr.ErrorCategory.NETWORK,message:`UV Error ${i}`};let e=i.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:vr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:vr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:vr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var di=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};var g=require("@vkontakte/videoplayer-shared");var Pr=Fe(ri(),1);var IE=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},EE=i=>window.clearTimeout(i),nf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Po=nf?IE:window.requestIdleCallback,rL=nf?EE:window.cancelIdleCallback;var Qf=Fe(Ua(),1);var Be=require("@vkontakte/videoplayer-shared"),xE=16,of=!1;try{of=Be.clientChecker.isSafari&&!!Be.clientChecker.macVersion&&Be.clientChecker.macVersion<=xE}catch(i){console.error(i)}var ko=class{constructor(e){this.bufferFull$=new Be.Subject;this.error$=new Be.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Be.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;of&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:Be.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Be.assertNever)(t)}}},uf=ko;var Ao=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var E=require("@vkontakte/videoplayer-shared");var K=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 yr=class extends K{};var pi=class extends K{};var hi=class extends K{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var fi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var bi=class extends K{constructor(e,t){super(e,t),this.data=this.content}};var ae=class extends K{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var _t=class extends ae{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),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 r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let l=a>>>28,u=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:u})}}};var Si=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var vi=class extends ae{constructor(e,t){switch(super(e,t),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 yi=class extends ae{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ti=class extends ae{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ii=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ei=class extends ae{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 xi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Pi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends ae{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ai=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends ae{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 Ri=class extends ae{constructor(t,r){super(t,r);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 Li=class extends ae{constructor(t,r){super(t,r);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 a=0;a<this.sampleCount;a++)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 kE={ftyp:hi,moov:fi,moof:mi,mdat:bi,sidx:_t,trak:Si,mdia:Ii,mfhd:ki,tkhd:Ei,traf:Ai,tfhd:wi,tfdt:Ri,trun:Li,minf:xi,sv3d:gi,st3d:vi,prhd:yi,proj:Pi,equi:Ti,uuid:pi,unknown:yr},Nt=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=kE[e];return r?new r(t,new i):new yr(t,new i)}};var Tr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var wE=new TextDecoder("ascii"),RE=i=>wE.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",LE=i=>{let e=new _t(i,new Nt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},$E=(i,e)=>{let r=new Nt().parse(i),a=new Tr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],l=n[n.length-1],u=o.source.byteOffset,c=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(i.buffer,u,c)},ME=(i,e)=>{let r=new Nt().parse(i),s=new Tr(r).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),l=s[s.length-1].children.find(c=>c.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((c,h)=>c+h,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},CE=i=>{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}}},r=new Nt().parse(i),a=new Tr(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let l=a.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},lf={validateData:RE,parseInit:CE,getIndexRange:()=>{},parseSegments:LE,parseFeedableSegmentChunk:$E,getSegmentEndTime:ME};var ht=require("@vkontakte/videoplayer-shared");var df=require("@vkontakte/videoplayer-shared");var cf={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"}},pf=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=$i(i,t),a=r in cf,s=a?cf[r].type:"binary",n=i.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 l=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,d=$i(l),c=u*2**((o-1)*8)+d,h=t+o,f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},$i=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ge=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return $i(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:(0,df.assertNever)(e)}},Ft=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=pf(r);if(!e(a))return;a.type==="master"&&Ft(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},hf=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=pf(i);return Ft(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Ge(o,n):s===17026?t=Ge(o,n):s===17029&&(r=Ge(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var ff=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],DE=[231,22612,22743,167,171,163,160,175],OE=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,d=!1,c=0;return Ft(i,({tag:h,type:f,value:b,valueSize:S})=>{if(h===21419){let y=Ge(b,f);u=$i(y)}else h!==21420&&(u=void 0);return h===408125543?(e=b.byteOffset,t=b.byteOffset+S):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Ge(b,f):h===17545?a=Ge(b,f):h===21420&&u===475249515?l=Ge(b,f):h===374648427?Ft(b,({tag:y,type:I,value:O})=>y===30321?(d=Ge(O,I)===1,!1):!0):s&&n&&ff.includes(h)&&(o=!0),!o}),(0,ht.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,ht.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,ht.assertNonNullable)(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:l,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},BE=i=>{if((0,ht.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},VE=(i,e)=>{let t=!1,r=!1,a=o=>(0,ht.isNonNullable)(o.time)&&(0,ht.isNonNullable)(o.position),s=[],n;return Ft(i,({tag:o,type:l,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ge(u,l));break;case 183:break;case 241:n&&(n.position=Ge(u,l));break;default:t&&ff.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:d}=o,c=s[l+1];return{status:"none",time:{from:u,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},_E=i=>{let e=0,t=!1;try{Ft(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):DE.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},mf={validateData:hf,parseInit:OE,getIndexRange:BE,parseSegments:VE,parseFeedableSegmentChunk:_E};var Ir=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return mf;case"mp4":return lf}}throw new ReferenceError(`Unsupported mime type ${i}`)};var Oo=Fe(Vf(),1);var Do=i=>{let e=i.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=r;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=r[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var xr=require("@vkontakte/videoplayer-shared");var _f=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Nf=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},qt=(i,e)=>{let t=i;t=(0,Oo.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,Oo.default)(t,n,(o,l)=>(0,xr.isNullable)(s)?o:(0,xr.isNullable)(l)?s:s.padStart(parseInt(l,10),"0"))}return t},qf=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",l=n.children,u=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),c=d?new Date(d).getTime():void 0,h,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),y=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)h=Nf(f);else if(b){let T=Nf(b);(0,xr.isNonNullable)(T)&&(h=T)}else y&&(h=parseInt(y,10));let I=0,O=s.getAttribute("profiles")?.split(",")??[];for(let T of l){let x=T.getAttribute("id")??"id"+(I++).toString(10),G=T.getAttribute("mimeType")??"",A=T.getAttribute("codecs")??"",Q=T.getAttribute("contentType")??G?.split("/")[0],X=T.getAttribute("profiles")?.split(",")??[],w=T.getAttribute("lang")??void 0,C=T.querySelector("Label")?.textContent?.trim()??void 0,N=T.querySelectorAll("Representation"),ee=T.querySelector("SegmentTemplate"),Ve=T.querySelector("Role")?.getAttribute("value")??void 0,Ee=Q,R={id:x,language:w,isDefault:Ve==="main",label:C,codecs:A,hdr:Ee==="video"&&Do(A),mime:G,representations:[]};for(let B of N){let se=B.getAttribute("lang")??void 0,le=B.getAttribute("label")??void 0,xe=B.querySelector("BaseURL")?.textContent?.trim()??"",We=new URL(xe||o,e).toString(),Wt=B.getAttribute("mimeType")??G,Pt=B.getAttribute("codecs")??A??"",z;if(Q==="text"){let ne=B.getAttribute("id")||"",fe=ne.includes("_auto");z={id:ne,isAuto:fe,kind:"text",url:We}}else{let ne=B.getAttribute("contentType")??Wt?.split("/")[0]??Q,fe=T.getAttribute("profiles")?.split(",")??[],_e=parseInt(B.getAttribute("width")??"",10),bt=parseInt(B.getAttribute("height")??"",10),Yt=parseInt(B.getAttribute("bandwidth")??"",10)/1e3,St=B.getAttribute("frameRate")??"",zt=B.getAttribute("quality")??void 0,Ar=St?_f(St):void 0,Zi=B.getAttribute("id")??"id"+(I++).toString(10),gm=ne==="video"?`${bt}p`:ne==="audio"?`${Yt}Kbps`:Pt,vm=`${Zi}@${gm}`,ym=[...O,...X,...fe],ms,Tm=B.querySelector("SegmentBase"),kt=B.querySelector("SegmentTemplate")??ee;if(Tm){let At=B.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[wt,Ss]=At.split("-").map(Kt=>parseInt(Kt,10)),gt={from:wt,to:Ss},wr=B.querySelector("SegmentBase")?.getAttribute("indexRange"),[gs,ea]=wr?wr.split("-").map(Kt=>parseInt(Kt,10)):[],Rr=wr?{from:gs,to:ea}:void 0;ms={type:"byteRange",url:We,initRange:gt,indexRange:Rr}}else if(kt){let At={representationId:B.getAttribute("id")??void 0,bandwidth:B.getAttribute("bandwidth")??void 0},wt=parseInt(kt.getAttribute("timescale")??"",10),Ss=kt.getAttribute("initialization")??"",gt=kt.getAttribute("media"),wr=parseInt(kt.getAttribute("startNumber")??"",10)??1,gs=qt(Ss,At);if(!gt)throw new ReferenceError("No media attribute in SegmentTemplate");let ea=kt.querySelectorAll("SegmentTimeline S")??[],Rr=[],Kt=0,vs="",ys=0;if(ea.length){let ta=wr,Ne=0;for(let Jt of ea){let Ye=parseInt(Jt.getAttribute("d")??"",10),Rt=parseInt(Jt.getAttribute("r")??"",10)||0,ra=parseInt(Jt.getAttribute("t")??"",10);Ne=Number.isFinite(ra)?ra:Ne;let Ts=Ye/wt*1e3,Em=Ne/wt*1e3;for(let ia=0;ia<Rt+1;ia++){let xm=qt(gt,{...At,segmentNumber:ta.toString(10),segmentTime:(Ne+ia*Ye).toString(10)}),Yo=(Em??0)+ia*Ts,Pm=Yo+Ts;ta++,Rr.push({time:{from:Yo,to:Pm},url:xm})}Ne+=(Rt+1)*Ye,Kt+=(Rt+1)*Ts}ys=Ne/wt*1e3,vs=qt(gt,{...At,segmentNumber:ta.toString(10),segmentTime:Ne.toString(10)})}else if((0,xr.isNonNullable)(h)){let Ne=parseInt(kt.getAttribute("duration")??"",10)/wt*1e3,Jt=Math.ceil(h/Ne),Ye=0;for(let Rt=1;Rt<Jt;Rt++){let ra=qt(gt,{...At,segmentNumber:Rt.toString(10),segmentTime:Ye.toString(10)});Rr.push({time:{from:Ye,to:Ye+Ne},url:ra}),Ye+=Ne}ys=Ye,vs=qt(gt,{...At,segmentNumber:Jt.toString(10),segmentTime:Ye.toString(10)})}let Im={time:{from:ys,to:1/0},url:vs};ms={type:"template",baseUrl:We,segmentTemplateUrl:gt,initUrl:gs,totalSegmentsDurationMs:Kt,segments:Rr,nextSegmentBeyondManifest:Im,timescale:wt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ne||!Wt)continue;let bs={video:"video",audio:"audio",text:"text"}[ne];if(!bs)continue;Ee||=bs,z={id:vm,kind:bs,segmentReference:ms,profiles:ym,duration:h,bitrate:Yt,mime:Wt,codecs:Pt,width:_e,height:bt,fps:Ar,quality:zt}}R.language||=se,R.label||=le,R.mime||=Wt,R.codecs||=Pt,R.hdr||=Ee==="video"&&Do(Pt),R.representations.push(z)}Ee&&a[Ee].push(R)}return{dynamic:u,liveAvailabilityStartTime:c,duration:h,streams:a}};var Mi=Fe(ri(),1);var Uf=require("@vkontakte/videoplayer-shared"),Hf=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?It(s):void 0)??(0,Uf.videoSizeToQuality)({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},jf=({id:i,bitrate:e})=>({id:i,bitrate:e}),es=(i,e,t)=>{let r=e.indexOf(i);return(0,Mi.default)(t,Math.round(t.length*r/e.length))??(0,Mi.default)(t,-1)},Gf=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Vo=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Mi.default)(r.split("."),0),isDefault:a}),_o=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Mi.default)(a.split("."),0)}),ts=i=>"url"in i,Ut=i=>i.type==="template",Ci=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Di=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:l=!1,manifest:u}){this.currentSegmentLength$=new E.ValueSubject(0);this.onLastSegment$=new E.ValueSubject(!1);this.fullyBuffered$=new E.ValueSubject(!1);this.playingRepresentation$=new E.ValueSubject(void 0);this.playingRepresentationInit$=new E.ValueSubject(void 0);this.error$=new E.Subject;this.gaps=[];this.subscription=new E.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new dt;this.destroyAbortController=new dt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,E.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,E.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new uf(this.sourceBuffer),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,l=this.mediaSource.readyState;l!=="open"&&(o={id:`SegmentEjection_source_${l}`,category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:E.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let l=Math.min(this.bufferLimit,Ao(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=l,this.tuning.useNewPruneBufferStrategy){let u=lt(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,u<d)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,E.assertNonNullable)(r,"No init buffer for starting representation"),(0,E.assertNonNullable)(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,E.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,E.assertNonNullable)(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,E.isNullable)(s)||(0,E.isNullable)(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,E.assertNonNullable)(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,E.isNonNullable)(n)&&(this.isLive||(a.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,E.abortable)(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(l=>l.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let u=t.find(h=>h.id===l);u&&this.representations.set(l,u);let d=this.representations.get(l);if(!d||!Ut(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);(0,E.assertNonNullable)(a);let s=this.segments.get(r);(0,E.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,E.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=l,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new dt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,E.isNullable)(e)||(0,E.isNullable)(this.downloadingRepresentationId)||(0,E.isNullable)(this.playingRepresentationId)||(0,E.isNullable)(this.sourceBuffer)||!(0,E.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,E.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=lt(this.sourceBuffer.buffered,e),c=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=c)}if(isFinite(this.bufferLimit)&&Ao(this.sourceBuffer.buffered)>=this.bufferLimit){let u=lt(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let d=(0,Pr.default)(o,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&<(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Pr.default)(r,-1);l&&l.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===l))}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;(0,E.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(r=>r.representations)??[];for(let r of t){if(!r||!Ut(r.segmentReference))return;let a=r.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Pr.default)(s,-1)?.time.to??0,o=a?.findIndex(l=>Math.floor(n)>=Math.floor(l.time.from)&&Math.floor(n)<=Math.floor(l.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,l)}else{let l=a.slice(o+1);this.segments.set(r.id,[...s,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,E.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let r=t.segmentReference;if(!Ut(r))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=qt(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:c,time:{from:h,to:f}},b)=>{let S=h<=r&&f>=r,y=h>r||S||b===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),O=this.preloadOnly&&h<=r+I||f<=r+I;return(c==="none"||c==="partially_ejected"&&y&&O&&this.sourceBuffer&&!di(this.sourceBuffer.buffered,r))&&y&&O});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=a;c<s.length&&(n<=u||o<=d);c++){let h=s[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:l,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,E.abortable)(o,async function*(){let d=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:l,priority:r,isLowLatency:this.isActiveLowLatency()});if(!d)return;let c=new DataView(d);if(!isFinite(a.segment.time.to)){let h=t.segmentReference.timescale,f=Ir(t.mime);a.segment.time.to=f.getSegmentEndTime(c,h)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(c,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ci(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let l of e)l.status="downloading",this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,E.abortable)(n,async function*(){let l=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),(0,E.fromEvent)(window,"online").pipe((0,E.once)()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(l){this.abortActiveSegments(e),Ci(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Ut(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Pr.default)(e,0).byte.from,to:(0,Pr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,l)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ut(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!s.aborted)try{let c=this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:a,signal:s,onProgress:l,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Ir(n.mime).parseFeedableSegmentChunk(u,this.isLive);d?.byteLength&&(l.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let l=o.segmentReference.type,u=e.byteLength;for(let d of this.activeSegments){let{segment:c}=d,h=l==="byteRange",f=h?c.byte.to-c.byte.from+1:u;if(d.representationId!==t||!(!h||c.byte.from>=r&&c.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let S=h?c.byte.from-r:0,y=h?c.byte.to-r:e.byteLength,I=S<a,O=y<=a;if(c.status==="downloading"&&I&&O){c.status="downloaded";let P=new DataView(e.buffer,e.byteOffset+S,f);this.sourceBufferTaskQueue.append(P,s).then(T=>T&&!s.aborted?this.onSegmentFullyAppended(d,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&I&&(d.loadedBytes=Math.min(f,a-S),d.loadedBytes>d.feedingBytes)){let P=new DataView(e.buffer,e.byteOffset+S+d.feedingBytes,d.loadedBytes-d.feedingBytes),T=d.loadedBytes===f?P:Ir(o.mime).parseFeedableSegmentChunk(P);T?.byteLength&&(c.status="partially_fed",d.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(x=>{if(s.aborted)n();else if(x)d.fedBytes+=T.byteLength,d.fedBytes===f&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<f)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let l of this.activeSegments){let{segment:u}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=u.byte.from-r,c=u.byte.to-r,h=c-d+1,f=d<a,b=c<=a;if(f){if(u.status==="downloading"&&b){u.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,h);await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(l.loadedBytes=Math.min(h,a-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),y=l.loadedBytes===h?S:Ir(o.mime).parseFeedableSegmentChunk(S);y?.byteLength&&(u.status="partially_fed",l.feedingBytes+=y.byteLength,await this.sourceBufferTaskQueue.append(y,s)&&!s.aborted?(l.fedBytes+=y.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ts(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Po(()=>(0,Qf.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,E.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ir(e.mime),a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:d}=o,c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Ut(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:E.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,E.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=l=>{l.sort((d,c)=>d.from-c.from);let u=[l[0]];for(let d=1;d<l.length;d++){let{from:c,to:h}=l[d],f=u[u.length-1];f.to>=c?f.to=Math.max(f.to,h):u.push(l[d])}return u},o=l=>{if(s>=t)return a;a.push(l.time),a=n(a);let u=ts(l)?l.size??0:l.byte.to-l.byte.from;s+=u};for(let l of this.segments.values())for(let u of l){let d=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&u.status==="fed"&&o(u)}for(let l=0;l<this.sourceBuffer.buffered.length;l++){let u=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3,c=0;for(let h of this.segments.values())for(let f of h)f.status==="none"&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let h={time:{from:u,to:d},url:"",status:"none"};o(h)}}if(a.length&&r){let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let d of u)d.time.from>=e+l&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,d)=>u||d,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,E.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,l=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let d=ts(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status==="fed"&&l(d)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status==="fed"&&l(d)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3;for(let h of this.segments.values())for(let f of h)if(f.status==="none"&&Math.round(f.time.from)<=Math.round(d)&&Math.round(f.time.to)>=Math.round(c)){s=d,n=c;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let c of d)c.time.from>e+u&&c.status==="fed"&&l(c)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Po(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:E.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,E.isNullable)(this.sourceBuffer)||(0,E.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),l=e.some(d=>d.from-t<=n&&d.to+t>=o),u=e.filter(d=>n>=d.from-t&&n<=d.to+t||o>=d.from-t&&o<=d.to+t);l||(u.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Oi=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Wf=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};var W=require("@vkontakte/videoplayer-shared");var rs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1}){this.lastConnectionType$=new W.ValueSubject(void 0);this.lastConnectionReused$=new W.ValueSubject(void 0);this.lastRequestFirstBytes$=new W.ValueSubject(void 0);this.abortAllController=new dt;this.subscription=new W.Subscription;this.fetchManifest=(0,W.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Oi(r));let a=yield ct(r,{signal:this.abortAllController.signal}).catch(Bi);return a?(t.log("success",(0,W.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",(0,W.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,W.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:l=!1}={}){let u=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let C=new URL(u,location.href);C.searchParams.append("bytes",`${r.from}-${r.to}`),u=C.toString();break}default:(0,W.assertNever)(t)}this.requestQuic&&(u=Oi(u));let h=this.abortAllController.signal,f;if(n){let C=new dt;if(f=(0,W.merge)((0,W.fromEvent)(this.abortAllController.signal,"abort"),(0,W.fromEvent)(n,"abort")).subscribe(()=>{try{C.abort()}catch(N){Bi(N)}}),this.abortAllController.signal.aborted||n.aborted)try{C.abort()}catch(N){Bi(N)}h=C.signal}let b=(0,W.now)();c.log("startRequest",(0,W.flattenObject)({url:u,priority:s,rangeMethod:t,range:r,isLowLatency:l,requestStartedAt:b}));let S=yield ct(u,{priority:s,headers:d,signal:h}).catch(Bi),y=(0,W.now)();if(!S)return c.error("error",{message:"No response in request"}),c.end(),f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-b),!S.ok||!S.body){f?.unsubscribe();let C=`Fetch error ${S.status}: ${S.statusText}`;return c.error("error",{message:C}),c.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!a&&!o){f?.unsubscribe();let C=(0,W.now)(),N={requestStartedAt:b,requestEndedAt:C,duration:C-b};return c.log("endRequest",(0,W.flattenObject)(N)),c.end(),S.arrayBuffer()}let[I,O]=S.body.tee(),P=I.getReader();o&&this.throughputEstimator?.trackStream(O,l);let T=0,x=new Uint8Array(0),G=!1,A=C=>{f?.unsubscribe(),G=!0,Bi(C)},Q=(0,W.abortable)(h,async function*({done:C,value:N}){if(T===0&&this.lastRequestFirstBytes$.next((0,W.now)()-b),h.aborted){f?.unsubscribe();return}if(!C&&N){let ee=new Uint8Array(x.length+N.length);ee.set(x),ee.set(N,x.length),x=ee,T+=N.byteLength,a?.(new DataView(x.buffer),T),yield P?.read().then(Q,A)}}.bind(this));yield P?.read().then(Q,A),f?.unsubscribe();let X=(0,W.now)(),w={failed:G,requestStartedAt:b,requestEndedAt:X,duration:X-b};return G?(c.error("endRequest",(0,W.flattenObject)(w)),c.end(),null):(c.log("endRequest",(0,W.flattenObject)(w)),c.end(),x.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,W.abortable)(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,l=!1,u,d;e.indexRange&&(u=e.indexRange.from,d=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,a),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!c)return null;let h=new DataView(c,a-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let f=t.parseInit(h),b=e.indexRange??t.getIndexRange(f);if(!b)throw new ReferenceError("No way to load representation index");let S;if(l)S=new DataView(c,b.from-n,b.to-b.from+1);else{let I=yield this.fetch(e.url,{range:b,priority:r,measureThroughput:!1});if(!I)return null;S=new DataView(I)}let y=t.parseSegments(S,f,b);return{init:f,dataView:new DataView(c),segments:y}}.bind(this));this.fetchTemplateRepresentation=(0,W.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=Wf(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:(0,W.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Bi=i=>{if(!Ci(i))throw i};var Ht=(i,e,t)=>t*e+(1-t)*i,No=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Yf=(i,e,t,r)=>{let a=0,s=t,n=No(i,e),o=e<r?e:r;for(let l=0;l<o;l++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};var Vi=require("@vkontakte/videoplayer-shared"),xt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Vi.ValueSubject(e.initial),this.debounced$=new Vi.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new he(`raw_${t}`),this.smoothedSeries$=new he(`smoothed_${t}`),this.reportedSeries$=new he(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,Vi.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var is=class extends xt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ht(this.slow,e,this.params.emaAlphaSlow),this.fast=Ht(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var as=class extends xt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=No(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ht(this.emaSmoothed,e,this.params.emaAlpha);let r=Yf(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var ss=class extends xt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ht(this.smoothed,t,this.params.emaAlpha):t}};var jt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new is({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new as({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ss({initial:e,label:"liveEdgeDelay",...t})}};var Fo=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var Kf=["timeupdate","progress","play","seeked","stalled","waiting"];var ns=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new g.Subscription;this.representationSubscription=new g.Subscription;this.state$=new U("none");this.currentVideoRepresentation$=new g.ValueSubject(void 0);this.currentVideoRepresentationInit$=new g.ValueSubject(void 0);this.currentAudioRepresentation$=new g.ValueSubject(void 0);this.currentVideoSegmentLength$=new g.ValueSubject(0);this.currentAudioSegmentLength$=new g.ValueSubject(0);this.error$=new g.Subject;this.lastConnectionType$=new g.ValueSubject(void 0);this.lastConnectionReused$=new g.ValueSubject(void 0);this.lastRequestFirstBytes$=new g.ValueSubject(void 0);this.isLive$=new g.ValueSubject(!1);this.liveDuration$=new g.ValueSubject(0);this.liveAvailabilityStartTime$=new g.ValueSubject(void 0);this.bufferLength$=new g.ValueSubject(0);this.liveLoadBufferLength$=new g.ValueSubject(0);this.livePositionFromPlayer$=new g.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new g.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new g.Subject;this.gapWatchdogActive=!1;this.destroyController=new dt;this.initManifest=(0,g.abortable)(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ce(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:g.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,g.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:g.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t;try{t=qf(e??"",this.manifestUrlString)}catch(n){let o=sf(e)??{id:"ManifestParsing",category:g.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,l)=>!!(this.element?.canPlayType?.(o)&&pt()?.isTypeSupported?.(`${o}; codecs="${l}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let l=t.streams[n].filter(({mime:c,codecs:h})=>r(n,c,h)),u=new Set(l.map(({codecs:c})=>c)),d=af(u);if(d&&(a[n]=l.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,h=a.video.some(b=>b.hdr),f=a.video.some(b=>!b.hdr);g.clientChecker.isHDR&&c&&h?a.video=a.video.filter(b=>b.hdr):f&&(a.video=a.video.filter(b=>!b.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",(0,g.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,g.abortable)(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",(0,g.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,g.assertNonNullable)(this.manifest),(0,g.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=c=>{this.representationSubscription.add((0,g.fromEvent)(c,"error").pipe((0,g.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:g.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?zh():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ja())if(r){let c=document.createElement("source");a(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((c,h)=>[...c,...h.representations],[]);if(this.videoBufferManager=new Di("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,g.isNonNullable)(t)){let c=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Di("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,g.interval)(1e3).subscribe(c=>{if(this.element?.paused){let h=lo(this.manifestUrlString,2);this.manifestUrlString=ce(this.manifestUrlString,h+1e3,2)}})),this.representationSubscription.add((0,g.merge)(...Kf.filter(c=>c!=="waiting").map(c=>(0,g.fromEvent)(this.element,c))).pipe((0,g.map)(c=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),(0,g.filterChanged)(),(0,g.filter)(c=>!!c),(0,g.tap)(c=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,g.filterChanged)()).subscribe(h=>Fo(this.element,1))),this.representationSubscription.add((0,g.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,g.filter)(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add((0,g.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,O=1;Math.abs(I)>S&&(O=1+Math.sign(I)*y),Fo(this.element,O)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(y=>y.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let c=0;this.representationSubscription.add((0,g.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,g.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if((0,g.assertNonNullable)(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,S=lo(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),O=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,P=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(h)?h:f,x=this.isActiveLowLatency$.getValue(),G=y<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(x&&G);let A="none";if(x?A="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&G?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(Q=>Q.proceedLowLatencyLive()),A="active_low_latency"):S!==0&&T<I?A="live_forward_buffering":T<I+P&&(A="live_with_target_offset"),isFinite(h)&&(c=h>c?h:c),A==="live_forward_buffering"||A==="live_with_target_offset"){let Q=c-(I+O),X=this.normolizeLiveOffset(Math.trunc(S+Q/b)),w=Math.abs(X-S),C;!h||w<=this.tuning.dashCmafLive.offsetCalculationError?C=S:X>0&&w>this.tuning.dashCmafLive.offsetCalculationError?C=X:C=0,this.manifestUrlString=ce(this.manifestUrlString,C,2)}A!=="none"&&A!=="active_low_latency"&&(c=0,this.updateLive())}))}let l=(0,g.merge)(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe((0,g.map)(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),u=(0,g.merge)(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe((0,g.map)(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue())));this.representationSubscription.add((0,g.merge)(this.forceEnded$,(0,g.combine)({allBuffersFull:l,someBufferEnded:u}).pipe((0,g.filter)(({allBuffersFull:c,someBufferEnded:h})=>c&&h))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:g.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add((0,g.merge)(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(c=>this.source?.addEventListener("sourceopen",c)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(c=>c.representations).flatMap(c=>c.duration??0)];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&(0,g.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,g.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:g.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new rs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=jt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){(0,g.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ce(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio))}initBuffer(){(0,g.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,g.merge)(...Kf.map(e=>(0,g.fromEvent)(this.element,e)),(0,g.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:g.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,g.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,g.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&di(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;this.timeInWaiting+=1e3;let t={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),t={...t,liveLastSeekOffset:this.liveLastSeekOffset};else{let r=this.element.currentTime*1e3;this.videoBufferManager?.maintain(r),this.audioBufferManager?.maintain(r),t={...t,position:r}}this.tracer.log("stallIntervalCallback",(0,g.flattenObject)(t))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,g.interval)(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:g.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,r)}seek(e,t){(0,g.assertNonNullable)(this.element),(0,g.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),di(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,g.flattenObject)({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,g.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,g.flattenObject)(t)))}}};var os=class{constructor(e,t){this.fov=e,this.orientation=t}};var us=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,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??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,r){this.setRotationSpeed(e,t,r),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,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Jf=`attribute vec2 a_vertex;
|
|
36
|
+
[best video track] ${z?.quality}
|
|
37
|
+
[selected video track] ${X?.quality}
|
|
38
|
+
`}),rf(r,p,X,u)},af=(i,e,t,{throughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:c})=>{(0,V.assertNotEmptyArray)(t,tf);let u=a.considerPlaybackRate&&(0,V.isNonNullable)(s)?s:1,d=[...t].sort(ko(-1)),l=i.bitrate;(0,V.assertNonNullable)(l);let p=u*ef(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f;return(0,V.isNonNullable)(r)&&isFinite(r)&&(f=d.find(b=>(0,V.isNonNullable)(b.bitrate)?r-l>=b.bitrate*p:!0)),f||(f=as(i,e,t,a.minVideoAudioRatio)),f?.bitrate!==o?.last?.bitrate&&c({message:`
|
|
39
|
+
[AUDIO TRACKS ABR]
|
|
40
|
+
[available audio tracks]
|
|
41
|
+
${t.map(b=>`{ id: ${b.id}, bitrate: ${b.bitrate} }`).join(`
|
|
42
|
+
`)}
|
|
43
|
+
|
|
44
|
+
[tuning]
|
|
45
|
+
${Object.entries(a??{}).map(([b,g])=>`${b}: ${g}`).join(`
|
|
46
|
+
`)}
|
|
47
|
+
|
|
48
|
+
[limit params]
|
|
49
|
+
throughput: ${r},
|
|
50
|
+
reserve: ${l},
|
|
51
|
+
playbackRate: ${s},
|
|
52
|
+
playbackRateFactor: ${u},
|
|
53
|
+
forwardBufferHealth: ${n},
|
|
54
|
+
bitrateFactor: ${p},
|
|
55
|
+
minBufferToSwitchUp: ${a.minBufferToSwitchUp},
|
|
56
|
+
|
|
57
|
+
[selected audio track] ${f?.id}
|
|
58
|
+
`}),f&&rf(a,c,f,o)};var ue=i=>new URL(i).hostname;var O=require("@vkontakte/videoplayer-shared");var sf=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},Ee=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!sf(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return sf(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};var $e=require("@vkontakte/videoplayer-shared");var nt=require("@vkontakte/videoplayer-shared");function ce(){return(0,nt.now)()}function wo(i){return ce()-i}function Ro(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,c=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return c&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function nf(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Pr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,c=!1,u=0,d,l,p=!1,f="arraybuffer",b=7e3,g=2e3,y=()=>{if(c)return;(0,nt.assertNonNullable)(d);let N=wo(d),ee;if(N<g){ee=g-N,setTimeout(y,ee);return}g*=2,g>b&&(g=b),n&&n.abort(),n=new a,k()},E=N=>(s=N,B),C=N=>(l=N,B),x=()=>(f="json",B),T=()=>{if(!c){if(--u>=0){y(),r&&r();return}c=!0,l&&l(),t&&t()}},P=N=>(p=N,B),k=()=>{d=ce(),n=new a,n.open("get",i);let N=0,ee,qe=0,ge=()=>((0,nt.assertNonNullable)(d),Math.max(d,Math.max(ee||0,qe||0)));if(s&&n.addEventListener("progress",w=>{let L=ce();s.updateChunk&&w.loaded>N&&(s.updateChunk(ge(),w.loaded-N),N=w.loaded,ee=L)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(c)return;(0,nt.assertNonNullable)(n);let w=n.status;if(w>=200&&w<300){if(n.response.byteLength&&s){let L=n.response.byteLength-N;L&&s.updateChunk&&s.updateChunk(ge(),L)}n.responseType==="json"&&!Object.values(n.response).length?T():(l&&l(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),p){let w=()=>{(0,nt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(qe=ce(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=f,n.send(),B},B={withBitrateReporting:E,withParallel:P,withJSONResponse:x,withRetryCount:N=>(u=N,B),withRetryInterval:(N,ee)=>((0,nt.isNonNullable)(N)&&(g=N),(0,nt.isNonNullable)(ee)&&(b=ee),B),withTimeout:N=>(o=N,B),withFinally:C,send:k,abort:()=>{n&&(n.abort(),n=void 0),c=!0,l&&l()}};return B}var mi=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,r){return{start:e,end:t,bytes:r}}_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 r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let c=s.bytes*n/o;a+=c,s.start=t,s.bytes-=c}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} 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,r){return this.intervals.push(this._createInterval(e,t,r)),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 bi=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ce(),a=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=c=>{e._complete=1,e._responseData=c,e._downloadTime=ce()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Pr(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ce()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ce();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!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(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var ss=1e4,$o=3;var fE=6e4,mE=10,bE=1,gE=500,gi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=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.params=e,this.chunkRateEstimator=new mi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ro(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,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=Ro(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,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.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,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,$e.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{nf(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new bi($o,ss,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,c=null,u=null,d=!1,l=()=>{let T=s&&(!d||d===this.rep);return T||t("Not running!"),T},p=(T,P,k)=>{c&&c.abort(),c=Pr(this.urlResolver.resolve(T,!1),P,k,()=>this._retryCallback()).withTimeout(ss).withBitrateReporting(this.bitrateSwitcher).withRetryCount($o).withFinally(()=>{c=null}).send()},f=(T,P,k)=>{(0,$e.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),P,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=T=>{let P=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${P}=>${T}`),r.playbackRate=T)},g=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}let k=ce()-1e4,Y=0;for(let X=0;X<this.bufferStates.length;X++){let D=this.bufferStates[X];T=Math.min(T,D.buf),D.ts<k&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${T} drop=${Y} jitter=${this.sourceJitter}`);let z=T-bE;this.sourceJitter>=0?z-=this.sourceJitter/2:this.sourceJitter-=1,z>3?b(1.15):z>1?b(1.1):z>.3?b(1.05):b(1)}},E=T=>{let P,k=()=>P&&P.start?P.start.length:0,Y=w=>P.start[w]/1e3,z=w=>P.dur[w]/1e3,X=w=>P.fragIndex+w,D=(w,L)=>({chunkIdx:X(w),startTS:Y(w),dur:z(w),discontinuity:L}),B=()=>{let w=0;if(P&&P.dur){let L=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,se=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,le=L;this.sourceJitter>1&&(le+=this.sourceJitter-1);let Ae=P.dur.length-1;for(;Ae>=0&&(le-=P.dur[Ae],!(le<=0));--Ae);w=Math.min(Ae,P.dur.length-1-se),w=Math.max(w,0)}return D(w,!0)},N=w=>{let L=k();if(!(L<=0)){if((0,$e.isNonNullable)(w)){for(let se=0;se<L;se++)if(Y(se)>w)return D(se)}return B()}},ee=w=>{let L=k(),se=w?w.chunkIdx+1:0,le=se-P.fragIndex;if(!(L<=0)){if(!w||le<0||le-L>mE)return t(`Resync: offset=${le} bChunks=${L} chunk=`+JSON.stringify(w)),B();if(!(le>=L))return D(se-P.fragIndex,!1)}},qe=(w,L,se)=>{u&&u.abort(),u=Pr(this.urlResolver.resolve(w,!0,this.lowLatency),L,se,()=>this._retryCallback()).withTimeout(ss).withRetryCount($o).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(w,L)=>{qe(T,se=>{if(!l())return;P=se;let le=!!P.lowLatency;le!==this.lowLatency&&g(le);let Ae=0;for(let Ue=0;Ue<P.dur.length;++Ue)Ae+=P.dur[Ue];Ae>0&&((0,$e.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ae/P.dur.length)),a({name:"index",zeroTime:P.zeroTime,shiftDuration:P.shiftDuration}),this.sourceJitter=P.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,P.jitter/1e3)):1,w(N(L))},()=>this._handleNetworkError())},nextChunk:ee}},C=()=>{s=!1,o&&o.abort(),c&&c.abort(),u&&u.abort(),(0,$e.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:T=>{let{videoElement:P,logger:k}=this.params,Y=E(e.jidxUrl),z,X,D,B,N=0,ee,qe,ge,w=()=>{ee&&(clearTimeout(ee),ee=void 0);let Q=Math.max(gE,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=N+Q,pe=ce(),oe=Math.min(1e4,ne-pe);N=pe;let Me=()=>{u||l()&&Y.seek(()=>{l()&&(N=ce(),L(),w())})};oe>0?ee=window.setTimeout(()=>{this.paused?w():Me()},oe):Me()},L=()=>{let Q;for(;Q=Y.nextChunk(B);)B=Q,ir(Q);let ne=Y.nextChunk(D);if(ne){if(D&&ne.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?w():(C(),this._initPlayerWith(e));return}Ue(ne)}else w()},se=(Q,ne)=>{if(!l()||!this.sourceBuffer)return;let pe,oe,Me,kt=et=>{window.setTimeout(()=>{l()&&se(Q,ne)},et)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),kt(100);else{let et=ce(),He=P.currentTime;!this.paused&&P.buffered.length>1&&qe===He&&et-ge>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),qe!==He&&(qe=He,ge=et);let Ot=this._getBufferSizeSec();if(Ot>30)k(`Buffered ${Ot} seconds; delaying appendBuffer`),kt(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:et,buf:Ot}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(ct){if(ct.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(pe=this.sourceBuffer.buffered.start(0),oe=He,oe-pe>4&&this.sourceBuffer.remove(pe,oe-3)),kt(1e3);else throw ct}}},le=()=>{X&&z&&(k([`Appending chunk, sz=${X.byteLength}:`,JSON.stringify(D)]),se(X,function(){X=null,L()}))},Ae=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),Ue=Q=>{l()&&f(Ae(Q),(ne,pe)=>{if(l()){if(pe/=1e3,X=ne,D=Q,n=Q.startTS,pe){let oe=Math.min(10,Q.dur/pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*oe:oe}le()}},()=>this._handleNetworkError())},ir=Q=>{l()&&((0,$e.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ae(Q),!1)))},Vt=Q=>{l()&&(e.cachedHeader=Q,se(Q,()=>{z=!0,le()}))};s=!0,Y.seek(Q=>{if(l()){if(N=ce(),!Q){w();return}B=Q,!(0,$e.isNullable)(T)||Q.startTS>T?Ue(Q):(D=Q,L())}},T),e.cachedHeader?Vt(e.cachedHeader):p(e.headerUrl,Vt,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,$e.isNonNullable)(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,$e.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,$e.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=l=>{if(!this.autoQuality)return;let p,f,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(f=this._getBufferSizeSec(),b=l/this.bitrate,f>10&&b>.8||f>15&&b>.5||f>20&&b>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},s={updateChunk:(p,f)=>{let b=ce();if(this.chunkRateEstimator.addInterval(p,b,f)){let y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:b-p,speed:y}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,c=!0,u=()=>{let l=s.get();if(l&&o&&this.autoQuality){if(c&&l>o&&wo(n)<3e4)return;r(l)}c=this.autoQuality};return{updateChunk:(l,p)=>{let f=s.updateChunk(l,p);return f&&u(),f},notifySwitch:l=>{let p=ce();l<o&&(n=p),o=l}}}_fetchManifest(e,t,r){this.manifestRequest=Pr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ss).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;Ee(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((c,u)=>{c.video&&a.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=u,o.push(c))}),o.sort(function(c,u){return c.video&&u.video?u.video.height-c.video.height:u.bitrate-c.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({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))},fE))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var te=require("@vkontakte/videoplayer-shared"),Lo=class{constructor(){this.onDroopedVideoFramesLimit$=new te.Subject;this.subscription=new te.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new te.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,te.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,te.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,te.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,te.interval)(this.droppedFramesChecker.checkTime).pipe((0,te.filter)(()=>this.playing),(0,te.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,te.debounce)(this.droppedFramesChecker.checkTime)),r=(0,te.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>(0,te.isLower)(r,a)?-1:1)?.[0]?.[0];return 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}},ns=Lo;var os=require("@vkontakte/videoplayer-shared"),of=require("@vkontakte/videoplayer-shared");var Si=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var SE=(i,e)=>new os.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(c=>t.next(c.isIntersecting||Si()))},{...r,...e});a.observe(i);let s=(0,of.fromEvent)(document,"visibilitychange").pipe((0,os.map)(n=>!document.hidden||Si())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Ne=SE;var vE=["paused","playing","ready"],yE=["paused","playing","ready"],vi=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new H("stopped");this.representations$=new O.ValueSubject([]);this.textTracksManager=new _e;this.droppedFramesManager=new ns;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new bt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:O.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=Ct(a.name)??(0,O.videoSizeToQuality)(a.video),o=a.bitrate/1e3,c={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:c};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,O.isNonNullable)(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);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(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="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(yE.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&vE.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(de(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let c=a?.from;c&&c==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="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 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.dash.reinit(de(this.params.source.url,c))}return;default:return(0,O.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),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(ue(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Ie(this.video);this.subscription.add(this.representations$.pipe((0,O.map)(a=>a.map(({track:s})=>s)),(0,O.filter)(a=>!!a.length),(0,O.once)()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:a}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,O.filterChanged)(),(0,O.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(st(this.video,this.params.desiredState.isLooped,t)).add(Te(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Oe(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ne(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,O.videoQualityToHeight)(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,O.assertNever)(a.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ye(this.video)}createLiveDashPlayer(){let e=new gi({videoElement:this.video,videoState:this.videoState,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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&(0,O.isNonNullable)(t)?t:Dt(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),c&&this.setAutoQuality(r),n||c||s!==o){let u=e.find(({track:d})=>d.id===s)?.representation;(0,O.assertNonNullable)(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;(0,O.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(de(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var uf=vi;var vt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var q=require("@vkontakte/videoplayer-shared");var us=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Ar=class extends us{constructor(){super(),this.listeners||us.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)}},yi=class{constructor(){Object.defineProperty(this,"signal",{value:new Ar,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(yi.prototype[Symbol.toStringTag]="AbortController",Ar.prototype[Symbol.toStringTag]="AbortSignal");function cs(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Mo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!cs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,d){let l;d&&d.signal&&(l=d.signal,delete d.signal);let p=new t(u,d);return l&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),p},s.prototype=t.prototype);let n=e;return{fetch:(c,u)=>{let d=s&&s.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(d){let l;try{l=new DOMException("Aborted","AbortError")}catch{l=new Error("Aborted"),l.name="AbortError"}if(d.aborted)return Promise.reject(l);let p=new Promise((f,b)=>{d.addEventListener("abort",()=>b(l),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(c,u)])}return n(c,u)},Request:s}}var Ti=cs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),cf=Ti?Mo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,yt=Ti?cf.fetch:window.fetch,zR=Ti?cf.Request:window.Request,Tt=Ti?yi:window.AbortController,KR=Ti?Ar:window.AbortSignal;var pf=We(pi(),1);var It=()=>window.ManagedMediaSource||window.MediaSource,ls=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),lf=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),df=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ot=require("@vkontakte/videoplayer-shared"),ps=document.createElement("video"),EE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',xE='video/mp4; codecs="hev1.1.6.L93.B0"',hf='video/webm; codecs="vp09.00.10.08"',ff='video/webm; codecs="av01.0.00M.08"',PE='audio/mp4; codecs="mp4a.40.2"',AE='audio/webm; codecs="opus"',Qt={mms:ls(),mse:lf(),hls:!!(ps.canPlayType?.("application/x-mpegurl")||ps.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},xe={mp4:!!ps.canPlayType?.("video/mp4"),webm:!!ps.canPlayType?.("video/webm"),cmaf:!0},Pe={h264:!!It()?.isTypeSupported?.(EE),h265:!!It()?.isTypeSupported?.(xE),vp9:!!It()?.isTypeSupported?.(hf),av1:!!It()?.isTypeSupported?.(ff),aac:!!It()?.isTypeSupported?.(PE),opus:!!It()?.isTypeSupported?.(AE)},kr=(Pe.h264||Pe.h265)&&Pe.aac,zt,kE=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:ff}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:hf}})]);zt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{kE()}catch(i){console.error(i)}var wr=Qt.hls&&xe.mp4,mf=()=>Object.keys(Pe).filter(i=>Pe[i]),bf=(i,e=!1,t=!1)=>{let r=Qt.mse||Qt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&xe.mp4&&kr;case"DASH_WEBM":return r&&xe.webm&&Pe.vp9&&Pe.opus;case"DASH_WEBM_AV1":return r&&xe.webm&&Pe.av1&&Pe.opus;case"DASH_STREAMS":return r&&(xe.mp4&&kr||xe.webm&&(Pe.vp9||Pe.av1)&&(Pe.opus||Pe.aac));case"DASH_LIVE":return Qt.mse&&xe.mp4&&kr;case"DASH_LIVE_CMAF":return r&&xe.mp4&&kr&&xe.cmaf;case"DASH_ONDEMAND":return r&&xe.mp4&&kr;case"HLS":case"HLS_ONDEMAND":return wr||e&&Qt.mse&&xe.mp4&&kr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return wr;case"MPEG":return xe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Qt.webrtc&&Qt.ws&&Pe.h264&&(xe.mp4||xe.webm);default:return(0,ot.assertNever)(a)}})},ds=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return zt?zt[t].smooth?[t,e]:zt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return zt?zt[t].powerEfficient?[t,e]:zt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ot.assertNever)(i)}return[e,t]},gf=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ds(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ot.clientChecker.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",...ds(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ds(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ds(i),...a,"HLS","HLS_ONDEMAND"];default:(0,ot.assertNever)(e)}return wr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Sf=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o,c=ot.clientChecker.isMac&&ot.clientChecker.isSafari;if(ot.clientChecker.isAndroid)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,ot.assertNever)(i)}else wr&&!c?o=n:c?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Co=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],vf=i=>{if(i.size!==0){if(i.size===1)return i.values().next().value.split(".").at(0);for(let e of i){let t=(0,pf.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};var Rr=require("@vkontakte/videoplayer-shared"),yf=i=>{if(!i)return{id:"EmptyResponse",category:Rr.ErrorCategory.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:Rr.ErrorCategory.NETWORK,message:`UV Error ${i}`};let e=i.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Rr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Rr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Rr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Ii=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};var S=require("@vkontakte/videoplayer-shared");var Br=We(pi(),1);var wE=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},RE=i=>window.clearTimeout(i),Tf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Do=Tf?wE:window.requestIdleCallback,u$=Tf?RE:window.cancelIdleCallback;var sm=We(ts(),1);var Fe=require("@vkontakte/videoplayer-shared"),$E=16,If=!1;try{If=Fe.clientChecker.isSafari&&!!Fe.clientChecker.macVersion&&Fe.clientChecker.macVersion<=$E}catch(i){console.error(i)}var Bo=class{constructor(e){this.bufferFull$=new Fe.Subject;this.error$=new Fe.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Fe.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;If&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:Fe.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Fe.assertNever)(t)}}},Ef=Bo;var Vo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var I=require("@vkontakte/videoplayer-shared");var K=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 $r=class extends K{};var Ei=class extends K{};var xi=class extends K{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var Pi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends K{constructor(e,t){super(e,t),this.data=this.content}};var ae=class extends K{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Kt=class extends ae{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),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 r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let c=a>>>28,u=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:c,SAPDeltaTime:u})}}};var wi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends ae{constructor(e,t){switch(super(e,t),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 Li=class extends ae{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Mi=class extends ae{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ci=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends ae{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 Bi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Oi=class extends ae{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var _i=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ni=class extends ae{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 Fi=class extends ae{constructor(t,r){super(t,r);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 qi=class extends ae{constructor(t,r){super(t,r);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 a=0;a<this.sampleCount;a++)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 ME={ftyp:xi,moov:Pi,moof:Ai,mdat:ki,sidx:Kt,trak:wi,mdia:Ci,mfhd:Oi,tkhd:Di,traf:_i,tfhd:Ni,tfdt:Fi,trun:qi,minf:Bi,sv3d:Ri,st3d:$i,prhd:Li,proj:Vi,equi:Mi,uuid:Ei,unknown:$r},Jt=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=ME[e];return r?new r(t,new i):new $r(t,new i)}};var Lr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var DE=new TextDecoder("ascii"),BE=i=>DE.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",VE=i=>{let e=new Kt(i,new Jt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},OE=(i,e)=>{let r=new Jt().parse(i),a=new Lr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],c=n[n.length-1],u=o.source.byteOffset,l=c.source.byteOffset-o.source.byteOffset+c.size;return new DataView(i.buffer,u,l)},_E=(i,e)=>{let r=new Jt().parse(i),s=new Lr(r).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),c=s[s.length-1].children.find(l=>l.type==="trun"),u=0;return c.sampleDuration.length?u=c.sampleDuration.reduce((l,p)=>l+p,0):u=n.defaultSampleDuration*c.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},NE=i=>{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}}},r=new Jt().parse(i),a=new Lr(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let c=a.find("equi");c&&(e.projectionData.bounds.top=c.projectionBoundsTop,e.projectionData.bounds.right=c.projectionBoundsRight,e.projectionData.bounds.bottom=c.projectionBoundsBottom,e.projectionData.bounds.left=c.projectionBoundsLeft)}return e},xf={validateData:BE,parseInit:NE,getIndexRange:()=>{},parseSegments:VE,parseFeedableSegmentChunk:OE,getSegmentEndTime:_E};var Et=require("@vkontakte/videoplayer-shared");var Af=require("@vkontakte/videoplayer-shared");var Pf={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"}},kf=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Ui(i,t),a=r in Pf,s=a?Pf[r].type:"binary",n=i.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 c=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,d=Ui(c),l=u*2**((o-1)*8)+d,p=t+o,f;return p+l>i.byteLength?f=new DataView(i.buffer,i.byteOffset+p):f=new DataView(i.buffer,i.byteOffset+p,l),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:f,valueSize:l}},Ui=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Je=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Ui(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:(0,Af.assertNever)(e)}},Xt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=kf(r);if(!e(a))return;a.type==="master"&&Xt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},wf=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=kf(i);return Xt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Je(o,n):s===17026?t=Je(o,n):s===17029&&(r=Je(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Rf=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],FE=[231,22612,22743,167,171,163,160,175],qE=i=>{let e,t,r,a,s=!1,n=!1,o=!1,c,u,d=!1,l=0;return Xt(i,({tag:p,type:f,value:b,valueSize:g})=>{if(p===21419){let y=Je(b,f);u=Ui(y)}else p!==21420&&(u=void 0);return p===408125543?(e=b.byteOffset,t=b.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Je(b,f):p===17545?a=Je(b,f):p===21420&&u===475249515?c=Je(b,f):p===374648427?Xt(b,({tag:y,type:E,value:C})=>y===30321?(d=Je(C,E)===1,!1):!0):s&&n&&Rf.includes(p)&&(o=!0),!o}),(0,Et.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Et.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Et.assertNonNullable)(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:c,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},UE=i=>{if((0,Et.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},HE=(i,e)=>{let t=!1,r=!1,a=o=>(0,Et.isNonNullable)(o.time)&&(0,Et.isNonNullable)(o.position),s=[],n;return Xt(i,({tag:o,type:c,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Je(u,c));break;case 183:break;case 241:n&&(n.position=Je(u,c));break;default:t&&Rf.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,c)=>{let{time:u,position:d}=o,l=s[c+1];return{status:"none",time:{from:u,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},jE=i=>{let e=0,t=!1;try{Xt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):FE.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},$f={validateData:wf,parseInit:qE,getIndexRange:UE,parseSegments:HE,parseFeedableSegmentChunk:jE};var Mr=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return $f;case"mp4":return xf}}throw new ReferenceError(`Unsupported mime type ${i}`)};var jo=We(Xf(),1);var Ho=i=>{let e=i.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=r;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=r[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var Dr=require("@vkontakte/videoplayer-shared");var Zf=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var em=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},xt=(i,e)=>{let t=i;t=(0,jo.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,jo.default)(t,n,(o,c)=>(0,Dr.isNullable)(s)?o:(0,Dr.isNullable)(c)?s:s.padStart(parseInt(c,10),"0"))}return t},tm=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",c=n.children,u=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),l=d?new Date(d).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),y=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=em(f);else if(b){let T=em(b);(0,Dr.isNonNullable)(T)&&(p=T)}else y&&(p=parseInt(y,10));let E=0,C=s.getAttribute("profiles")?.split(",")??[];for(let T of c){let P=T.getAttribute("id")??"id"+(E++).toString(10),k=T.getAttribute("mimeType")??"",Y=T.getAttribute("codecs")??"",z=T.getAttribute("contentType")??k?.split("/")[0],X=T.getAttribute("profiles")?.split(",")??[],D=T.getAttribute("lang")??void 0,B=T.querySelector("Label")?.textContent?.trim()??void 0,N=T.querySelectorAll("Representation"),ee=T.querySelector("SegmentTemplate"),qe=T.querySelector("Role")?.getAttribute("value")??void 0,ge=z,w={id:P,language:D,isDefault:qe==="main",label:B,codecs:Y,hdr:ge==="video"&&Ho(Y),mime:k,representations:[]};for(let L of N){let se=L.getAttribute("lang")??void 0,le=L.getAttribute("label")??void 0,Ae=L.querySelector("BaseURL")?.textContent?.trim()??"",Ue=new URL(Ae||o,e).toString(),ir=L.getAttribute("mimeType")??k,Vt=L.getAttribute("codecs")??Y??"",Q;if(z==="text"){let ne=L.getAttribute("id")||"",pe=ne.includes("_auto"),oe=L.querySelector("SegmentTemplate");if(oe){let Me={representationId:L.getAttribute("id")??void 0,bandwidth:L.getAttribute("bandwidth")??void 0},kt=parseInt(L.getAttribute("bandwidth")??"",10)/1e3,et=parseInt(oe.getAttribute("startNumber")??"",10)??1,He=parseInt(oe.getAttribute("timescale")??"",10),Ot=oe.querySelectorAll("SegmentTimeline S")??[],ct=oe.getAttribute("media");if(!ct)throw new ReferenceError("No media attribute in SegmentTemplate");let da=[],pa=0,ha="",ar=0,Or=et,he=0;for(let je of Ot){let _t=parseInt(je.getAttribute("d")??"",10),Ce=parseInt(je.getAttribute("r")??"",10)||0,wt=parseInt(je.getAttribute("t")??"",10);he=Number.isFinite(wt)?wt:he;let Nt=_t/He*1e3,sr=he/He*1e3;for(let tt=0;tt<Ce+1;tt++){let Rt=xt(ct,{...Me,segmentNumber:Or.toString(10),segmentTime:(he+tt*_t).toString(10)}),nr=(sr??0)+tt*Nt,Nr=nr+Nt;Or++,da.push({time:{from:nr,to:Nr},url:Rt})}he+=(Ce+1)*_t,pa+=(Ce+1)*Nt}ar=he/He*1e3,ha=xt(ct,{...Me,segmentNumber:Or.toString(10),segmentTime:he.toString(10)});let _r={time:{from:ar,to:1/0},url:ha},lt={type:"template",baseUrl:Ue,segmentTemplateUrl:ct,initUrl:"",totalSegmentsDurationMs:pa,segments:da,nextSegmentBeyondManifest:_r,timescale:He};Q={id:ne,kind:"text",segmentReference:lt,profiles:[],duration:p,bitrate:kt,mime:"",codecs:"",width:0,height:0,isAuto:pe}}else Q={id:L.getAttribute("id")||"",isAuto:pe,kind:"text",url:Ue}}else{let ne=L.getAttribute("contentType")??ir?.split("/")[0]??z,pe=T.getAttribute("profiles")?.split(",")??[],oe=parseInt(L.getAttribute("width")??"",10),Me=parseInt(L.getAttribute("height")??"",10),kt=parseInt(L.getAttribute("bandwidth")??"",10)/1e3,et=L.getAttribute("frameRate")??"",He=L.getAttribute("quality")??void 0,Ot=et?Zf(et):void 0,ct=L.getAttribute("id")??"id"+(E++).toString(10),da=ne==="video"?`${Me}p`:ne==="audio"?`${kt}Kbps`:Vt,pa=`${ct}@${da}`,ha=[...C,...X,...pe],ar,Or=L.querySelector("SegmentBase"),he=L.querySelector("SegmentTemplate")??ee;if(Or){let lt=L.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[je,_t]=lt.split("-").map(Rt=>parseInt(Rt,10)),Ce={from:je,to:_t},wt=L.querySelector("SegmentBase")?.getAttribute("indexRange"),[Nt,sr]=wt?wt.split("-").map(Rt=>parseInt(Rt,10)):[],tt=wt?{from:Nt,to:sr}:void 0;ar={type:"byteRange",url:Ue,initRange:Ce,indexRange:tt}}else if(he){let lt={representationId:L.getAttribute("id")??void 0,bandwidth:L.getAttribute("bandwidth")??void 0},je=parseInt(he.getAttribute("timescale")??"",10),_t=he.getAttribute("initialization")??"",Ce=he.getAttribute("media"),wt=parseInt(he.getAttribute("startNumber")??"",10)??1,Nt=xt(_t,lt);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");let sr=he.querySelectorAll("SegmentTimeline S")??[],tt=[],Rt=0,nr="",Nr=0;if(sr.length){let fa=wt,Ge=0;for(let or of sr){let rt=parseInt(or.getAttribute("d")??"",10),Ft=parseInt(or.getAttribute("r")??"",10)||0,ma=parseInt(or.getAttribute("t")??"",10);Ge=Number.isFinite(ma)?ma:Ge;let $s=rt/je*1e3,Mm=Ge/je*1e3;for(let ba=0;ba<Ft+1;ba++){let Cm=xt(Ce,{...lt,segmentNumber:fa.toString(10),segmentTime:(Ge+ba*rt).toString(10)}),au=(Mm??0)+ba*$s,Dm=au+$s;fa++,tt.push({time:{from:au,to:Dm},url:Cm})}Ge+=(Ft+1)*rt,Rt+=(Ft+1)*$s}Nr=Ge/je*1e3,nr=xt(Ce,{...lt,segmentNumber:fa.toString(10),segmentTime:Ge.toString(10)})}else if((0,Dr.isNonNullable)(p)){let Ge=parseInt(he.getAttribute("duration")??"",10)/je*1e3,or=Math.ceil(p/Ge),rt=0;for(let Ft=1;Ft<or;Ft++){let ma=xt(Ce,{...lt,segmentNumber:Ft.toString(10),segmentTime:rt.toString(10)});tt.push({time:{from:rt,to:rt+Ge},url:ma}),rt+=Ge}Nr=rt,nr=xt(Ce,{...lt,segmentNumber:or.toString(10),segmentTime:rt.toString(10)})}let Lm={time:{from:Nr,to:1/0},url:nr};ar={type:"template",baseUrl:Ue,segmentTemplateUrl:Ce,initUrl:Nt,totalSegmentsDurationMs:Rt,segments:tt,nextSegmentBeyondManifest:Lm,timescale:je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ne||!ir)continue;let _r={video:"video",audio:"audio",text:"text"}[ne];if(!_r)continue;ge||=_r,Q={id:pa,kind:_r,segmentReference:ar,profiles:ha,duration:p,bitrate:kt,mime:ir,codecs:Vt,width:oe,height:Me,fps:Ot,quality:He}}w.language||=se,w.label||=le,w.mime||=ir,w.codecs||=Vt,w.hdr||=ge==="video"&&Ho(Vt),w.representations.push(Q)}ge&&a[ge].push(w)}return{dynamic:u,liveAvailabilityStartTime:l,duration:p,streams:a}};var Hi=We(pi(),1);var rm=require("@vkontakte/videoplayer-shared"),im=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?Ct(s):void 0)??(0,rm.videoSizeToQuality)({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},am=({id:i,bitrate:e})=>({id:i,bitrate:e}),hs=(i,e,t)=>{let r=e.indexOf(i);return(0,Hi.default)(t,Math.round(t.length*r/e.length))??(0,Hi.default)(t,-1)},fs=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Yo=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Hi.default)(r.split("."),0),isDefault:a}),Qo=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Hi.default)(a.split("."),0)}),ms=i=>"url"in i,Xe=i=>i.type==="template",ji=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Gi=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:c=!1,manifest:u}){this.currentSegmentLength$=new I.ValueSubject(0);this.onLastSegment$=new I.ValueSubject(!1);this.fullyBuffered$=new I.ValueSubject(!1);this.playingRepresentation$=new I.ValueSubject(void 0);this.playingRepresentationInit$=new I.ValueSubject(void 0);this.error$=new I.Subject;this.gaps=[];this.subscription=new I.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Tt;this.destroyAbortController=new Tt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,I.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ef(this.sourceBuffer),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,c=this.mediaSource.readyState;c!=="open"&&(o={id:`SegmentEjection_source_${c}`,category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let c=Math.min(this.bufferLimit,Vo(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=c,this.tuning.useNewPruneBufferStrategy){let u=vt(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,u<d)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,I.assertNonNullable)(r,"No init buffer for starting representation"),(0,I.assertNonNullable)(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,I.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,I.assertNonNullable)(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,I.assertNonNullable)(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,I.isNonNullable)(n)&&(this.isLive||(a.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(c=>c.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let u=t.find(p=>p.id===c);u&&this.representations.set(c,u);let d=this.representations.get(c);if(!d||!Xe(d.segmentReference))return;let l=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,l)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);(0,I.assertNonNullable)(a);let s=this.segments.get(r);(0,I.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,I.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=c,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Tt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,I.isNullable)(e)||(0,I.isNullable)(this.downloadingRepresentationId)||(0,I.isNullable)(this.playingRepresentationId)||(0,I.isNullable)(this.sourceBuffer)||!(0,I.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,I.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=vt(this.sourceBuffer.buffered,e),l=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=l)}if(isFinite(this.bufferLimit)&&Vo(this.sourceBuffer.buffered)>=this.bufferLimit){let u=vt(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let d=(0,Br.default)(o,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&vt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Br.default)(r,-1);c&&c.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===c))}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;(0,I.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(r=>r.representations)??[];for(let r of t){if(!r||!Xe(r.segmentReference))return;let a=r.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Br.default)(s,-1)?.time.to??0,o=a?.findIndex(c=>Math.floor(n)>=Math.floor(c.time.from)&&Math.floor(n)<=Math.floor(c.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,c)}else{let c=a.slice(o+1);this.segments.set(r.id,[...s,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,I.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let r=t.segmentReference;if(!Xe(r))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=xt(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:l,time:{from:p,to:f}},b)=>{let g=p<=r&&f>=r,y=p>r||g||b===0&&r===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&p<=r+E||f<=r+E;return(l==="none"||l==="partially_ejected"&&y&&C&&this.sourceBuffer&&!Ii(this.sourceBuffer.buffered,r))&&y&&C});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,c=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let l=a;l<s.length&&(n<=u||o<=d);l++){let p=s[l];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:c,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,I.abortable)(o,async function*(){let d=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:c,priority:r,isLowLatency:this.isActiveLowLatency()});if(!d)return;let l=new DataView(d);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,f=Mr(t.mime);a.segment.time.to=f.getSegmentEndTime(l,p)}c&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(l,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),ji(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let c of e)c.status="downloading",this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,I.abortable)(n,async function*(){let c=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,c),(0,I.fromEvent)(window,"online").pipe((0,I.once)()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(c){this.abortActiveSegments(e),ji(c)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Xe(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Br.default)(e,0).byte.from,to:(0,Br.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,c)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Xe(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!s.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:a,signal:s,onProgress:c,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:c}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Mr(n.mime).parseFeedableSegmentChunk(u,this.isLive);d?.byteLength&&(c.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let c=o.segmentReference.type,u=e.byteLength;for(let d of this.activeSegments){let{segment:l}=d,p=c==="byteRange",f=p?l.byte.to-l.byte.from+1:u;if(d.representationId!==t||!(!p||l.byte.from>=r&&l.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let g=p?l.byte.from-r:0,y=p?l.byte.to-r:e.byteLength,E=g<a,C=y<=a;if(l.status==="downloading"&&E&&C){l.status="downloaded";let x=new DataView(e.buffer,e.byteOffset+g,f),T=this.getCurrentPosition();(0,I.isNonNullable)(T)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-T,this.bufferAccumulation.accumulated.push({segmentView:x,segmentProgress:d}),this.activeSegments.delete(d));let P=({segmentView:k,segmentProgress:Y})=>this.sourceBufferTaskQueue.append(k,s).then(z=>z&&!s.aborted?this.onSegmentFullyAppended(Y,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(P),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,I.isNullable)(T))&&(P({segmentView:x,segmentProgress:d}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&E&&!C&&(d.loadedBytes=Math.min(f,a-g),d.loadedBytes>d.feedingBytes)){let x=new DataView(e.buffer,e.byteOffset+g+d.feedingBytes,d.loadedBytes-d.feedingBytes),T=d.loadedBytes===f?x:Mr(o.mime).parseFeedableSegmentChunk(x);T?.byteLength&&(l.status="partially_fed",d.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(P=>{if(s.aborted)n();else if(P)d.fedBytes+=T.byteLength,d.fedBytes===f&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<f)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let c of this.activeSegments){let{segment:u}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=u.byte.from-r,l=u.byte.to-r,p=l-d+1,f=d<a,b=l<=a;if(f){if(u.status==="downloading"&&b){u.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(c.loadedBytes=Math.min(p,a-d),c.loadedBytes>c.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===p?g:Mr(o.mime).parseFeedableSegmentChunk(g);y?.byteLength&&(u.status="partially_fed",c.feedingBytes+=y.byteLength,await this.sourceBufferTaskQueue.append(y,s)&&!s.aborted?(c.fedBytes+=y.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t)):n())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ms(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Do(()=>(0,sm.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,I.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mr(e.mime),a)).then(async o=>{if(!o)return;let{init:c,dataView:u,segments:d}=o,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l);let p=d;this.isLive&&Xe(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:I.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=c=>{c.sort((d,l)=>d.from-l.from);let u=[c[0]];for(let d=1;d<c.length;d++){let{from:l,to:p}=c[d],f=u[u.length-1];f.to>=l?f.to=Math.max(f.to,p):u.push(c[d])}return u},o=c=>{if(s>=t)return a;a.push(c.time),a=n(a);let u=ms(c)?c.size??0:c.byte.to-c.byte.from;s+=u};for(let c of this.segments.values())for(let u of c){let d=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&u.status==="fed"&&o(u)}for(let c=0;c<this.sourceBuffer.buffered.length;c++){let u=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3,l=0;for(let p of this.segments.values())for(let f of p)f.status==="none"&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:u,to:d},url:"",status:"none"};o(p)}}if(a.length&&r){let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let d of u)d.time.from>=e+c&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,d)=>u||d,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,c=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let d=ms(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status==="fed"&&c(d)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status==="fed"&&c(d)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let f of p)if(f.status==="none"&&Math.round(f.time.from)<=Math.round(d)&&Math.round(f.time.to)>=Math.round(l)){s=d,n=l;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>e+u&&l.status==="fed"&&c(l)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Do(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:I.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,I.isNullable)(this.sourceBuffer)||(0,I.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),c=e.some(d=>d.from-t<=n&&d.to+t>=o),u=e.filter(d=>n>=d.from-t&&n<=d.to+t||o>=d.from-t&&o<=d.to+t);c||(u.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Wi=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var nm=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};var G=require("@vkontakte/videoplayer-shared");var bs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1}){this.lastConnectionType$=new G.ValueSubject(void 0);this.lastConnectionReused$=new G.ValueSubject(void 0);this.lastRequestFirstBytes$=new G.ValueSubject(void 0);this.abortAllController=new Tt;this.subscription=new G.Subscription;this.fetchManifest=(0,G.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Wi(r));let a=yield yt(r,{signal:this.abortAllController.signal}).catch(Yi);return a?(t.log("success",(0,G.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",(0,G.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,G.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:c=!1}={}){let u=e,d=new Headers,l=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let B=new URL(u,location.href);B.searchParams.append("bytes",`${r.from}-${r.to}`),u=B.toString();break}default:(0,G.assertNever)(t)}this.requestQuic&&(u=Wi(u));let p=this.abortAllController.signal,f;if(n){let B=new Tt;if(f=(0,G.merge)((0,G.fromEvent)(this.abortAllController.signal,"abort"),(0,G.fromEvent)(n,"abort")).subscribe(()=>{try{B.abort()}catch(N){Yi(N)}}),this.abortAllController.signal.aborted||n.aborted)try{B.abort()}catch(N){Yi(N)}p=B.signal}let b=(0,G.now)();l.log("startRequest",(0,G.flattenObject)({url:u,priority:s,rangeMethod:t,range:r,isLowLatency:c,requestStartedAt:b}));let g=yield yt(u,{priority:s,headers:d,signal:p}).catch(Yi),y=(0,G.now)();if(!g)return l.error("error",{message:"No response in request"}),l.end(),f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-b),!g.ok||!g.body){f?.unsubscribe();let B=`Fetch error ${g.status}: ${g.statusText}`;return l.error("error",{message:B}),l.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!a&&!o){f?.unsubscribe();let B=(0,G.now)(),N={requestStartedAt:b,requestEndedAt:B,duration:B-b};return l.log("endRequest",(0,G.flattenObject)(N)),l.end(),g.arrayBuffer()}let[E,C]=g.body.tee(),x=E.getReader();o&&this.throughputEstimator?.trackStream(C,c);let T=0,P=new Uint8Array(0),k=!1,Y=B=>{f?.unsubscribe(),k=!0,Yi(B)},z=(0,G.abortable)(p,async function*({done:B,value:N}){if(T===0&&this.lastRequestFirstBytes$.next((0,G.now)()-b),p.aborted){f?.unsubscribe();return}if(!B&&N){let ee=new Uint8Array(P.length+N.length);ee.set(P),ee.set(N,P.length),P=ee,T+=N.byteLength,a?.(new DataView(P.buffer),T),yield x?.read().then(z,Y)}}.bind(this));yield x?.read().then(z,Y),f?.unsubscribe();let X=(0,G.now)(),D={failed:k,requestStartedAt:b,requestEndedAt:X,duration:X-b};return k?(l.error("endRequest",(0,G.flattenObject)(D)),l.end(),null):(l.log("endRequest",(0,G.flattenObject)(D)),l.end(),P.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,G.abortable)(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,c=!1,u,d;e.indexRange&&(u=e.indexRange.from,d=e.indexRange.to,c=s+1===u,c&&(n=Math.min(u,a),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!l)return null;let p=new DataView(l,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let f=t.parseInit(p),b=e.indexRange??t.getIndexRange(f);if(!b)throw new ReferenceError("No way to load representation index");let g;if(c)g=new DataView(l,b.from-n,b.to-b.from+1);else{let E=yield this.fetch(e.url,{range:b,priority:r,measureThroughput:!1});if(!E)return null;g=new DataView(E)}let y=t.parseSegments(g,f,b);return{init:f,dataView:new DataView(l),segments:y}}.bind(this));this.fetchTemplateRepresentation=(0,G.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=nm(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:(0,G.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Yi=i=>{if(!ji(i))throw i};var Zt=(i,e,t)=>t*e+(1-t)*i,zo=(i,e)=>i.reduce((t,r)=>t+r,0)/e,om=(i,e,t,r)=>{let a=0,s=t,n=zo(i,e),o=e<r?e:r;for(let c=0;c<o;c++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};var Qi=require("@vkontakte/videoplayer-shared"),Bt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Qi.ValueSubject(e.initial),this.debounced$=new Qi.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,Qi.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var gs=class extends Bt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Zt(this.slow,e,this.params.emaAlphaSlow),this.fast=Zt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ss=class extends Bt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=zo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Zt(this.emaSmoothed,e,this.params.emaAlpha);let r=om(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var vs=class extends Bt{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?Zt(this.smoothed,t,this.params.emaAlpha):t}};var er=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new gs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ss({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new vs({initial:e,label:"liveEdgeDelay",...t})}};var Ko=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var ys=require("@vkontakte/videoplayer-shared");var zi=class i{constructor(e,t){this.currentRepresentation$=new ys.ValueSubject(null);this.currentSegment=null;this.currentSegmentId=0;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if((0,ys.isNullable)(e))return;let t=null,r=null;for(let a of this.representations){let s=a.segmentReference.segments.find(n=>n.time.from<=e&&n.time.to>=e);if(s){t=s,r=a;break}}!t||!r||this.currentSegment?.time.from===t.time.from&&this.currentSegment.time.to===t.time.to||(this.currentSegment=t,this.currentSegmentId=(this.currentSegmentId+1)%Number.MAX_SAFE_INTEGER,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(t.url,r.segmentReference.baseUrl).toString(),id:`subtitle-${this.currentSegmentId.toString(10)}`}))}destroy(){this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let r=i.filterRepresentations(t.representations);if(r){this.representations=r;break}}}static isSupported(e){return!!e?.some(t=>i.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Xe(t.segmentReference))}};var cm=["timeupdate","progress","play","seeked","stalled","waiting"];var Ts=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new H("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new S.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new Tt;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=de(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=tm(e??"",this.manifestUrlString)}catch(n){let o=yf(e)??{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,c)=>!!(this.element?.canPlayType?.(o)&&It()?.isTypeSupported?.(`${o}; codecs="${c}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let c=t.streams[n].filter(({mime:l,codecs:p})=>r(n,l,p)),u=new Set(c.map(({codecs:l})=>l)),d=vf(u);if(d&&(a[n]=c.filter(({codecs:l})=>l.startsWith(d))),n==="video"){let l=this.tuning.preferHDR,p=a.video.some(b=>b.hdr),f=a.video.some(b=>!b.hdr);S.clientChecker.isHDR&&l&&p?a.video=a.video.filter(b=>b.hdr):f&&(a.video=a.video.filter(b=>!b.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=l=>{this.representationSubscription.add((0,S.fromEvent)(l,"error").pipe((0,S.filter)(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?df():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ls())if(r){let l=document.createElement("source");a(l),l.type="application/x-mpegurl",l.src=r.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new Gi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let l=this.manifest.streams.audio.reduce((p,f)=>[...p,...f.representations],[]);this.audioBufferManager=new Gi("audio",this.source,l,n),this.bufferManagers.push(this.audioBufferManager)}if(zi.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new zi(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,S.interval)(1e3).subscribe(l=>{if(this.element?.paused){let p=vo(this.manifestUrlString,2);this.manifestUrlString=de(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add((0,S.merge)(...cm.filter(l=>l!=="waiting").map(l=>(0,S.fromEvent)(this.element,l))).pipe((0,S.map)(l=>this.element?vt(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.filter)(l=>!!l),(0,S.tap)(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(p=>Ko(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:p,isActiveLowLatency:f})=>f&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add((0,S.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=p-b,C=1;Math.abs(E)>g&&(C=1+Math.sign(E)*y),Ko(this.element,C)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let f=0;if(p){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(y=>y.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let l=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:f})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=vo(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),C=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(p)?p:f,P=this.isActiveLowLatency$.getValue(),k=y<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(P&&k);let Y="none";if(P?Y="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&k?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(z=>z.proceedLowLatencyLive()),Y="active_low_latency"):g!==0&&T<E?Y="live_forward_buffering":T<E+x&&(Y="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),Y==="live_forward_buffering"||Y==="live_with_target_offset"){let z=l-(E+C),X=this.normolizeLiveOffset(Math.trunc(g+z/b)),D=Math.abs(X-g),B;!p||D<=this.tuning.dashCmafLive.offsetCalculationError?B=g:X>0&&D>this.tuning.dashCmafLive.offsetCalculationError?B=X:B=0,this.manifestUrlString=de(this.manifestUrlString,B,2)}Y!=="none"&&Y!=="active_low_latency"&&(l=0,this.updateLive())}))}let c=(0,S.merge)(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),u=(0,S.merge)(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:c,someBufferEnded:u}).pipe((0,S.filter)(({allBuffersFull:l,someBufferEnded:p})=>l&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(l=>this.source?.addEventListener("sourceopen",l)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>{let p=[];return l.duration&&p.push(l.duration),Xe(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new bs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=er.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=de(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...cm.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ii(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;this.timeInWaiting+=1e3;let t={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),t={...t,liveLastSeekOffset:this.liveLastSeekOffset};else{let r=this.element.currentTime*1e3;this.videoBufferManager?.maintain(r),this.audioBufferManager?.maintain(r),t={...t,position:r}}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(t))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,r)}seek(e,t){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Ii(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,S.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,S.flattenObject)(t)))}}};var Is=class{constructor(e,t){this.fov=e,this.orientation=t}};var Es=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,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??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,r){this.setRotationSpeed(e,t,r),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,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var lm=`attribute vec2 a_vertex;
|
|
38
59
|
attribute vec2 a_texel;
|
|
39
60
|
|
|
40
61
|
varying vec2 v_texel;
|
|
@@ -45,7 +66,7 @@ void main(void) {
|
|
|
45
66
|
// save texel vector to pass to fragment shader
|
|
46
67
|
v_texel = a_texel;
|
|
47
68
|
}
|
|
48
|
-
`;var
|
|
69
|
+
`;var dm=`#ifdef GL_ES
|
|
49
70
|
precision highp float;
|
|
50
71
|
precision highp int;
|
|
51
72
|
#else
|
|
@@ -88,5 +109,5 @@ void main(void) {
|
|
|
88
109
|
// sample using new coordinates
|
|
89
110
|
gl_FragColor = texture2D(u_texture, tc);
|
|
90
111
|
}
|
|
91
|
-
`;var ls=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new os(this.params.fov,this.params.orientation),this.cameraRotationManager=new us(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"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),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(r,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(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Jf,this.gl.VERTEX_SHADER),r=this.createShader(Xf,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),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,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),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,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,l=t-a,u=e+r,d=t+a,c=e-r,h=t+a;return[s,n,o,l,u,d,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Gt=class{constructor(e){this.subscription=new D.Subscription;this.videoState=new U("stopped");this.elementSize$=new D.ValueSubject(void 0);this.textTracksManager=new De;this.droppedFramesManager=new Wa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ga;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,D.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ls(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};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(oe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ns({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ve(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:D.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,l)=>this.subscription.add(o.subscribe(l,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,D.filter)(u=>!!u.length),(0,D.once)()).subscribe(u=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:u})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,D.filter)(D.isNonNullable),(0,D.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,D.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Je(this.video,t.isLooped,a)),this.subscription.add(ge(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,D.observeElementSize)(this.video),this.elementSize$),s(Oe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,D.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Vo(f));let b=[];for(let S of f.representations){let y=jf(S);b.push(y),this.audioTracksMap.set(y,{stream:f,representation:S})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(_o(h));let f=[];for(let b of h.representations){let S=Hf(b);S&&(f.push(S),this.videoTracksMap.set(S,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(c);for(let h of d.text)for(let f of h.representations){let b=Gf(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}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),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:D.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add((0,D.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,D.fromEvent)(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[h,f]=c,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),u==="manifest_ready")this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(n),f){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,S).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,D.filterChanged)()).subscribe(u=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===u);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(_o(h))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,D.filterChanged)()).subscribe(u=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===u);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Vo(h))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,D.map)(({to:u})=>u==="ready"),(0,D.filterChanged)());this.subscription.add((0,D.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add((0,D.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,D.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,D.observableFrom)(["init"])).pipe((0,D.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:A})=>A===a),o=t.currentVideoTrack$.getValue(),l=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let u=[...this.videoStreamsMap.keys()].find(({id:A})=>A===l.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let c=lt(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(c/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:A})=>A===b?.id)??this.audioStreamsMap.keys().next().value,y=0;if(S){if(n&&!r){let A=es(n,d,this.audioStreamsMap.get(S)??[]);y=Math.max(y,A?.bitrate??-1/0)}if(o){let A=es(o,d,this.audioStreamsMap.get(S)??[]);y=Math.max(y,A?.bitrate??-1/0)}}let I=Et(d,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:f,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:O}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(I=d.filter(A=>!(0,D.isInvariantQuality)(A.quality)).sort((A,Q)=>(Q.bitrate??0)-(A.bitrate??0)).filter(A=>(0,D.isLowerOrEqual)(A.quality,I.quality)&&(0,D.isLowerOrEqual)(A.quality,O))[0]??I);let P=r?I??n:n??I,T=S&&es(P,d,this.audioStreamsMap.get(S)??[]),x=this.videoTracksMap.get(P)?.representation,G=T&&this.audioTracksMap.get(T)?.representation;if(x&&G)return[x,G];if(x&&!G&&this.audioTracksMap.size===0)return[x,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Se(this.video),this.tracer.end()}};var Ni=class extends Gt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Qt=require("@vkontakte/videoplayer-shared");var Fi=class extends Gt{constructor(e){super(e),this.liveOffset=new nt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,Qt.combine)({interval:(0,Qt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(a-1);s<=0&&e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add((0,Qt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Qt.map)(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var Zf=Fe(Ua(),1);var H=require("@vkontakte/videoplayer-shared"),Qe={};var kr=(i,e)=>new H.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),qi=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new U("initializing");this.textTracksManager=new De;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,H.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,H.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,H.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,H.assertNever)(e)}break;default:(0,H.assertNever)(t)}};this.video=be(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),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(oe(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),Se(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:H.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Zf.default)(import("hls.js").then(a=>{e||(Qe.Hls=a.default,Qe.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,H.assertNonNullable)(Qe.Hls,"hls.js not loaded"),this.hls=new Qe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,H.assertNonNullable)(Qe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:H.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=ve(this.video),s=(u,d)=>this.subscription.add(u.subscribe(d,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Je(this.video,e.isLooped,r)),this.subscription.add(ge(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ce(this.video,e.playbackRate,a.playbackRateState$,r)),s(Oe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,H.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(kr(this.hls,Qe.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:H.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(kr(this.hls,Qe.Events.MANIFEST_PARSED).pipe((0,H.map)(({levels:u})=>u.reduce((d,c)=>{let h=c.name||c.height.toString(10),{width:f,height:b}=c,S=It(c.attrs.QUALITY??"")??(0,H.videoSizeToQuality)({width:f,height:b});if(!S)return d;let y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,I={id:h.toString(),quality:S,bitrate:c.bitrate/1e3,size:{width:f,height:b},fps:y};return this.trackLevels.set(h,{track:I,level:c}),d.push(I),d},[]))),t.availableVideoTracks$),s(kr(this.hls,Qe.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let d=[];for(let c of u.subtitleTracks){let h=c.name,f=c.attrs.URI||"",b=c.lang;d.push({id:h,url:f,language:b,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(kr(this.hls,Qe.Events.LEVEL_LOADING).pipe((0,H.map)(({url:u})=>oe(u))),t.hostname$),s(kr(this.hls,Qe.Events.FRAG_CHANGED),u=>{let{video:d,audio:c}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(Tt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:d})=>d===u)?.track,o=kr(this.hls,Qe.Events.LEVEL_SWITCHED).pipe((0,H.map)(({level:u})=>n(this.hls.levels[u])));o.pipe((0,H.filter)(H.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Tt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if((0,H.isNullable)(u))return;let d=this.trackLevels.get(u.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),h=this.hls.currentLevel,f=this.hls.levels[h];!f||d.bitrate>f.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=(0,H.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ye(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){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.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0)}};var em="X-Playback-Duration",qo=async i=>{let e=await ct(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(em)?parseInt(e.headers.get(em),10):void 0};var q=require("@vkontakte/videoplayer-shared");var Ho=Fe(En(),1);var cs=require("@vkontakte/videoplayer-shared");var xx=i=>{let e=null;if(i.QUALITY&&(e=It(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,cs.videoSizeToQuality)({width:t,height:r})}return e??null},Px=(i,e)=>{let t=i.split(`
|
|
92
|
-
`),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),l=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!l)){if(o){let u=(0,Ho.default)(o[1].split(",").map(y=>y.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,c=xx(u),h;u.BANDWIDTH&&(h=parseInt(u.BANDWIDTH,10)/1e3||void 0),!h&&u["AVERAGE-BANDWIDTH"]&&(h=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let f=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,b;if(u.RESOLUTION){let[y,I]=u.RESOLUTION.split("x").map(O=>parseInt(O,10));y&&I&&(b={width:y,height:I})}let S=new URL(t[++s],e).toString();c&&r.push({id:d,quality:c,url:S,bandwidth:h,size:b,fps:f})}if(l){let u=(0,Ho.default)(l[1].split(",").map(f=>f.split("=")).map(([f,b])=>[f,b.replace(/^"|"$/g,"")])),d=u.URI?.replace(/playlist$/,"subtitles.vtt"),c=u.LANGUAGE,h=u.NAME;d&&c&&a.push({type:"internal",id:c,label:h,language:c,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},kx=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Uo=0,tm=async(i,e=i,t)=>{let a=await(await ct(i)).text();Uo+=1;try{let{qualityManifests:s,textTracks:n}=Px(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Uo<=t.manifestRetryMaxCount)return await kx((0,cs.getExponentialDelay)(Uo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),tm(i,e,t)}return{qualityManifests:[],textTracks:[]}},ds=tm;var Ui=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new U("stopped");this.textTracksManager=new De;this.manifests$=new q.ValueSubject([]);this.liveOffset=new nt;this.manifestStartTime$=new q.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,q.assertNever)(t)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:q.VideoQuality.INVARIANT,url:this.params.source.url},ds(ce(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})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:q.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:q.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),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(oe(this.params.source.url)),this.maxSeekBackTime$=new q.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:q.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ve(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ge(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),s(Oe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,q.filterChanged)(),(0,q.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&(0,q.isNonNullable)(u.to)){let c=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(oe(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,q.combine)({startTime:this.manifestStartTime$.pipe((0,q.filter)(q.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe((0,q.map)(o=>o.map(({id:l,quality:u,size:d,bandwidth:c,fps:h})=>({id:l,quality:u,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if((0,q.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:l}=t?.to??r??{};for(let[u,d]of[[o,"mq"],[l,"lq"]]){let c=String(parseFloat(u||""));d&&u&&a.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ce(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),qo(n).then(o=>{if(!(0,q.isNullable)(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,q.isNullable)(l)||!isFinite(l))try{ct(n).then(u=>u.text()).then(u=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(d){let c=new URL(d,n).toString();qo(c).then(h=>{(0,q.isNullable)(h)||this.maxSeekBackTime$.next(h)})}})}catch{}}})}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};var Y=require("@vkontakte/videoplayer-shared");var Hi=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new U("stopped");this.textTracksManager=new De;this.manifests$=new Y.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,Y.assertNever)(t)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Y.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ds(ce(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:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Y.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Y.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ve(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,Y.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&(0,Y.isNonNullable)(u.to)){let c=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let h=this.manifests$.getValue().find(f=>f.id===c);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(oe(h.url));let f=this.params.desiredState.playbackRate.getState(),b=this.params.output.element$.getValue()?.playbackRate;if(f!==b){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(f),S.playbackRate=f)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,Y.map)(o=>o.map(({id:l,quality:u,size:d,bandwidth:c,fps:h})=>({id:l,quality:u,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r)),!Y.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,Y.merge)((0,Y.fromEvent)(o,"addtrack"),(0,Y.fromEvent)(o,"removetrack"),(0,Y.fromEvent)(o,"change"),(0,Y.observableFrom)(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=(0,Y.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Y.observableFrom)(["init"])).pipe((0,Y.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if((0,Y.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,l]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));l&&o&&a.searchParams.set(l,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Y.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var J=require("@vkontakte/videoplayer-shared");var ji=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new U("stopped");this.trackUrls={};this.textTracksManager=new De;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:l}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,J.assertNever)(e)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(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,r=o=>{e.error$.next({id:"MpegProvider",category:J.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ve(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,J.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),s(Oe(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,J.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(l!==u){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(l),d.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,J.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,J.observableFrom)(["init"])).pipe((0,J.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,J.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,J.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Oi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:J.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!(0,J.isInvariantQuality)(o.track.quality)&&(0,J.isLowerOrEqual)(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&(0,J.isHigherOrEqual)(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!(0,J.isInvariantQuality)(u.track.quality)&&(0,J.isHigher)(u.track.quality,e)),l=o.length;l&&(t=o[l-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=Et(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};var Z=require("@vkontakte/videoplayer-shared");var im=require("@vkontakte/videoplayer-shared"),rm=["stun:videostun.mycdn.me:80"],Ax=1e3,wx=3,jo=()=>null,ps=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=jo;this.externalStopCallback=jo;this.externalErrorCallback=jo;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.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:rm}]};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:im.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Ax)}normalizeOptions(e={}){let t={stunServerList:rm,maxRetryNumber:wx,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Gi=class{constructor(e){this.videoState=new U("stopped");this.maxSeekBackTime$=new Z.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,Z.assertNever)(e)}};this.subscription=new Z.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=be(e.container,e.tuning),this.liveStreamClient=new ps(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.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Se(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Z.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,Z.merge)(this.videoState.stateChangeStarted$.pipe((0,Z.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Z.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ve(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Oe(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ge(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,Z.assertNever)(n.to)}},r)).add((0,Z.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Z.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Z.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Z.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qi=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var v=require("@vkontakte/videoplayer-shared");var ft=require("@vkontakte/videoplayer-shared"),am=i=>new ft.Observable(e=>{let t=new ft.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,ft.map)(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,ft.map)(({type:u})=>u!==void 0)),n=new ft.Subject,o=0,l="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),l=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Re=require("@vkontakte/videoplayer-shared");var Wi=null,hs=null;function Go(){return Wi||(Wi=new(window.AudioContext||window.webkitAudioContext)),hs||(hs=new GainNode(Wi,{gain:1}),hs.connect(Wi.destination)),{audioCtx:Wi,gainNode:hs}}var sm=require("@vkontakte/videoplayer-shared");var Yi=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new Re.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe((0,Re.filter)(n=>!!n.type),(0,Re.once)()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){sm.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Re.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Re.filter)(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),(0,Re.once)()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:a}=Go(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${i.errorId} destroyed`);a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch(n){this.volumeMultiplierError$.next({id:i.errorId,category:Re.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:Re.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Go();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var Rx={chunkDuration:5e3,maxParallelRequests:5},zi=class{constructor(e){this.current$=new v.ValueSubject({type:void 0});this.providerError$=new v.Subject;this.noAvailableProvidersError$=new v.Subject;this.volumeMultiplierError$=new v.Subject;this.providerOutput={position$:new v.ValueSubject(0),duration$:new v.ValueSubject(1/0),volume$:new v.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new v.ValueSubject([]),currentVideoStream$:new v.ValueSubject(void 0),availableVideoTracks$:new v.ValueSubject([]),currentVideoTrack$:new v.ValueSubject(void 0),availableAudioStreams$:new v.ValueSubject([]),currentAudioStream$:new v.ValueSubject(void 0),availableAudioTracks$:new v.ValueSubject([]),currentVideoSegmentLength$:new v.ValueSubject(0),currentAudioSegmentLength$:new v.ValueSubject(0),isAudioAvailable$:new v.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new v.ValueSubject(!1),autoVideoTrackLimits$:new v.ValueSubject(void 0),currentBuffer$:new v.ValueSubject(void 0),isBuffering$:new v.ValueSubject(!0),error$:new v.Subject,warning$:new v.Subject,willSeekEvent$:new v.Subject,seekedEvent$:new v.Subject,loopedEvent$:new v.Subject,endedEvent$:new v.Subject,firstBytesEvent$:new v.Subject,loadedMetadataEvent$:new v.Subject,firstFrameEvent$:new v.Subject,canplay$:new v.Subject,isLive$:new v.ValueSubject(void 0),isLowLatency$:new v.ValueSubject(!1),canChangePlaybackSpeed$:new v.ValueSubject(!0),liveTime$:new v.ValueSubject(void 0),liveBufferTime$:new v.ValueSubject(void 0),availableTextTracks$:new v.ValueSubject([]),currentTextTrack$:new v.ValueSubject(void 0),hostname$:new v.ValueSubject(void 0),httpConnectionType$:new v.ValueSubject(void 0),httpConnectionReused$:new v.ValueSubject(void 0),inPiP$:new v.ValueSubject(!1),inFullscreen$:new v.ValueSubject(!1),element$:new v.ValueSubject(void 0),elementVisible$:new v.ValueSubject(!0),availableSources$:new v.ValueSubject(void 0),is3DVideo$:new v.ValueSubject(!1),playbackState$:new v.ValueSubject("")};this.subscription=new v.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=ef([...rf(this.params.tuning),...tf(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,v.isNonNullable)(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,v.flattenObject)(s)),this.screenFormatsIterator=new Qi(s);let n=[...xo(!0),...xo(!1)];this.chromecastFormatsIterator=new Qi(n.filter(o=>(0,v.isNonNullable)(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Yi(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,v.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,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()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,v.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,v.assertNonNullable)(o),new Ni({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Fi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),gr||!this.params.tuning.useHlsJs?new Hi({...n,source:o}):new qi({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Ui({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ji({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Qh({...n,source:o,config:{...Rx,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Gi({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,v.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,v.assertNonNullable)(o),new ti({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,v.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,v.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,v.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,nm.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,r=0;return e.add((0,v.merge)(this.providerOutput.error$,am({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,v.map)(a=>({id:`ProviderHangup:${a}`,category:v.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe((0,v.filter)(({to:s})=>s==="playing"),(0,v.once)()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===v.ErrorCategory.NETWORK,l=a.category===v.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!l,c=u&&!l&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:l,haveFailoverHost:u,tryFailover:c,canReinitProvider:d},c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",(0,v.flattenObject)(n))})),e}};var _=require("@vkontakte/videoplayer-shared");var Lx=5e3,om="one_video_throughput",um="one_video_rtt",Ki=window.navigator.connection,lm=()=>{let i=Ki?.downlink;if((0,_.isNonNullable)(i)&&i!==10)return i*1e3},cm=()=>{let i=Ki?.rtt;if((0,_.isNonNullable)(i)&&i!==3e3)return i},dm=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Qo=class i{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(om)||(e.useBrowserEstimation?lm():void 0)||Lx,r=i.load(um)??(e.useBrowserEstimation?cm():void 0)??0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(r),this.rttAdjustedThroughput$=new _.ValueSubject(dm(t,r,e.rttPenaltyRequestSize)),this.throughput=jt.getSmoothedValue(t,-1,e),this.rtt=jt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=lm();n&&this.throughput.next(n);let o=cm();(0,_.isNonNullable)(o)&&this.rtt.next(o)};Ki&&"onchange"in Ki&&this.subscription.add((0,_.fromEvent)(Ki,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{_.safeStorage.set(om,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{_.safeStorage.set(um,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,_.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,_.map)(({throughput:a,rtt:s})=>dm(a,s,e.rttPenaltyRequestSize)),(0,_.filter)(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,_.now)(),a=new _.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,_.fromEvent)(e,"progress").pipe((0,_.once)()).subscribe(s=>{t=s.loaded,r=(0,_.now)()}));break;case 1:case 0:a.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,_.now)()}));break}a.add((0,_.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,_.now)(),l=n-t,u=o-r;this.addRawSpeed(l,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=(0,_.now)(),n=0,o=(0,_.now)(),l=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(a,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=(0,_.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=c.byteLength,s=(0,_.now)()}else n+=c.byteLength;o=(0,_.now)()}else a+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,_.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,_.now)()-o,this.concurrentDownloads.size),n=0,o=(0,_.now)());await r?.read().then(u,l)}};this.concurrentDownloads.add(e),r?.read().then(u,l)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return parseInt(t,10)??void 0}},pm=Qo;var Ji=require("@vkontakte/videoplayer-shared"),hm={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:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Ji.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ji.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{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:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!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},fm=i=>({...(0,Ji.fillWithDefault)(i,hm),configName:[...i.configName??[],...hm.configName]});var p=require("@vkontakte/videoplayer-shared");var mt=require("@vkontakte/videoplayer-shared"),Wo=({seekState:i,position$:e})=>(0,mt.merge)(i.stateChangeEnded$.pipe((0,mt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,mt.filter)(mt.isNonNullable)),e.pipe((0,mt.filter)(()=>i.getState().state==="none")));var mm=require("@vkontakte/videoplayer-shared"),bm=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,mm.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var fs=require("@vkontakte/videoplayer-shared"),Sm=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,fs.filter)(a=>a.length>0),(0,fs.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Xi=class{constructor(e={configName:[]},t){this.subscription=new p.Subscription;this.logger=new p.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new p.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new U("stopped"),seekState:new U({state:"none"}),volume:new U({volume:1,muted:!1}),videoTrack:new U(void 0),videoStream:new U(void 0),audioStream:new U(void 0),autoVideoTrackSwitching:new U(!0),autoVideoTrackLimits:new U({}),isLooped:new U(!1),playbackRate:new U(1),externalTextTracks:new U([]),internalTextTracks:new U([]),currentTextTrack:new U(void 0),textTrackCuesSettings:new U({}),cameraOrientation:new U({x:0,y:0})};this.info={playbackState$:new p.ValueSubject("stopped"),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableVideoStreams$:new p.ValueSubject([]),currentVideoStream$:new p.ValueSubject(void 0),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),availableAudioStreams$:new p.ValueSubject([]),currentAudioStream$:new p.ValueSubject(void 0),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),currentPlaybackRate$:new p.ValueSubject(1),currentBuffer$:new p.ValueSubject({start:0,end:0}),isBuffering$:new p.ValueSubject(!0),isStalled$:new p.ValueSubject(!1),isEnded$:new p.ValueSubject(!1),isLooped$:new p.ValueSubject(!1),isLive$:new p.ValueSubject(void 0),canChangePlaybackSpeed$:new p.ValueSubject(void 0),atLiveEdge$:new p.ValueSubject(void 0),atLiveDurationEdge$:new p.ValueSubject(void 0),liveTime$:new p.ValueSubject(void 0),liveBufferTime$:new p.ValueSubject(void 0),currentFormat$:new p.ValueSubject(void 0),availableTextTracks$:new p.ValueSubject([]),currentTextTrack$:new p.ValueSubject(void 0),throughputEstimation$:new p.ValueSubject(void 0),rttEstimation$:new p.ValueSubject(void 0),videoBitrate$:new p.ValueSubject(void 0),hostname$:new p.ValueSubject(void 0),httpConnectionType$:new p.ValueSubject(void 0),httpConnectionReused$:new p.ValueSubject(void 0),surface$:new p.ValueSubject("none"),chromecastState$:new p.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new p.ValueSubject(void 0),intrinsicVideoSize$:new p.ValueSubject(void 0),availableSources$:new p.ValueSubject(void 0),is3DVideo$:new p.ValueSubject(!1),currentVideoSegmentLength$:new p.ValueSubject(0),currentAudioSegmentLength$:new p.ValueSubject(0)};this.events={inited$:new p.Subject,ready$:new p.Subject,started$:new p.Subject,playing$:new p.Subject,paused$:new p.Subject,stopped$:new p.Subject,willStart$:new p.Subject,willResume$:new p.Subject,willPause$:new p.Subject,willStop$:new p.Subject,willDestruct$:new p.Subject,watchCoverageRecord$:new p.Subject,watchCoverageLive$:new p.Subject,managedError$:new p.Subject,fatalError$:new p.Subject,ended$:new p.Subject,looped$:new p.Subject,seeked$:new p.Subject,willSeek$:new p.Subject,firstBytes$:new p.Subject,loadedMetadata$:new p.Subject,firstFrame$:new p.Subject,canplay$:new p.Subject,log$:new p.Subject};this.experimental={element$:new p.ValueSubject(void 0),tuningConfigName$:new p.ValueSubject([]),enableDebugTelemetry$:new p.ValueSubject(!1),dumpTelemetry:Uh};if(this.initLogs(),this.tuning=fm(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new oa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new pm(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,a,s)=>{let n=Reflect.get(r,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(l){let u=o.map(h=>JSON.stringify(h,(f,b)=>{let S=typeof b;return["number","string","boolean"].includes(S)?b:b===null?null:`<${S}>`})),d=`Player.${String(a)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:p.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){return this.config=e,this.tracer.log("initVideo",(0,p.flattenObject)(e)),this.domContainer=bm(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new zi({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!oi()?(this.tracer.log("request play from hidden tab"),(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=r&&!a&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,p.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return 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.providerContainer.providerOutput.availableVideoTracks$.pipe((0,p.filter)(r=>r.length>0),(0,p.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,p.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){(0,p.assertNonNullable)(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,p.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Sm(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,p.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,p.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.filter)(({from:e})=>e==="stopped"),(0,p.once)()).subscribe(()=>{this.initedAt=(0,p.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,p.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:p.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,p.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,p.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,p.map)(n=>n.destination),(0,p.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,p.map)(n=>n.map(({quality:o})=>o).sort((o,l)=>(0,p.isInvariantQuality)(o)?1:(0,p.isInvariantQuality)(l)?-1:(0,p.isHigher)(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let l of n)l.fps&&(o[l.quality]=l.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,p.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,p.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe((0,p.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,p.combine)({hasLiveOffsetByPaused:(0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(n=>n.to),(0,p.filterChanged)(),(0,p.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,p.combine)({atLiveEdge:(0,p.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Wo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,p.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,p.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,p.map)(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.muted),(0,p.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.volume),(0,p.filterChanged)()).subscribe(this.info.volume$)).add(Wo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,p.merge)(e.providerOutput.endedEvent$.pipe((0,p.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,p.mapTo)(!1))).pipe((0,p.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,p.map)(n=>({id:n?`No${n}`:"NoProviders",category:p.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,p.once)(),(0,p.map)(n=>n??(0,p.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new p.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:n})=>n==="playing"),(0,p.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,p.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,p.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,p.filterChanged)());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add((0,p.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,p.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":l?u?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,p.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new p.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,p.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(r=>r.length>0),(0,p.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=Et(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,p.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,p.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;(0,p.assertNonNullable)(this.providerContainer),(0,p.assertNonNullable)(e),qh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Fh(t)),this.providerContainer.current$.subscribe(({type:t})=>ii("provider",t)),e.duration$.subscribe(t=>ii("duration",t)),e.availableVideoTracks$.pipe((0,p.filter)(t=>!!t.length),(0,p.once)()).subscribe(t=>ii("tracks",t)),this.events.fatalError$.subscribe(new he("fatalError")),this.events.managedError$.subscribe(new he("managedError")),e.position$.subscribe(new he("position")),e.currentVideoTrack$.pipe((0,p.map)(t=>t?.quality)).subscribe(new he("quality")),this.info.currentBuffer$.subscribe(new he("buffer")),e.isBuffering$.subscribe(new he("isBuffering"))].forEach(t=>this.subscription.add(t)),ii("codecs",Zh())}initTracerSubscription(){let e=(0,p.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,p.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,p.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,p.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,p.filter)(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),(0,p.filterChanged)((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,p.filter)(r=>r>0),(0,p.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,p.filter)(r=>r>0),(0,p.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,p.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,p.filter)(r=>r.end>0),(0,p.filterChanged)((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe((0,p.filterChanged)())}).pipe((0,p.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,p.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,p.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,p.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,p.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,p.filter)(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),(0,p.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,p.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,p.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,p.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,p.filter)(({throughputEstimation:r,rtt:a})=>!!r&&!!a),(0,p.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!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?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:p.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,p.merge)((0,p.fromEvent)(document,"visibilitychange"),(0,p.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,p.flattenObject)({quality:t,availableTracks:(0,p.flattenObject)(e),track:(0,p.flattenObject)(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var et=require("@vkontakte/videoplayer-shared"),$x=`@vkontakte/videoplayer-core@${Is}`;
|
|
112
|
+
`;var xs=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Is(this.params.fov,this.params.orientation),this.cameraRotationManager=new Es(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"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),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(r,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(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(lm,this.gl.VERTEX_SHADER),r=this.createShader(dm,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),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,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),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,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,c=t-a,u=e+r,d=t+a,l=e-r,p=t+a;return[s,n,o,c,u,d,l,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var tr=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("stopped");this.elementSize$=new q.ValueSubject(void 0);this.textTracksManager=new _e;this.droppedFramesManager=new ns;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new fi;this.audioTrackSwitchHistory=new fi;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),A(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"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&A(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,q.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new xs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ve(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(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ts({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Ie(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:q.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,c)=>this.subscription.add(o.subscribe(c,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,q.filter)(u=>!!u.length),(0,q.once)()).subscribe(u=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:u})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,q.filter)(q.isNonNullable),(0,q.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,q.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(st(this.video,t.isLooped,a)),this.subscription.add(Te(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Oe(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,q.observeElementSize)(this.video),this.elementSize$),s(Ne(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,q.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(Yo(f));let b=[];for(let g of f.representations){let y=am(g);b.push(y),this.audioTracksMap.set(y,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let l=[];for(let p of d.video){l.push(Qo(p));let f=[];for(let b of p.representations){let g=im(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}this.params.output.availableVideoStreams$.next(l);for(let p of d.text)for(let f of p.representations){let b=fs(p,f);this.textTracksMap.set(b,{stream:p,representation:f})}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),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:q.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add((0,q.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,q.fromEvent)(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoAudioRepresentations();if(!l)return;let[p,f]=l,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),u==="manifest_ready")this.player.initRepresentations(p.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),f){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,g).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,q.filterChanged)()).subscribe(u=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===u);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[l,{stream:p}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(l),e.currentVideoStream$.next(Qo(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,q.filterChanged)()).subscribe(u=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===u);if(!d){e.currentAudioStream$.next(void 0);return}let[l,{stream:p}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Yo(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,q.map)(({to:u})=>u==="ready"),(0,q.filterChanged)());this.subscription.add((0,q.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add((0,q.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=(0,q.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(c.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:k})=>k===a),o=t.currentVideoTrack$.getValue(),c=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let u=[...this.videoStreamsMap.keys()].find(({id:k})=>k===c.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let l=vt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(l/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:k})=>k===b?.id)??this.audioStreamsMap.keys().next().value,y=0;if(g){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let k=as(n,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,k?.bitrate??-1/0)}else{let k=hs(n,d,this.audioStreamsMap.get(g)??[]);y=Math.max(y,k?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let k=as(o,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,k?.bitrate??-1/0)}else{let k=hs(o,d,this.audioStreamsMap.get(g)??[]);y=Math.max(y,k?.bitrate??-1/0)}}let E=Dt(d,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),C=r?E??n:n??E,x;this.params.tuning.useSeparateAudioVideoABR?x=g&&af(C,d,this.audioStreamsMap.get(g)??[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):x=g&&hs(C,d,this.audioStreamsMap.get(g)??[]);let T=this.videoTracksMap.get(C)?.representation,P=x&&this.audioTracksMap.get(x)?.representation;if(T&&P)return[T,P];if(T&&!P&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ee(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ye(this.video),this.tracer.end()}};var Ji=class extends tr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var rr=require("@vkontakte/videoplayer-shared");var Xi=class extends tr{constructor(e){super(e),this.liveOffset=new bt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,rr.combine)({interval:(0,rr.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(a-1);s<=0&&e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add((0,rr.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,rr.map)(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=fs(a,a);this.params.desiredState.internalTextTracks.startTransitionTo([s])}else this.params.desiredState.internalTextTracks.startTransitionTo([])}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var pm=We(ts(),1);var j=require("@vkontakte/videoplayer-shared"),Ze={};var Vr=(i,e)=>new j.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Zi=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new H("initializing");this.textTracksManager=new _e;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,j.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,j.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,j.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,j.assertNever)(e)}break;default:(0,j.assertNever)(t)}};this.video=ve(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),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(ue(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),ye(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:j.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,pm.default)(import("hls.js").then(a=>{e||(Ze.Hls=a.default,Ze.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,j.assertNonNullable)(Ze.Hls,"hls.js not loaded"),this.hls=new Ze.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,j.assertNonNullable)(Ze.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:j.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=Ie(this.video),s=(u,d)=>this.subscription.add(u.subscribe(d,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(st(this.video,e.isLooped,r)),this.subscription.add(Te(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Oe(this.video,e.playbackRate,a.playbackRateState$,r)),s(Ne(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,j.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Vr(this.hls,Ze.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:j.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Vr(this.hls,Ze.Events.MANIFEST_PARSED).pipe((0,j.map)(({levels:u})=>u.reduce((d,l)=>{let p=l.name||l.height.toString(10),{width:f,height:b}=l,g=Ct(l.attrs.QUALITY??"")??(0,j.videoSizeToQuality)({width:f,height:b});if(!g)return d;let y=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,E={id:p.toString(),quality:g,bitrate:l.bitrate/1e3,size:{width:f,height:b},fps:y};return this.trackLevels.set(p,{track:E,level:l}),d.push(E),d},[]))),t.availableVideoTracks$),s(Vr(this.hls,Ze.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let d=[];for(let l of u.subtitleTracks){let p=l.name,f=l.attrs.URI||"",b=l.lang;d.push({id:p,url:f,language:b,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Vr(this.hls,Ze.Events.LEVEL_LOADING).pipe((0,j.map)(({url:u})=>ue(u))),t.hostname$),s(Vr(this.hls,Ze.Events.FRAG_CHANGED),u=>{let{video:d,audio:l}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3)}),this.subscription.add(Mt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:d})=>d===u)?.track,o=Vr(this.hls,Ze.Events.LEVEL_SWITCHED).pipe((0,j.map)(({level:u})=>n(this.hls.levels[u])));o.pipe((0,j.filter)(j.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Mt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if((0,j.isNullable)(u))return;let d=this.trackLevels.get(u.id)?.level;if(!d)return;let l=this.hls.levels.indexOf(d),p=this.hls.currentLevel,f=this.hls.levels[p];!f||d.bitrate>f.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let c=(0,j.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,j.observableFrom)(["init"])).pipe((0,j.debounce)(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Ee(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:j.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){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.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0)}};var hm="X-Playback-Duration",Jo=async i=>{let e=await yt(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(hm)?parseInt(e.headers.get(hm),10):void 0};var U=require("@vkontakte/videoplayer-shared");var Zo=We(Mn(),1);var Ps=require("@vkontakte/videoplayer-shared");var $x=i=>{let e=null;if(i.QUALITY&&(e=Ct(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,Ps.videoSizeToQuality)({width:t,height:r})}return e??null},Lx=(i,e)=>{let t=i.split(`
|
|
113
|
+
`),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),c=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!c)){if(o){let u=(0,Zo.default)(o[1].split(",").map(y=>y.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,l=$x(u),p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let f=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,b;if(u.RESOLUTION){let[y,E]=u.RESOLUTION.split("x").map(C=>parseInt(C,10));y&&E&&(b={width:y,height:E})}let g=new URL(t[++s],e).toString();l&&r.push({id:d,quality:l,url:g,bandwidth:p,size:b,fps:f})}if(c){let u=(0,Zo.default)(c[1].split(",").map(f=>f.split("=")).map(([f,b])=>[f,b.replace(/^"|"$/g,"")])),d=u.URI?.replace(/playlist$/,"subtitles.vtt"),l=u.LANGUAGE,p=u.NAME;d&&l&&a.push({type:"internal",id:l,label:p,language:l,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},Mx=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Xo=0,fm=async(i,e=i,t)=>{let a=await(await yt(i)).text();Xo+=1;try{let{qualityManifests:s,textTracks:n}=Lx(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Xo<=t.manifestRetryMaxCount)return await Mx((0,Ps.getExponentialDelay)(Xo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),fm(i,e,t)}return{qualityManifests:[],textTracks:[]}},As=fm;var ea=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new H("stopped");this.textTracksManager=new _e;this.manifests$=new U.ValueSubject([]);this.liveOffset=new bt;this.manifestStartTime$=new U.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,U.assertNever)(t)}};this.params=e,this.video=ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:U.VideoQuality.INVARIANT,url:this.params.source.url},As(de(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})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:U.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:U.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),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(ue(this.params.source.url)),this.maxSeekBackTime$=new U.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:U.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=Ie(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Te(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ne(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,U.filterChanged)(),(0,U.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&(0,U.isNonNullable)(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(f=>f.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from==="changing_manifest"&&this.videoState.setState(c.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,U.combine)({startTime:this.manifestStartTime$.pipe((0,U.filter)(U.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),r)),this.subscription.add(this.manifests$.pipe((0,U.map)(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:p})=>({id:c,quality:u,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,U.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.selectManifest();if((0,U.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:c}=t?.to??r??{};for(let[u,d]of[[o,"mq"],[c,"lq"]]){let l=String(parseFloat(u||""));d&&u&&a.searchParams.set(d,l)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=de(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Jo(n).then(o=>{if(!(0,U.isNullable)(o))this.maxSeekBackTime$.next(o);else{let c=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,U.isNullable)(c)||!isFinite(c))try{yt(n).then(u=>u.text()).then(u=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(d){let l=new URL(d,n).toString();Jo(l).then(p=>{(0,U.isNullable)(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){Ee(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};var W=require("@vkontakte/videoplayer-shared");var ta=class{constructor(e){this.subscription=new W.Subscription;this.videoState=new H("stopped");this.textTracksManager=new _e;this.manifests$=new W.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,W.assertNever)(t)}};this.params=e,this.video=ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:W.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),As(de(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:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:W.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:W.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=Ie(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,W.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(st(this.video,t.isLooped,r)),this.subscription.add(Te(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&(0,W.isNonNullable)(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(f=>f.id===l);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(p.url));let f=this.params.desiredState.playbackRate.getState(),b=this.params.output.element$.getValue()?.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from==="changing_manifest"&&this.videoState.setState(c.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,W.map)(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:p})=>({id:c,quality:u,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,r)),!W.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,W.merge)((0,W.fromEvent)(o,"addtrack"),(0,W.fromEvent)(o,"removetrack"),(0,W.fromEvent)(o,"change"),(0,W.observableFrom)(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},r))}let n=(0,W.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,W.observableFrom)(["init"])).pipe((0,W.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.selectManifest();if((0,W.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,c]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));c&&o&&a.searchParams.set(c,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){Ee(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:W.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var J=require("@vkontakte/videoplayer-shared");var ra=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new _e;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(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()):r?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,J.assertNever)(e)}};this.params=e,this.video=ve(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(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,r=o=>{e.error$.next({id:"MpegProvider",category:J.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=Ie(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,J.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(st(this.video,t.isLooped,r)),this.subscription.add(Te(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ne(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,J.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(c!==u){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(c),d.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,J.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,J.observableFrom)(["init"])).pipe((0,J.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,J.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,J.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Wi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){Ee(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:J.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!(0,J.isInvariantQuality)(o.track.quality)&&(0,J.isLowerOrEqual)(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&(0,J.isHigherOrEqual)(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!(0,J.isInvariantQuality)(u.track.quality)&&(0,J.isHigher)(u.track.quality,e)),c=o.length;c&&(t=o[c-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=Dt(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};var Z=require("@vkontakte/videoplayer-shared");var bm=require("@vkontakte/videoplayer-shared"),mm=["stun:videostun.mycdn.me:80"],Cx=1e3,Dx=3,eu=()=>null,ks=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=eu;this.externalStopCallback=eu;this.externalErrorCallback=eu;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.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:mm}]};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:bm.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Cx)}normalizeOptions(e={}){let t={stunServerList:mm,maxRetryNumber:Dx,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ia=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new Z.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),A(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()):r?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,Z.assertNever)(e)}};this.subscription=new Z.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ve(e.container,e.tuning),this.liveStreamClient=new ks(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.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ye(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Z.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,Z.merge)(this.videoState.stateChangeStarted$.pipe((0,Z.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Z.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=Ie(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Ne(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Te(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,Z.assertNever)(n.to)}},r)).add((0,Z.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}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(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Z.VideoQuality.INVARIANT}),this.video.srcObject=e,A(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:Z.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ee(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Z.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var aa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var v=require("@vkontakte/videoplayer-shared");var Pt=require("@vkontakte/videoplayer-shared"),gm=i=>new Pt.Observable(e=>{let t=new Pt.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,Pt.map)(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,Pt.map)(({type:u})=>u!==void 0)),n=new Pt.Subject,o=0,c="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),c=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),c="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(c),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Le=require("@vkontakte/videoplayer-shared");var sa=null,ws=null;function tu(){return sa||(sa=new(window.AudioContext||window.webkitAudioContext)),ws||(ws=new GainNode(sa,{gain:1}),ws.connect(sa.destination)),{audioCtx:sa,gainNode:ws}}var Sm=require("@vkontakte/videoplayer-shared");var na=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new Le.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe((0,Le.filter)(n=>!!n.type),(0,Le.once)()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){Sm.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Le.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Le.filter)(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),(0,Le.once)()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:a}=tu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${i.errorId} destroyed`);a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch(n){this.volumeMultiplierError$.next({id:i.errorId,category:Le.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:Le.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=tu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var Bx={chunkDuration:5e3,maxParallelRequests:5},oa=class{constructor(e){this.current$=new v.ValueSubject({type:void 0});this.providerError$=new v.Subject;this.noAvailableProvidersError$=new v.Subject;this.volumeMultiplierError$=new v.Subject;this.providerOutput={position$:new v.ValueSubject(0),duration$:new v.ValueSubject(1/0),volume$:new v.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new v.ValueSubject([]),currentVideoStream$:new v.ValueSubject(void 0),availableVideoTracks$:new v.ValueSubject([]),currentVideoTrack$:new v.ValueSubject(void 0),availableAudioStreams$:new v.ValueSubject([]),currentAudioStream$:new v.ValueSubject(void 0),availableAudioTracks$:new v.ValueSubject([]),currentVideoSegmentLength$:new v.ValueSubject(0),currentAudioSegmentLength$:new v.ValueSubject(0),isAudioAvailable$:new v.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new v.ValueSubject(!1),autoVideoTrackLimits$:new v.ValueSubject(void 0),currentBuffer$:new v.ValueSubject(void 0),isBuffering$:new v.ValueSubject(!0),error$:new v.Subject,warning$:new v.Subject,willSeekEvent$:new v.Subject,seekedEvent$:new v.Subject,loopedEvent$:new v.Subject,endedEvent$:new v.Subject,firstBytesEvent$:new v.Subject,loadedMetadataEvent$:new v.Subject,firstFrameEvent$:new v.Subject,canplay$:new v.Subject,isLive$:new v.ValueSubject(void 0),isLowLatency$:new v.ValueSubject(!1),canChangePlaybackSpeed$:new v.ValueSubject(!0),liveTime$:new v.ValueSubject(void 0),liveBufferTime$:new v.ValueSubject(void 0),availableTextTracks$:new v.ValueSubject([]),currentTextTrack$:new v.ValueSubject(void 0),hostname$:new v.ValueSubject(void 0),httpConnectionType$:new v.ValueSubject(void 0),httpConnectionReused$:new v.ValueSubject(void 0),inPiP$:new v.ValueSubject(!1),inFullscreen$:new v.ValueSubject(!1),element$:new v.ValueSubject(void 0),elementVisible$:new v.ValueSubject(!0),availableSources$:new v.ValueSubject(void 0),is3DVideo$:new v.ValueSubject(!1),playbackState$:new v.ValueSubject("")};this.subscription=new v.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=bf([...Sf(this.params.tuning),...gf(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,v.isNonNullable)(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,v.flattenObject)(s)),this.screenFormatsIterator=new aa(s);let n=[...Co(!0),...Co(!1)];this.chromecastFormatsIterator=new aa(n.filter(o=>(0,v.isNonNullable)(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new na(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,v.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,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()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,v.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,v.assertNonNullable)(o),new Ji({...n,source:o,sourceHls:c})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Xi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),wr||!this.params.tuning.useHlsJs?new ta({...n,source:o}):new Zi({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ea({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ra({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new uf({...n,source:o,config:{...Bx,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ia({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,v.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,v.assertNonNullable)(o),new di({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,v.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,v.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,v.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,vm.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,r=0;return e.add((0,v.merge)(this.providerOutput.error$,gm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,v.map)(a=>({id:`ProviderHangup:${a}`,category:v.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe((0,v.filter)(({to:s})=>s==="playing"),(0,v.once)()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===v.ErrorCategory.NETWORK,c=a.category===v.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!c,l=u&&!c&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:c,haveFailoverHost:u,tryFailover:l,canReinitProvider:d},l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",(0,v.flattenObject)(n))})),e}};var _=require("@vkontakte/videoplayer-shared");var Vx=5e3,ym="one_video_throughput",Tm="one_video_rtt",ua=window.navigator.connection,Im=()=>{let i=ua?.downlink;if((0,_.isNonNullable)(i)&&i!==10)return i*1e3},Em=()=>{let i=ua?.rtt;if((0,_.isNonNullable)(i)&&i!==3e3)return i},xm=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},ru=class i{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(ym)||(e.useBrowserEstimation?Im():void 0)||Vx,r=i.load(Tm)??(e.useBrowserEstimation?Em():void 0)??0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(r),this.rttAdjustedThroughput$=new _.ValueSubject(xm(t,r,e.rttPenaltyRequestSize)),this.throughput=er.getSmoothedValue(t,-1,e),this.rtt=er.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Im();n&&this.throughput.next(n);let o=Em();(0,_.isNonNullable)(o)&&this.rtt.next(o)};ua&&"onchange"in ua&&this.subscription.add((0,_.fromEvent)(ua,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{_.safeStorage.set(ym,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{_.safeStorage.set(Tm,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,_.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,_.map)(({throughput:a,rtt:s})=>xm(a,s,e.rttPenaltyRequestSize)),(0,_.filter)(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,_.now)(),a=new _.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,_.fromEvent)(e,"progress").pipe((0,_.once)()).subscribe(s=>{t=s.loaded,r=(0,_.now)()}));break;case 1:case 0:a.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,_.now)()}));break}a.add((0,_.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,_.now)(),c=n-t,u=o-r;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=(0,_.now)(),n=0,o=(0,_.now)(),c=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:l})=>{if(d)!t&&this.addRawSpeed(a,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=(0,_.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=l.byteLength,s=(0,_.now)()}else n+=l.byteLength;o=(0,_.now)()}else a+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,_.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,_.now)()-o,this.concurrentDownloads.size),n=0,o=(0,_.now)());await r?.read().then(u,c)}};this.concurrentDownloads.add(e),r?.read().then(u,c)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return parseInt(t,10)??void 0}},Pm=ru;var ca=require("@vkontakte/videoplayer-shared"),Am={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:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:ca.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ca.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{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:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!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},km=i=>({...(0,ca.fillWithDefault)(i,Am),configName:[...i.configName??[],...Am.configName]});var h=require("@vkontakte/videoplayer-shared");var At=require("@vkontakte/videoplayer-shared"),iu=({seekState:i,position$:e})=>(0,At.merge)(i.stateChangeEnded$.pipe((0,At.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,At.filter)(At.isNonNullable)),e.pipe((0,At.filter)(()=>i.getState().state==="none")));var wm=require("@vkontakte/videoplayer-shared"),Rm=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,wm.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var Rs=require("@vkontakte/videoplayer-shared"),$m=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,Rs.filter)(a=>a.length>0),(0,Rs.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var la=class{constructor(e={configName:[]},t=h.Tracer.createRootTracer(!1)){this.subscription=new h.Subscription;this.logger=new h.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new h.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;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),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 h.ValueSubject("stopped"),position$:new h.ValueSubject(0),duration$:new h.ValueSubject(1/0),muted$:new h.ValueSubject(!1),volume$:new h.ValueSubject(1),availableVideoStreams$:new h.ValueSubject([]),currentVideoStream$:new h.ValueSubject(void 0),availableQualities$:new h.ValueSubject([]),availableQualitiesFps$:new h.ValueSubject({}),currentQuality$:new h.ValueSubject(void 0),isAutoQualityEnabled$:new h.ValueSubject(!0),autoQualityLimitingAvailable$:new h.ValueSubject(!1),autoQualityLimits$:new h.ValueSubject({}),availableAudioStreams$:new h.ValueSubject([]),currentAudioStream$:new h.ValueSubject(void 0),availableAudioTracks$:new h.ValueSubject([]),isAudioAvailable$:new h.ValueSubject(!0),currentPlaybackRate$:new h.ValueSubject(1),currentBuffer$:new h.ValueSubject({start:0,end:0}),isBuffering$:new h.ValueSubject(!0),isStalled$:new h.ValueSubject(!1),isEnded$:new h.ValueSubject(!1),isLooped$:new h.ValueSubject(!1),isLive$:new h.ValueSubject(void 0),canChangePlaybackSpeed$:new h.ValueSubject(void 0),atLiveEdge$:new h.ValueSubject(void 0),atLiveDurationEdge$:new h.ValueSubject(void 0),liveTime$:new h.ValueSubject(void 0),liveBufferTime$:new h.ValueSubject(void 0),currentFormat$:new h.ValueSubject(void 0),availableTextTracks$:new h.ValueSubject([]),currentTextTrack$:new h.ValueSubject(void 0),throughputEstimation$:new h.ValueSubject(void 0),rttEstimation$:new h.ValueSubject(void 0),videoBitrate$:new h.ValueSubject(void 0),hostname$:new h.ValueSubject(void 0),httpConnectionType$:new h.ValueSubject(void 0),httpConnectionReused$:new h.ValueSubject(void 0),surface$:new h.ValueSubject("none"),chromecastState$:new h.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new h.ValueSubject(void 0),intrinsicVideoSize$:new h.ValueSubject(void 0),availableSources$:new h.ValueSubject(void 0),is3DVideo$:new h.ValueSubject(!1),currentVideoSegmentLength$:new h.ValueSubject(0),currentAudioSegmentLength$:new h.ValueSubject(0)};this.events={inited$:new h.Subject,ready$:new h.Subject,started$:new h.Subject,playing$:new h.Subject,paused$:new h.Subject,stopped$:new h.Subject,willStart$:new h.Subject,willResume$:new h.Subject,willPause$:new h.Subject,willStop$:new h.Subject,willDestruct$:new h.Subject,watchCoverageRecord$:new h.Subject,watchCoverageLive$:new h.Subject,managedError$:new h.Subject,fatalError$:new h.Subject,ended$:new h.Subject,looped$:new h.Subject,seeked$:new h.Subject,willSeek$:new h.Subject,firstBytes$:new h.Subject,loadedMetadata$:new h.Subject,firstFrame$:new h.Subject,canplay$:new h.Subject,log$:new h.Subject};this.experimental={element$:new h.ValueSubject(void 0),tuningConfigName$:new h.ValueSubject([]),enableDebugTelemetry$:new h.ValueSubject(!1),dumpTelemetry:Xh};if(this.initLogs(),this.tuning=km(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ya({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Pm(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,a,s)=>{let n=Reflect.get(r,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(c){let u=o.map(p=>JSON.stringify(p,(f,b)=>{let g=typeof b;return["number","string","boolean"].includes(g)?b:b===null?null:`<${g}>`})),d=`Player.${String(a)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:h.ErrorCategory.WTF,message:l,thrown:c}),c}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",(0,h.flattenObject)(r)),this.domContainer=Rm(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new oa({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Si()?(this.tracer.log("request play from hidden tab"),(0,h.fromEvent)(document,"visibilitychange").pipe((0,h.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=r&&!a&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,h.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return 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.providerContainer.providerOutput.availableVideoTracks$.pipe((0,h.filter)(r=>r.length>0),(0,h.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,h.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){(0,h.assertNonNullable)(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,h.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return $m(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,h.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,h.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.filter)(({from:e})=>e==="stopped"),(0,h.once)()).subscribe(()=>{this.initedAt=(0,h.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,h.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:h.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,h.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,h.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,h.map)(n=>n.destination),(0,h.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,h.map)(n=>n.map(({quality:o})=>o).sort((o,c)=>(0,h.isInvariantQuality)(o)?1:(0,h.isInvariantQuality)(c)?-1:(0,h.isHigher)(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let c of n)c.fps&&(o[c.quality]=c.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,h.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,h.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,h.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,h.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe((0,h.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,h.combine)({hasLiveOffsetByPaused:(0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(n=>n.to),(0,h.filterChanged)(),(0,h.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,h.combine)({atLiveEdge:(0,h.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:iu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,h.map)(({isLive:n,position:o,isLowLatency:c})=>{let u=this.getActiveLiveDelay(c);return n&&Math.abs(o)<u/1e3}),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,h.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,h.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,h.map)(({isLive:n,position:o,duration:c})=>n&&(Math.abs(c)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.muted),(0,h.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.volume),(0,h.filterChanged)()).subscribe(this.info.volume$)).add(iu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,h.merge)(e.providerOutput.endedEvent$.pipe((0,h.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,h.mapTo)(!1))).pipe((0,h.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,h.map)(n=>({id:n?`No${n}`:"NoProviders",category:h.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,h.once)(),(0,h.map)(n=>n??(0,h.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new h.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new h.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.filter)(({to:n})=>n==="playing"),(0,h.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,h.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,h.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,h.filterChanged)());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add((0,h.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,h.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),c=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":c?u?n?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,h.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new h.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,h.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,h.filter)(r=>r.length>0),(0,h.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=Dt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,h.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,h.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;(0,h.assertNonNullable)(this.providerContainer),(0,h.assertNonNullable)(e),Jh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Kh(t)),this.providerContainer.current$.subscribe(({type:t})=>hi("provider",t)),e.duration$.subscribe(t=>hi("duration",t)),e.availableVideoTracks$.pipe((0,h.filter)(t=>!!t.length),(0,h.once)()).subscribe(t=>hi("tracks",t)),this.events.fatalError$.subscribe(new be("fatalError")),this.events.managedError$.subscribe(new be("managedError")),e.position$.subscribe(new be("position")),e.currentVideoTrack$.pipe((0,h.map)(t=>t?.quality)).subscribe(new be("quality")),this.info.currentBuffer$.subscribe(new be("buffer")),e.isBuffering$.subscribe(new be("isBuffering"))].forEach(t=>this.subscription.add(t)),hi("codecs",mf())}initTracerSubscription(){let e=(0,h.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,h.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,h.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,h.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,h.filter)(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),(0,h.filterChanged)((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,h.filter)(r=>r>0),(0,h.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,h.filter)(r=>r>0),(0,h.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,h.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,h.filter)(r=>r.end>0),(0,h.filterChanged)((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe((0,h.filterChanged)())}).pipe((0,h.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,h.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,h.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,h.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,h.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,h.filter)(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),(0,h.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,h.filterChanged)(),(0,h.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,h.filterChanged)(),(0,h.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,h.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,h.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,h.filterChanged)(),(0,h.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,h.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,h.filter)(({throughputEstimation:r,rtt:a})=>!!r&&!!a),(0,h.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,h.filterChanged)(),(0,h.filter)(r=>r===!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?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:h.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,h.merge)((0,h.fromEvent)(document,"visibilitychange"),(0,h.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,h.flattenObject)({quality:t,availableTracks:(0,h.flattenObject)(e),track:(0,h.flattenObject)(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var ut=require("@vkontakte/videoplayer-shared"),Ox=`@vkontakte/videoplayer-core@${Ls}`;
|