@vkontakte/videoplayer-core 2.0.113-dev.53b63d90.0 → 2.0.113-dev.85777574.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 +16 -16
- package/es2015.esm.js +16 -16
- package/es2018.cjs.js +17 -17
- package/es2018.esm.js +17 -17
- package/esnext.cjs.js +10 -10
- package/esnext.esm.js +9 -9
- package/evergreen.esm.js +10 -10
- package/package.json +2 -2
- package/types/providers/DashProvider/baseDashProvider.d.ts +6 -0
- package/types/providers/DashProvider/lib/LiveTextManager.d.ts +2 -0
- package/types/providers/DashProvider/lib/utils.d.ts +5 -1
package/esnext.cjs.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.113-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.113-dev.85777574.0
|
|
3
|
+
* Tue, 08 Oct 2024 08:37:30 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-113/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Dm=Object.create;var ga=Object.defineProperty;var Bm=Object.getOwnPropertyDescriptor;var Om=Object.getOwnPropertyNames;var Vm=Object.getPrototypeOf,_m=Object.prototype.hasOwnProperty;var m=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Nm=(r,e)=>{for(var t in e)ga(r,t,{get:e[t],enumerable:!0})},au=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Om(e))!_m.call(r,a)&&a!==t&&ga(r,a,{get:()=>e[a],enumerable:!(i=Bm(e,a))||i.enumerable});return r};var Ge=(r,e,t)=>(t=r!=null?Dm(Vm(r)):{},au(e||!r||!r.__esModule?ga(t,"default",{value:r,enumerable:!0}):t,r)),Fm=r=>au(ga({},"__esModule",{value:!0}),r);var ke=m((Zx,nu)=>{"use strict";nu.exports=function(r){try{return!!r()}catch{return!0}}});var Ui=m((eP,ou)=>{"use strict";var Um=ke();ou.exports=!Um(function(){var r=function(){}.bind();return typeof r!="function"||r.hasOwnProperty("prototype")})});var Se=m((tP,lu)=>{"use strict";var uu=Ui(),cu=Function.prototype,$s=cu.call,Hm=uu&&cu.bind.bind($s,$s);lu.exports=uu?Hm:function(r){return function(){return $s.apply(r,arguments)}}});var ui=m((iP,pu)=>{"use strict";var du=Se(),jm=du({}.toString),Gm=du("".slice);pu.exports=function(r){return Gm(jm(r),8,-1)}});var fu=m((rP,hu)=>{"use strict";var Wm=Se(),Ym=ke(),Qm=ui(),Ms=Object,zm=Wm("".split);hu.exports=Ym(function(){return!Ms("z").propertyIsEnumerable(0)})?function(r){return Qm(r)==="String"?zm(r,""):Ms(r)}:Ms});var ci=m((aP,mu)=>{"use strict";mu.exports=function(r){return r==null}});var Hi=m((sP,bu)=>{"use strict";var Km=ci(),Jm=TypeError;bu.exports=function(r){if(Km(r))throw new Jm("Can't call method on "+r);return r}});var li=m((nP,gu)=>{"use strict";var Xm=fu(),Zm=Hi();gu.exports=function(r){return Xm(Zm(r))}});var Cs=m((oP,Su)=>{"use strict";Su.exports=function(){}});var qt=m((uP,vu)=>{"use strict";vu.exports={}});var re=m((Ds,yu)=>{"use strict";var ji=function(r){return r&&r.Math===Math&&r};yu.exports=ji(typeof globalThis=="object"&&globalThis)||ji(typeof window=="object"&&window)||ji(typeof self=="object"&&self)||ji(typeof global=="object"&&global)||ji(typeof Ds=="object"&&Ds)||function(){return this}()||Function("return this")()});var ie=m((cP,Tu)=>{"use strict";var Bs=typeof document=="object"&&document.all;Tu.exports=typeof Bs>"u"&&Bs!==void 0?function(r){return typeof r=="function"||r===Bs}:function(r){return typeof r=="function"}});var xu=m((lP,Eu)=>{"use strict";var eb=re(),tb=ie(),Iu=eb.WeakMap;Eu.exports=tb(Iu)&&/native code/.test(String(Iu))});var Ce=m((dP,Pu)=>{"use strict";var ib=ie();Pu.exports=function(r){return typeof r=="object"?r!==null:ib(r)}});var De=m((pP,Au)=>{"use strict";var rb=ke();Au.exports=!rb(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ta=m((hP,wu)=>{"use strict";var ab=re(),ku=Ce(),Os=ab.document,sb=ku(Os)&&ku(Os.createElement);wu.exports=function(r){return sb?Os.createElement(r):{}}});var Vs=m((fP,Ru)=>{"use strict";var nb=De(),ob=ke(),ub=Ta();Ru.exports=!nb&&!ob(function(){return Object.defineProperty(ub("div"),"a",{get:function(){return 7}}).a!==7})});var _s=m((mP,Lu)=>{"use strict";var cb=De(),lb=ke();Lu.exports=cb&&lb(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var it=m((bP,$u)=>{"use strict";var db=Ce(),pb=String,hb=TypeError;$u.exports=function(r){if(db(r))return r;throw new hb(pb(r)+" is not an object")}});var we=m((gP,Mu)=>{"use strict";var fb=Ui(),Ia=Function.prototype.call;Mu.exports=fb?Ia.bind(Ia):function(){return Ia.apply(Ia,arguments)}});var Ea=m((SP,Cu)=>{"use strict";Cu.exports={}});var ht=m((vP,Bu)=>{"use strict";var Ns=Ea(),Fs=re(),mb=ie(),Du=function(r){return mb(r)?r:void 0};Bu.exports=function(r,e){return arguments.length<2?Du(Ns[r])||Du(Fs[r]):Ns[r]&&Ns[r][e]||Fs[r]&&Fs[r][e]}});var Gi=m((yP,Ou)=>{"use strict";var bb=Se();Ou.exports=bb({}.isPrototypeOf)});var di=m((TP,Nu)=>{"use strict";var gb=re(),Vu=gb.navigator,_u=Vu&&Vu.userAgent;Nu.exports=_u?String(_u):""});var Us=m((IP,Gu)=>{"use strict";var ju=re(),qs=di(),Fu=ju.process,qu=ju.Deno,Uu=Fu&&Fu.versions||qu&&qu.version,Hu=Uu&&Uu.v8,We,xa;Hu&&(We=Hu.split("."),xa=We[0]>0&&We[0]<4?1:+(We[0]+We[1]));!xa&&qs&&(We=qs.match(/Edge\/(\d+)/),(!We||We[1]>=74)&&(We=qs.match(/Chrome\/(\d+)/),We&&(xa=+We[1])));Gu.exports=xa});var Hs=m((EP,Yu)=>{"use strict";var Wu=Us(),Sb=ke(),vb=re(),yb=vb.String;Yu.exports=!!Object.getOwnPropertySymbols&&!Sb(function(){var r=Symbol("symbol detection");return!yb(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&Wu&&Wu<41})});var js=m((xP,Qu)=>{"use strict";var Tb=Hs();Qu.exports=Tb&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Gs=m((PP,zu)=>{"use strict";var Ib=ht(),Eb=ie(),xb=Gi(),Pb=js(),Ab=Object;zu.exports=Pb?function(r){return typeof r=="symbol"}:function(r){var e=Ib("Symbol");return Eb(e)&&xb(e.prototype,Ab(r))}});var Wi=m((AP,Ku)=>{"use strict";var kb=String;Ku.exports=function(r){try{return kb(r)}catch{return"Object"}}});var ft=m((kP,Ju)=>{"use strict";var wb=ie(),Rb=Wi(),Lb=TypeError;Ju.exports=function(r){if(wb(r))return r;throw new Lb(Rb(r)+" is not a function")}});var Yi=m((wP,Xu)=>{"use strict";var $b=ft(),Mb=ci();Xu.exports=function(r,e){var t=r[e];return Mb(t)?void 0:$b(t)}});var ec=m((RP,Zu)=>{"use strict";var Ws=we(),Ys=ie(),Qs=Ce(),Cb=TypeError;Zu.exports=function(r,e){var t,i;if(e==="string"&&Ys(t=r.toString)&&!Qs(i=Ws(t,r))||Ys(t=r.valueOf)&&!Qs(i=Ws(t,r))||e!=="string"&&Ys(t=r.toString)&&!Qs(i=Ws(t,r)))return i;throw new Cb("Can't convert object to primitive value")}});var Ye=m((LP,tc)=>{"use strict";tc.exports=!0});var ac=m(($P,rc)=>{"use strict";var ic=re(),Db=Object.defineProperty;rc.exports=function(r,e){try{Db(ic,r,{value:e,configurable:!0,writable:!0})}catch{ic[r]=e}return e}});var Qi=m((MP,oc)=>{"use strict";var Bb=Ye(),Ob=re(),Vb=ac(),sc="__core-js_shared__",nc=oc.exports=Ob[sc]||Vb(sc,{});(nc.versions||(nc.versions=[])).push({version:"3.38.0",mode:Bb?"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 zs=m((CP,cc)=>{"use strict";var uc=Qi();cc.exports=function(r,e){return uc[r]||(uc[r]=e||{})}});var zi=m((DP,lc)=>{"use strict";var _b=Hi(),Nb=Object;lc.exports=function(r){return Nb(_b(r))}});var Qe=m((BP,dc)=>{"use strict";var Fb=Se(),qb=zi(),Ub=Fb({}.hasOwnProperty);dc.exports=Object.hasOwn||function(e,t){return Ub(qb(e),t)}});var Ks=m((OP,pc)=>{"use strict";var Hb=Se(),jb=0,Gb=Math.random(),Wb=Hb(1 .toString);pc.exports=function(r){return"Symbol("+(r===void 0?"":r)+")_"+Wb(++jb+Gb,36)}});var fe=m((VP,fc)=>{"use strict";var Yb=re(),Qb=zs(),hc=Qe(),zb=Ks(),Kb=Hs(),Jb=js(),pi=Yb.Symbol,Js=Qb("wks"),Xb=Jb?pi.for||pi:pi&&pi.withoutSetter||zb;fc.exports=function(r){return hc(Js,r)||(Js[r]=Kb&&hc(pi,r)?pi[r]:Xb("Symbol."+r)),Js[r]}});var Sc=m((_P,gc)=>{"use strict";var Zb=we(),mc=Ce(),bc=Gs(),eg=Yi(),tg=ec(),ig=fe(),rg=TypeError,ag=ig("toPrimitive");gc.exports=function(r,e){if(!mc(r)||bc(r))return r;var t=eg(r,ag),i;if(t){if(e===void 0&&(e="default"),i=Zb(t,r,e),!mc(i)||bc(i))return i;throw new rg("Can't convert object to primitive value")}return e===void 0&&(e="number"),tg(r,e)}});var Xs=m((NP,vc)=>{"use strict";var sg=Sc(),ng=Gs();vc.exports=function(r){var e=sg(r,"string");return ng(e)?e:e+""}});var Ut=m(Tc=>{"use strict";var og=De(),ug=Vs(),cg=_s(),Pa=it(),yc=Xs(),lg=TypeError,Zs=Object.defineProperty,dg=Object.getOwnPropertyDescriptor,en="enumerable",tn="configurable",rn="writable";Tc.f=og?cg?function(e,t,i){if(Pa(e),t=yc(t),Pa(i),typeof e=="function"&&t==="prototype"&&"value"in i&&rn in i&&!i[rn]){var a=dg(e,t);a&&a[rn]&&(e[t]=i.value,i={configurable:tn in i?i[tn]:a[tn],enumerable:en in i?i[en]:a[en],writable:!1})}return Zs(e,t,i)}:Zs:function(e,t,i){if(Pa(e),t=yc(t),Pa(i),ug)try{return Zs(e,t,i)}catch{}if("get"in i||"set"in i)throw new lg("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ki=m((qP,Ic)=>{"use strict";Ic.exports=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}}});var hi=m((UP,Ec)=>{"use strict";var pg=De(),hg=Ut(),fg=Ki();Ec.exports=pg?function(r,e,t){return hg.f(r,e,fg(1,t))}:function(r,e,t){return r[e]=t,r}});var Aa=m((HP,Pc)=>{"use strict";var mg=zs(),bg=Ks(),xc=mg("keys");Pc.exports=function(r){return xc[r]||(xc[r]=bg(r))}});var ka=m((jP,Ac)=>{"use strict";Ac.exports={}});var on=m((GP,Rc)=>{"use strict";var gg=xu(),wc=re(),Sg=Ce(),vg=hi(),an=Qe(),sn=Qi(),yg=Aa(),Tg=ka(),kc="Object already initialized",nn=wc.TypeError,Ig=wc.WeakMap,wa,Ji,Ra,Eg=function(r){return Ra(r)?Ji(r):wa(r,{})},xg=function(r){return function(e){var t;if(!Sg(e)||(t=Ji(e)).type!==r)throw new nn("Incompatible receiver, "+r+" required");return t}};gg||sn.state?(ze=sn.state||(sn.state=new Ig),ze.get=ze.get,ze.has=ze.has,ze.set=ze.set,wa=function(r,e){if(ze.has(r))throw new nn(kc);return e.facade=r,ze.set(r,e),e},Ji=function(r){return ze.get(r)||{}},Ra=function(r){return ze.has(r)}):(Ht=yg("state"),Tg[Ht]=!0,wa=function(r,e){if(an(r,Ht))throw new nn(kc);return e.facade=r,vg(r,Ht,e),e},Ji=function(r){return an(r,Ht)?r[Ht]:{}},Ra=function(r){return an(r,Ht)});var ze,Ht;Rc.exports={set:wa,get:Ji,has:Ra,enforce:Eg,getterFor:xg}});var un=m((WP,Cc)=>{"use strict";var Pg=Ui(),Mc=Function.prototype,Lc=Mc.apply,$c=Mc.call;Cc.exports=typeof Reflect=="object"&&Reflect.apply||(Pg?$c.bind(Lc):function(){return $c.apply(Lc,arguments)})});var cn=m((YP,Dc)=>{"use strict";var Ag=ui(),kg=Se();Dc.exports=function(r){if(Ag(r)==="Function")return kg(r)}});var _c=m(Vc=>{"use strict";var Bc={}.propertyIsEnumerable,Oc=Object.getOwnPropertyDescriptor,wg=Oc&&!Bc.call({1:2},1);Vc.f=wg?function(e){var t=Oc(this,e);return!!t&&t.enumerable}:Bc});var qc=m(Fc=>{"use strict";var Rg=De(),Lg=we(),$g=_c(),Mg=Ki(),Cg=li(),Dg=Xs(),Bg=Qe(),Og=Vs(),Nc=Object.getOwnPropertyDescriptor;Fc.f=Rg?Nc:function(e,t){if(e=Cg(e),t=Dg(t),Og)try{return Nc(e,t)}catch{}if(Bg(e,t))return Mg(!Lg($g.f,e,t),e[t])}});var ln=m((KP,Uc)=>{"use strict";var Vg=ke(),_g=ie(),Ng=/#|\.prototype\./,Xi=function(r,e){var t=qg[Fg(r)];return t===Hg?!0:t===Ug?!1:_g(e)?Vg(e):!!e},Fg=Xi.normalize=function(r){return String(r).replace(Ng,".").toLowerCase()},qg=Xi.data={},Ug=Xi.NATIVE="N",Hg=Xi.POLYFILL="P";Uc.exports=Xi});var Zi=m((JP,jc)=>{"use strict";var Hc=cn(),jg=ft(),Gg=Ui(),Wg=Hc(Hc.bind);jc.exports=function(r,e){return jg(r),e===void 0?r:Gg?Wg(r,e):function(){return r.apply(e,arguments)}}});var Be=m((XP,Wc)=>{"use strict";var er=re(),Yg=un(),Qg=cn(),zg=ie(),Kg=qc().f,Jg=ln(),fi=Ea(),Xg=Zi(),mi=hi(),Gc=Qe();Qi();var Zg=function(r){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new r;case 1:return new r(t);case 2:return new r(t,i)}return new r(t,i,a)}return Yg(r,this,arguments)};return e.prototype=r.prototype,e};Wc.exports=function(r,e){var t=r.target,i=r.global,a=r.stat,s=r.proto,n=i?er:a?er[t]:er[t]&&er[t].prototype,o=i?fi:fi[t]||mi(fi,t,{})[t],c=o.prototype,u,d,l,h,f,b,g,y,E;for(h in e)u=Jg(i?h:t+(a?".":"#")+h,r.forced),d=!u&&n&&Gc(n,h),b=o[h],d&&(r.dontCallGetSet?(E=Kg(n,h),g=E&&E.value):g=n[h]),f=d&&g?g:e[h],!(!u&&!s&&typeof b==typeof f)&&(r.bind&&d?y=Xg(f,er):r.wrap&&d?y=Zg(f):s&&zg(f)?y=Qg(f):y=f,(r.sham||f&&f.sham||b&&b.sham)&&mi(y,"sham",!0),mi(o,h,y),s&&(l=t+"Prototype",Gc(fi,l)||mi(fi,l,{}),mi(fi[l],h,f),r.real&&c&&(u||!c[h])&&mi(c,h,f)))}});var zc=m((ZP,Qc)=>{"use strict";var dn=De(),eS=Qe(),Yc=Function.prototype,tS=dn&&Object.getOwnPropertyDescriptor,pn=eS(Yc,"name"),iS=pn&&function(){}.name==="something",rS=pn&&(!dn||dn&&tS(Yc,"name").configurable);Qc.exports={EXISTS:pn,PROPER:iS,CONFIGURABLE:rS}});var Jc=m((eA,Kc)=>{"use strict";var aS=Math.ceil,sS=Math.floor;Kc.exports=Math.trunc||function(e){var t=+e;return(t>0?sS:aS)(t)}});var La=m((tA,Xc)=>{"use strict";var nS=Jc();Xc.exports=function(r){var e=+r;return e!==e||e===0?0:nS(e)}});var el=m((iA,Zc)=>{"use strict";var oS=La(),uS=Math.max,cS=Math.min;Zc.exports=function(r,e){var t=oS(r);return t<0?uS(t+e,0):cS(t,e)}});var il=m((rA,tl)=>{"use strict";var lS=La(),dS=Math.min;tl.exports=function(r){var e=lS(r);return e>0?dS(e,9007199254740991):0}});var $a=m((aA,rl)=>{"use strict";var pS=il();rl.exports=function(r){return pS(r.length)}});var nl=m((sA,sl)=>{"use strict";var hS=li(),fS=el(),mS=$a(),al=function(r){return function(e,t,i){var a=hS(e),s=mS(a);if(s===0)return!r&&-1;var n=fS(i,s),o;if(r&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((r||n in a)&&a[n]===t)return r||n||0;return!r&&-1}};sl.exports={includes:al(!0),indexOf:al(!1)}});var cl=m((nA,ul)=>{"use strict";var bS=Se(),hn=Qe(),gS=li(),SS=nl().indexOf,vS=ka(),ol=bS([].push);ul.exports=function(r,e){var t=gS(r),i=0,a=[],s;for(s in t)!hn(vS,s)&&hn(t,s)&&ol(a,s);for(;e.length>i;)hn(t,s=e[i++])&&(~SS(a,s)||ol(a,s));return a}});var fn=m((oA,ll)=>{"use strict";ll.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var pl=m((uA,dl)=>{"use strict";var yS=cl(),TS=fn();dl.exports=Object.keys||function(e){return yS(e,TS)}});var fl=m(hl=>{"use strict";var IS=De(),ES=_s(),xS=Ut(),PS=it(),AS=li(),kS=pl();hl.f=IS&&!ES?Object.defineProperties:function(e,t){PS(e);for(var i=AS(t),a=kS(t),s=a.length,n=0,o;s>n;)xS.f(e,o=a[n++],i[o]);return e}});var mn=m((lA,ml)=>{"use strict";var wS=ht();ml.exports=wS("document","documentElement")});var vn=m((dA,Il)=>{"use strict";var RS=it(),LS=fl(),bl=fn(),$S=ka(),MS=mn(),CS=Ta(),DS=Aa(),gl=">",Sl="<",gn="prototype",Sn="script",yl=DS("IE_PROTO"),bn=function(){},Tl=function(r){return Sl+Sn+gl+r+Sl+"/"+Sn+gl},vl=function(r){r.write(Tl("")),r.close();var e=r.parentWindow.Object;return r=null,e},BS=function(){var r=CS("iframe"),e="java"+Sn+":",t;return r.style.display="none",MS.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(Tl("document.F=Object")),t.close(),t.F},Ma,Ca=function(){try{Ma=new ActiveXObject("htmlfile")}catch{}Ca=typeof document<"u"?document.domain&&Ma?vl(Ma):BS():vl(Ma);for(var r=bl.length;r--;)delete Ca[gn][bl[r]];return Ca()};$S[yl]=!0;Il.exports=Object.create||function(e,t){var i;return e!==null?(bn[gn]=RS(e),i=new bn,bn[gn]=null,i[yl]=e):i=Ca(),t===void 0?i:LS.f(i,t)}});var xl=m((pA,El)=>{"use strict";var OS=ke();El.exports=!OS(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype})});var Tn=m((hA,Al)=>{"use strict";var VS=Qe(),_S=ie(),NS=zi(),FS=Aa(),qS=xl(),Pl=FS("IE_PROTO"),yn=Object,US=yn.prototype;Al.exports=qS?yn.getPrototypeOf:function(r){var e=NS(r);if(VS(e,Pl))return e[Pl];var t=e.constructor;return _S(t)&&e instanceof t?t.prototype:e instanceof yn?US:null}});var bi=m((fA,kl)=>{"use strict";var HS=hi();kl.exports=function(r,e,t,i){return i&&i.enumerable?r[e]=t:HS(r,e,t),r}});var Pn=m((mA,Ll)=>{"use strict";var jS=ke(),GS=ie(),WS=Ce(),YS=vn(),wl=Tn(),QS=bi(),zS=fe(),KS=Ye(),xn=zS("iterator"),Rl=!1,mt,In,En;[].keys&&(En=[].keys(),"next"in En?(In=wl(wl(En)),In!==Object.prototype&&(mt=In)):Rl=!0);var JS=!WS(mt)||jS(function(){var r={};return mt[xn].call(r)!==r});JS?mt={}:KS&&(mt=YS(mt));GS(mt[xn])||QS(mt,xn,function(){return this});Ll.exports={IteratorPrototype:mt,BUGGY_SAFARI_ITERATORS:Rl}});var Da=m((bA,Ml)=>{"use strict";var XS=fe(),ZS=XS("toStringTag"),$l={};$l[ZS]="z";Ml.exports=String($l)==="[object z]"});var tr=m((gA,Cl)=>{"use strict";var ev=Da(),tv=ie(),Ba=ui(),iv=fe(),rv=iv("toStringTag"),av=Object,sv=Ba(function(){return arguments}())==="Arguments",nv=function(r,e){try{return r[e]}catch{}};Cl.exports=ev?Ba:function(r){var e,t,i;return r===void 0?"Undefined":r===null?"Null":typeof(t=nv(e=av(r),rv))=="string"?t:sv?Ba(e):(i=Ba(e))==="Object"&&tv(e.callee)?"Arguments":i}});var Bl=m((SA,Dl)=>{"use strict";var ov=Da(),uv=tr();Dl.exports=ov?{}.toString:function(){return"[object "+uv(this)+"]"}});var ir=m((vA,Vl)=>{"use strict";var cv=Da(),lv=Ut().f,dv=hi(),pv=Qe(),hv=Bl(),fv=fe(),Ol=fv("toStringTag");Vl.exports=function(r,e,t,i){var a=t?r:r&&r.prototype;a&&(pv(a,Ol)||lv(a,Ol,{configurable:!0,value:e}),i&&!cv&&dv(a,"toString",hv))}});var Nl=m((yA,_l)=>{"use strict";var mv=Pn().IteratorPrototype,bv=vn(),gv=Ki(),Sv=ir(),vv=qt(),yv=function(){return this};_l.exports=function(r,e,t,i){var a=e+" Iterator";return r.prototype=bv(mv,{next:gv(+!i,t)}),Sv(r,a,!1,!0),vv[a]=yv,r}});var ql=m((TA,Fl)=>{"use strict";var Tv=Se(),Iv=ft();Fl.exports=function(r,e,t){try{return Tv(Iv(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}}});var Hl=m((IA,Ul)=>{"use strict";var Ev=Ce();Ul.exports=function(r){return Ev(r)||r===null}});var Gl=m((EA,jl)=>{"use strict";var xv=Hl(),Pv=String,Av=TypeError;jl.exports=function(r){if(xv(r))return r;throw new Av("Can't set "+Pv(r)+" as a prototype")}});var An=m((xA,Wl)=>{"use strict";var kv=ql(),wv=Ce(),Rv=Hi(),Lv=Gl();Wl.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=kv(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(a,s){return Rv(a),Lv(s),wv(a)&&(r?t(a,s):a.__proto__=s),a}}():void 0)});var rd=m((PA,id)=>{"use strict";var $v=Be(),Mv=we(),Oa=Ye(),ed=zc(),Cv=ie(),Dv=Nl(),Yl=Tn(),Ql=An(),Bv=ir(),Ov=hi(),kn=bi(),Vv=fe(),zl=qt(),td=Pn(),_v=ed.PROPER,Nv=ed.CONFIGURABLE,Kl=td.IteratorPrototype,Va=td.BUGGY_SAFARI_ITERATORS,rr=Vv("iterator"),Jl="keys",ar="values",Xl="entries",Zl=function(){return this};id.exports=function(r,e,t,i,a,s,n){Dv(t,e,i);var o=function(E){if(E===a&&h)return h;if(!Va&&E&&E in d)return d[E];switch(E){case Jl:return function(){return new t(this,E)};case ar:return function(){return new t(this,E)};case Xl:return function(){return new t(this,E)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=r.prototype,l=d[rr]||d["@@iterator"]||a&&d[a],h=!Va&&l||o(a),f=e==="Array"&&d.entries||l,b,g,y;if(f&&(b=Yl(f.call(new r)),b!==Object.prototype&&b.next&&(!Oa&&Yl(b)!==Kl&&(Ql?Ql(b,Kl):Cv(b[rr])||kn(b,rr,Zl)),Bv(b,c,!0,!0),Oa&&(zl[c]=Zl))),_v&&a===ar&&l&&l.name!==ar&&(!Oa&&Nv?Ov(d,"name",ar):(u=!0,h=function(){return Mv(l,this)})),a)if(g={values:o(ar),keys:s?h:o(Jl),entries:o(Xl)},n)for(y in g)(Va||u||!(y in d))&&kn(d,y,g[y]);else $v({target:e,proto:!0,forced:Va||u},g);return(!Oa||n)&&d[rr]!==h&&kn(d,rr,h,{name:a}),zl[e]=h,g}});var sd=m((AA,ad)=>{"use strict";ad.exports=function(r,e){return{value:r,done:e}}});var Rn=m((kA,ld)=>{"use strict";var Fv=li(),wn=Cs(),nd=qt(),ud=on(),qv=Ut().f,Uv=rd(),_a=sd(),Hv=Ye(),jv=De(),cd="Array Iterator",Gv=ud.set,Wv=ud.getterFor(cd);ld.exports=Uv(Array,"Array",function(r,e){Gv(this,{type:cd,target:Fv(r),index:0,kind:e})},function(){var r=Wv(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=void 0,_a(void 0,!0);switch(r.kind){case"keys":return _a(t,!1);case"values":return _a(e[t],!1)}return _a([t,e[t]],!1)},"values");var od=nd.Arguments=nd.Array;wn("keys");wn("values");wn("entries");if(!Hv&&jv&&od.name!=="values")try{qv(od,"name",{value:"values"})}catch{}});var pd=m((wA,dd)=>{"use strict";var Yv=fe(),Qv=qt(),zv=Yv("iterator"),Kv=Array.prototype;dd.exports=function(r){return r!==void 0&&(Qv.Array===r||Kv[zv]===r)}});var Ln=m((RA,fd)=>{"use strict";var Jv=tr(),hd=Yi(),Xv=ci(),Zv=qt(),ey=fe(),ty=ey("iterator");fd.exports=function(r){if(!Xv(r))return hd(r,ty)||hd(r,"@@iterator")||Zv[Jv(r)]}});var bd=m((LA,md)=>{"use strict";var iy=we(),ry=ft(),ay=it(),sy=Wi(),ny=Ln(),oy=TypeError;md.exports=function(r,e){var t=arguments.length<2?ny(r):e;if(ry(t))return ay(iy(t,r));throw new oy(sy(r)+" is not iterable")}});var vd=m(($A,Sd)=>{"use strict";var uy=we(),gd=it(),cy=Yi();Sd.exports=function(r,e,t){var i,a;gd(r);try{if(i=cy(r,"return"),!i){if(e==="throw")throw t;return t}i=uy(i,r)}catch(s){a=!0,i=s}if(e==="throw")throw t;if(a)throw i;return gd(i),t}});var Fa=m((MA,Ed)=>{"use strict";var ly=Zi(),dy=we(),py=it(),hy=Wi(),fy=pd(),my=$a(),yd=Gi(),by=bd(),gy=Ln(),Td=vd(),Sy=TypeError,Na=function(r,e){this.stopped=r,this.result=e},Id=Na.prototype;Ed.exports=function(r,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),c=ly(e,i),u,d,l,h,f,b,g,y=function(C){return u&&Td(u,"normal",C),new Na(!0,C)},E=function(C){return a?(py(C),o?c(C[0],C[1],y):c(C[0],C[1])):o?c(C,y):c(C)};if(s)u=r.iterator;else if(n)u=r;else{if(d=gy(r),!d)throw new Sy(hy(r)+" is not iterable");if(fy(d)){for(l=0,h=my(r);h>l;l++)if(f=E(r[l]),f&&yd(Id,f))return f;return new Na(!1)}u=by(r,d)}for(b=s?r.next:u.next;!(g=dy(b,u)).done;){try{f=E(g.value)}catch(C){Td(u,"throw",C)}if(typeof f=="object"&&f&&yd(Id,f))return f}return new Na(!1)}});var Pd=m((CA,xd)=>{"use strict";var vy=De(),yy=Ut(),Ty=Ki();xd.exports=function(r,e,t){vy?yy.f(r,e,Ty(0,t)):r[e]=t}});var Ad=m(()=>{"use strict";var Iy=Be(),Ey=Fa(),xy=Pd();Iy({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Ey(e,function(i,a){xy(t,i,a)},{AS_ENTRIES:!0}),t}})});var wd=m((OA,kd)=>{"use strict";Rn();Ad();var Py=Ea();kd.exports=Py.Object.fromEntries});var Ld=m((VA,Rd)=>{"use strict";Rd.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 Md=m(()=>{"use strict";Rn();var Ay=Ld(),ky=re(),wy=ir(),$d=qt();for(qa in Ay)wy(ky[qa],qa),$d[qa]=$d.Array;var qa});var Dd=m((FA,Cd)=>{"use strict";var Ry=wd();Md();Cd.exports=Ry});var $n=m((qA,Bd)=>{"use strict";var Ly=Dd();Bd.exports=Ly});var Od=m(()=>{"use strict"});var Mn=m((jA,Vd)=>{"use strict";var sr=re(),$y=di(),My=ui(),Ua=function(r){return $y.slice(0,r.length)===r};Vd.exports=function(){return Ua("Bun/")?"BUN":Ua("Cloudflare-Workers")?"CLOUDFLARE":Ua("Deno/")?"DENO":Ua("Node.js/")?"NODE":sr.Bun&&typeof Bun.version=="string"?"BUN":sr.Deno&&typeof Deno.version=="object"?"DENO":My(sr.process)==="process"?"NODE":sr.window&&sr.document?"BROWSER":"REST"}()});var Ha=m((GA,_d)=>{"use strict";var Cy=Mn();_d.exports=Cy==="NODE"});var Fd=m((WA,Nd)=>{"use strict";var Dy=Ut();Nd.exports=function(r,e,t){return Dy.f(r,e,t)}});var Hd=m((YA,Ud)=>{"use strict";var By=ht(),Oy=Fd(),Vy=fe(),_y=De(),qd=Vy("species");Ud.exports=function(r){var e=By(r);_y&&e&&!e[qd]&&Oy(e,qd,{configurable:!0,get:function(){return this}})}});var Gd=m((QA,jd)=>{"use strict";var Ny=Gi(),Fy=TypeError;jd.exports=function(r,e){if(Ny(e,r))return r;throw new Fy("Incorrect invocation")}});var Dn=m((zA,Wd)=>{"use strict";var qy=Se(),Uy=ie(),Cn=Qi(),Hy=qy(Function.toString);Uy(Cn.inspectSource)||(Cn.inspectSource=function(r){return Hy(r)});Wd.exports=Cn.inspectSource});var Xd=m((KA,Jd)=>{"use strict";var jy=Se(),Gy=ke(),Yd=ie(),Wy=tr(),Yy=ht(),Qy=Dn(),Qd=function(){},zd=Yy("Reflect","construct"),Bn=/^\s*(?:class|function)\b/,zy=jy(Bn.exec),Ky=!Bn.test(Qd),nr=function(e){if(!Yd(e))return!1;try{return zd(Qd,[],e),!0}catch{return!1}},Kd=function(e){if(!Yd(e))return!1;switch(Wy(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ky||!!zy(Bn,Qy(e))}catch{return!0}};Kd.sham=!0;Jd.exports=!zd||Gy(function(){var r;return nr(nr.call)||!nr(Object)||!nr(function(){r=!0})||r})?Kd:nr});var ep=m((JA,Zd)=>{"use strict";var Jy=Xd(),Xy=Wi(),Zy=TypeError;Zd.exports=function(r){if(Jy(r))return r;throw new Zy(Xy(r)+" is not a constructor")}});var On=m((XA,ip)=>{"use strict";var tp=it(),eT=ep(),tT=ci(),iT=fe(),rT=iT("species");ip.exports=function(r,e){var t=tp(r).constructor,i;return t===void 0||tT(i=tp(t)[rT])?e:eT(i)}});var ap=m((ZA,rp)=>{"use strict";var aT=Se();rp.exports=aT([].slice)});var np=m((ek,sp)=>{"use strict";var sT=TypeError;sp.exports=function(r,e){if(r<e)throw new sT("Not enough arguments");return r}});var Vn=m((tk,op)=>{"use strict";var nT=di();op.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(nT)});var Wn=m((ik,bp)=>{"use strict";var Re=re(),oT=un(),uT=Zi(),up=ie(),cT=Qe(),mp=ke(),cp=mn(),lT=ap(),lp=Ta(),dT=np(),pT=Vn(),hT=Ha(),Hn=Re.setImmediate,jn=Re.clearImmediate,fT=Re.process,_n=Re.Dispatch,mT=Re.Function,dp=Re.MessageChannel,bT=Re.String,Nn=0,or={},pp="onreadystatechange",ur,jt,Fn,qn;mp(function(){ur=Re.location});var Gn=function(r){if(cT(or,r)){var e=or[r];delete or[r],e()}},Un=function(r){return function(){Gn(r)}},hp=function(r){Gn(r.data)},fp=function(r){Re.postMessage(bT(r),ur.protocol+"//"+ur.host)};(!Hn||!jn)&&(Hn=function(e){dT(arguments.length,1);var t=up(e)?e:mT(e),i=lT(arguments,1);return or[++Nn]=function(){oT(t,void 0,i)},jt(Nn),Nn},jn=function(e){delete or[e]},hT?jt=function(r){fT.nextTick(Un(r))}:_n&&_n.now?jt=function(r){_n.now(Un(r))}:dp&&!pT?(Fn=new dp,qn=Fn.port2,Fn.port1.onmessage=hp,jt=uT(qn.postMessage,qn)):Re.addEventListener&&up(Re.postMessage)&&!Re.importScripts&&ur&&ur.protocol!=="file:"&&!mp(fp)?(jt=fp,Re.addEventListener("message",hp,!1)):pp in lp("script")?jt=function(r){cp.appendChild(lp("script"))[pp]=function(){cp.removeChild(this),Gn(r)}}:jt=function(r){setTimeout(Un(r),0)});bp.exports={set:Hn,clear:jn}});var vp=m((rk,Sp)=>{"use strict";var gp=re(),gT=De(),ST=Object.getOwnPropertyDescriptor;Sp.exports=function(r){if(!gT)return gp[r];var e=ST(gp,r);return e&&e.value}});var Yn=m((ak,Tp)=>{"use strict";var yp=function(){this.head=null,this.tail=null};yp.prototype={add:function(r){var e={item:r,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var r=this.head;if(r){var e=this.head=r.next;return e===null&&(this.tail=null),r.item}}};Tp.exports=yp});var Ep=m((sk,Ip)=>{"use strict";var vT=di();Ip.exports=/ipad|iphone|ipod/i.test(vT)&&typeof Pebble<"u"});var Pp=m((nk,xp)=>{"use strict";var yT=di();xp.exports=/web0s(?!.*chrome)/i.test(yT)});var Mp=m((ok,$p)=>{"use strict";var Si=re(),TT=vp(),Ap=Zi(),Qn=Wn().set,IT=Yn(),ET=Vn(),xT=Ep(),PT=Pp(),zn=Ha(),kp=Si.MutationObserver||Si.WebKitMutationObserver,wp=Si.document,Rp=Si.process,ja=Si.Promise,Xn=TT("queueMicrotask"),gi,Kn,Jn,Ga,Lp;Xn||(cr=new IT,lr=function(){var r,e;for(zn&&(r=Rp.domain)&&r.exit();e=cr.get();)try{e()}catch(t){throw cr.head&&gi(),t}r&&r.enter()},!ET&&!zn&&!PT&&kp&&wp?(Kn=!0,Jn=wp.createTextNode(""),new kp(lr).observe(Jn,{characterData:!0}),gi=function(){Jn.data=Kn=!Kn}):!xT&&ja&&ja.resolve?(Ga=ja.resolve(void 0),Ga.constructor=ja,Lp=Ap(Ga.then,Ga),gi=function(){Lp(lr)}):zn?gi=function(){Rp.nextTick(lr)}:(Qn=Ap(Qn,Si),gi=function(){Qn(lr)}),Xn=function(r){cr.head||gi(),cr.add(r)});var cr,lr;$p.exports=Xn});var Dp=m((uk,Cp)=>{"use strict";Cp.exports=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}}});var Wa=m((ck,Bp)=>{"use strict";Bp.exports=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}}});var Gt=m((lk,Op)=>{"use strict";var AT=re();Op.exports=AT.Promise});var vi=m((dk,Fp)=>{"use strict";var kT=re(),dr=Gt(),wT=ie(),RT=ln(),LT=Dn(),$T=fe(),Vp=Mn(),MT=Ye(),Zn=Us(),_p=dr&&dr.prototype,CT=$T("species"),eo=!1,Np=wT(kT.PromiseRejectionEvent),DT=RT("Promise",function(){var r=LT(dr),e=r!==String(dr);if(!e&&Zn===66||MT&&!(_p.catch&&_p.finally))return!0;if(!Zn||Zn<51||!/native code/.test(r)){var t=new dr(function(s){s(1)}),i=function(s){s(function(){},function(){})},a=t.constructor={};if(a[CT]=i,eo=t.then(function(){})instanceof i,!eo)return!0}return!e&&(Vp==="BROWSER"||Vp==="DENO")&&!Np});Fp.exports={CONSTRUCTOR:DT,REJECTION_EVENT:Np,SUBCLASSING:eo}});var yi=m((pk,Up)=>{"use strict";var qp=ft(),BT=TypeError,OT=function(r){var e,t;this.promise=new r(function(i,a){if(e!==void 0||t!==void 0)throw new BT("Bad Promise constructor");e=i,t=a}),this.resolve=qp(e),this.reject=qp(t)};Up.exports.f=function(r){return new OT(r)}});var oh=m(()=>{"use strict";var VT=Be(),_T=Ye(),Ka=Ha(),Lt=re(),xi=we(),Hp=bi(),jp=An(),NT=ir(),FT=Hd(),qT=ft(),za=ie(),UT=Ce(),HT=Gd(),jT=On(),zp=Wn().set,so=Mp(),GT=Dp(),WT=Wa(),YT=Yn(),Kp=on(),Ja=Gt(),no=vi(),Jp=yi(),Xa="Promise",Xp=no.CONSTRUCTOR,QT=no.REJECTION_EVENT,zT=no.SUBCLASSING,to=Kp.getterFor(Xa),KT=Kp.set,Ti=Ja&&Ja.prototype,Wt=Ja,Ya=Ti,Zp=Lt.TypeError,io=Lt.document,oo=Lt.process,ro=Jp.f,JT=ro,XT=!!(io&&io.createEvent&&Lt.dispatchEvent),eh="unhandledrejection",ZT="rejectionhandled",Gp=0,th=1,eI=2,uo=1,ih=2,Qa,Wp,tI,Yp,rh=function(r){var e;return UT(r)&&za(e=r.then)?e:!1},ah=function(r,e){var t=e.value,i=e.state===th,a=i?r.ok:r.fail,s=r.resolve,n=r.reject,o=r.domain,c,u,d;try{a?(i||(e.rejection===ih&&rI(e),e.rejection=uo),a===!0?c=t:(o&&o.enter(),c=a(t),o&&(o.exit(),d=!0)),c===r.promise?n(new Zp("Promise-chain cycle")):(u=rh(c))?xi(u,c,s,n):s(c)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},sh=function(r,e){r.notified||(r.notified=!0,so(function(){for(var t=r.reactions,i;i=t.get();)ah(i,r);r.notified=!1,e&&!r.rejection&&iI(r)}))},nh=function(r,e,t){var i,a;XT?(i=io.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(r,!1,!0),Lt.dispatchEvent(i)):i={promise:e,reason:t},!QT&&(a=Lt["on"+r])?a(i):r===eh&>("Unhandled promise rejection",t)},iI=function(r){xi(zp,Lt,function(){var e=r.facade,t=r.value,i=Qp(r),a;if(i&&(a=WT(function(){Ka?oo.emit("unhandledRejection",t,e):nh(eh,e,t)}),r.rejection=Ka||Qp(r)?ih:uo,a.error))throw a.value})},Qp=function(r){return r.rejection!==uo&&!r.parent},rI=function(r){xi(zp,Lt,function(){var e=r.facade;Ka?oo.emit("rejectionHandled",e):nh(ZT,e,r.value)})},Ii=function(r,e,t){return function(i){r(e,i,t)}},Ei=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=eI,sh(r,!0))},ao=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new Zp("Promise can't be resolved itself");var i=rh(e);i?so(function(){var a={done:!1};try{xi(i,e,Ii(ao,a,r),Ii(Ei,a,r))}catch(s){Ei(a,s,r)}}):(r.value=e,r.state=th,sh(r,!1))}catch(a){Ei({done:!1},a,r)}}};if(Xp&&(Wt=function(e){HT(this,Ya),qT(e),xi(Qa,this);var t=to(this);try{e(Ii(ao,t),Ii(Ei,t))}catch(i){Ei(t,i)}},Ya=Wt.prototype,Qa=function(e){KT(this,{type:Xa,done:!1,notified:!1,parent:!1,reactions:new YT,rejection:!1,state:Gp,value:void 0})},Qa.prototype=Hp(Ya,"then",function(e,t){var i=to(this),a=ro(jT(this,Wt));return i.parent=!0,a.ok=za(e)?e:!0,a.fail=za(t)&&t,a.domain=Ka?oo.domain:void 0,i.state===Gp?i.reactions.add(a):so(function(){ah(a,i)}),a.promise}),Wp=function(){var r=new Qa,e=to(r);this.promise=r,this.resolve=Ii(ao,e),this.reject=Ii(Ei,e)},Jp.f=ro=function(r){return r===Wt||r===tI?new Wp(r):JT(r)},!_T&&za(Ja)&&Ti!==Object.prototype)){Yp=Ti.then,zT||Hp(Ti,"then",function(e,t){var i=this;return new Wt(function(a,s){xi(Yp,i,a,s)}).then(e,t)},{unsafe:!0});try{delete Ti.constructor}catch{}jp&&jp(Ti,Ya)}VT({global:!0,constructor:!0,wrap:!0,forced:Xp},{Promise:Wt});NT(Wt,Xa,!1,!0);FT(Xa)});var ph=m((mk,dh)=>{"use strict";var aI=fe(),ch=aI("iterator"),lh=!1;try{uh=0,co={next:function(){return{done:!!uh++}},return:function(){lh=!0}},co[ch]=function(){return this},Array.from(co,function(){throw 2})}catch{}var uh,co;dh.exports=function(r,e){try{if(!e&&!lh)return!1}catch{return!1}var t=!1;try{var i={};i[ch]=function(){return{next:function(){return{done:t=!0}}}},r(i)}catch{}return t}});var lo=m((bk,hh)=>{"use strict";var sI=Gt(),nI=ph(),oI=vi().CONSTRUCTOR;hh.exports=oI||!nI(function(r){sI.all(r).then(void 0,function(){})})});var fh=m(()=>{"use strict";var uI=Be(),cI=we(),lI=ft(),dI=yi(),pI=Wa(),hI=Fa(),fI=lo();uI({target:"Promise",stat:!0,forced:fI},{all:function(e){var t=this,i=dI.f(t),a=i.resolve,s=i.reject,n=pI(function(){var o=lI(t.resolve),c=[],u=0,d=1;hI(e,function(l){var h=u++,f=!1;d++,cI(o,t,l).then(function(b){f||(f=!0,c[h]=b,--d||a(c))},s)}),--d||a(c)});return n.error&&s(n.value),i.promise}})});var bh=m(()=>{"use strict";var mI=Be(),bI=Ye(),gI=vi().CONSTRUCTOR,ho=Gt(),SI=ht(),vI=ie(),yI=bi(),mh=ho&&ho.prototype;mI({target:"Promise",proto:!0,forced:gI,real:!0},{catch:function(r){return this.then(void 0,r)}});!bI&&vI(ho)&&(po=SI("Promise").prototype.catch,mh.catch!==po&&yI(mh,"catch",po,{unsafe:!0}));var po});var gh=m(()=>{"use strict";var TI=Be(),II=we(),EI=ft(),xI=yi(),PI=Wa(),AI=Fa(),kI=lo();TI({target:"Promise",stat:!0,forced:kI},{race:function(e){var t=this,i=xI.f(t),a=i.reject,s=PI(function(){var n=EI(t.resolve);AI(e,function(o){II(n,t,o).then(i.resolve,a)})});return s.error&&a(s.value),i.promise}})});var Sh=m(()=>{"use strict";var wI=Be(),RI=yi(),LI=vi().CONSTRUCTOR;wI({target:"Promise",stat:!0,forced:LI},{reject:function(e){var t=RI.f(this),i=t.reject;return i(e),t.promise}})});var fo=m((Pk,vh)=>{"use strict";var $I=it(),MI=Ce(),CI=yi();vh.exports=function(r,e){if($I(r),MI(e)&&e.constructor===r)return e;var t=CI.f(r),i=t.resolve;return i(e),t.promise}});var Ih=m(()=>{"use strict";var DI=Be(),BI=ht(),yh=Ye(),OI=Gt(),Th=vi().CONSTRUCTOR,VI=fo(),_I=BI("Promise"),NI=yh&&!Th;DI({target:"Promise",stat:!0,forced:yh||Th},{resolve:function(e){return VI(NI&&this===_I?OI:this,e)}})});var Eh=m(()=>{"use strict";oh();fh();bh();gh();Sh();Ih()});var kh=m(()=>{"use strict";var FI=Be(),qI=Ye(),Za=Gt(),UI=ke(),Ph=ht(),Ah=ie(),HI=On(),xh=fo(),jI=bi(),bo=Za&&Za.prototype,GI=!!Za&&UI(function(){bo.finally.call({then:function(){}},function(){})});FI({target:"Promise",proto:!0,real:!0,forced:GI},{finally:function(r){var e=HI(this,Ph("Promise")),t=Ah(r);return this.then(t?function(i){return xh(e,r()).then(function(){return i})}:r,t?function(i){return xh(e,r()).then(function(){throw i})}:r)}});!qI&&Ah(Za)&&(mo=Ph("Promise").prototype.finally,bo.finally!==mo&&jI(bo,"finally",mo,{unsafe:!0}));var mo});var es=m((Mk,wh)=>{"use strict";var WI=ht();wh.exports=WI});var Lh=m((Ck,Rh)=>{"use strict";Od();Eh();kh();var YI=es();Rh.exports=YI("Promise","finally")});var Mh=m((Dk,$h)=>{"use strict";var QI=Lh();$h.exports=QI});var ts=m((Bk,Ch)=>{"use strict";var zI=Mh();Ch.exports=zI});var Hh=m(()=>{"use strict";var rE=Be(),aE=zi(),sE=$a(),nE=La(),oE=Cs();rE({target:"Array",proto:!0},{at:function(e){var t=aE(this),i=sE(t),a=nE(e),s=a>=0?a:i+a;return s<0||s>=i?void 0:t[s]}});oE("at")});var Gh=m((Cw,jh)=>{"use strict";Hh();var uE=es();jh.exports=uE("Array","at")});var Yh=m((Dw,Wh)=>{"use strict";var cE=Gh();Wh.exports=cE});var hr=m((Bw,Qh)=>{"use strict";var lE=Yh();Qh.exports=lE});var Lf=m(()=>{"use strict"});var $f=m(()=>{"use strict"});var Cf=m((EM,Mf)=>{"use strict";var jE=Ce(),GE=ui(),WE=fe(),YE=WE("match");Mf.exports=function(r){var e;return jE(r)&&((e=r[YE])!==void 0?!!e:GE(r)==="RegExp")}});var Bf=m((xM,Df)=>{"use strict";var QE=tr(),zE=String;Df.exports=function(r){if(QE(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return zE(r)}});var Vf=m((PM,Of)=>{"use strict";var KE=it();Of.exports=function(){var r=KE(this),e="";return r.hasIndices&&(e+="d"),r.global&&(e+="g"),r.ignoreCase&&(e+="i"),r.multiline&&(e+="m"),r.dotAll&&(e+="s"),r.unicode&&(e+="u"),r.unicodeSets&&(e+="v"),r.sticky&&(e+="y"),e}});var Ff=m((AM,Nf)=>{"use strict";var JE=we(),XE=Qe(),ZE=Gi(),ex=Vf(),_f=RegExp.prototype;Nf.exports=function(r){var e=r.flags;return e===void 0&&!("flags"in _f)&&!XE(r,"flags")&&ZE(_f,r)?JE(ex,r):e}});var Uf=m((kM,qf)=>{"use strict";var No=Se(),tx=zi(),ix=Math.floor,Vo=No("".charAt),rx=No("".replace),_o=No("".slice),ax=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,sx=/\$([$&'`]|\d{1,2})/g;qf.exports=function(r,e,t,i,a,s){var n=t+r.length,o=i.length,c=sx;return a!==void 0&&(a=tx(a),c=ax),rx(s,c,function(u,d){var l;switch(Vo(d,0)){case"$":return"$";case"&":return r;case"`":return _o(e,0,t);case"'":return _o(e,n);case"<":l=a[_o(d,1,-1)];break;default:var h=+d;if(h===0)return u;if(h>o){var f=ix(h/10);return f===0?u:f<=o?i[f-1]===void 0?Vo(d,1):i[f-1]+Vo(d,1):u}l=i[h-1]}return l===void 0?"":l})}});var Gf=m(()=>{"use strict";var nx=Be(),ox=we(),qo=Se(),Hf=Hi(),ux=ie(),cx=ci(),lx=Cf(),Di=Bf(),dx=Yi(),px=Ff(),hx=Uf(),fx=fe(),mx=Ye(),bx=fx("replace"),gx=TypeError,Fo=qo("".indexOf),Sx=qo("".replace),jf=qo("".slice),vx=Math.max;nx({target:"String",proto:!0},{replaceAll:function(e,t){var i=Hf(this),a,s,n,o,c,u,d,l,h,f,b=0,g="";if(!cx(e)){if(a=lx(e),a&&(s=Di(Hf(px(e))),!~Fo(s,"g")))throw new gx("`.replaceAll` does not allow non-global regexes");if(n=dx(e,bx),n)return ox(n,e,i,t);if(mx&&a)return Sx(Di(i),e,t)}for(o=Di(i),c=Di(e),u=ux(t),u||(t=Di(t)),d=c.length,l=vx(1,d),h=Fo(o,c);h!==-1;)f=u?Di(t(c,h,o)):hx(c,o,h,[],void 0,t),g+=jf(o,b,h)+f,b=h+d,h=h+l>o.length?-1:Fo(o,c,h+l);return b<o.length&&(g+=jf(o,b)),g}})});var Yf=m((LM,Wf)=>{"use strict";Lf();$f();Gf();var yx=es();Wf.exports=yx("String","replaceAll")});var zf=m(($M,Qf)=>{"use strict";var Tx=Yf();Qf.exports=Tx});var Jf=m((MM,Kf)=>{"use strict";var Ix=zf();Kf.exports=Ix});var Nx={};Nm(Nx,{ChromecastState:()=>qi,HttpConnectionType:()=>Sa,Observable:()=>ct.Observable,PlaybackState:()=>he,Player:()=>la,SDK_VERSION:()=>_x,Subject:()=>ct.Subject,Subscription:()=>ct.Subscription,Surface:()=>va,VERSION:()=>Ls,ValueSubject:()=>ct.ValueSubject,VideoFormat:()=>pt,VideoQuality:()=>ct.VideoQuality});module.exports=Fm(Nx);var Ls="2.0.113-dev.53b63d90.0";var he=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(he||{}),pt=(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))(pt||{});var qi=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(qi||{}),Sa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(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 su=r=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});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 i=(0,F.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||su("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),i=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(i,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=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,F.assertNever)(a.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(i,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)([i.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(qm),(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=i.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,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},qm=r=>{switch(r){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)(r)}};var Sm=Ge($n(),1);var Vh=Ge(ts(),1);var go=require("@vkontakte/videoplayer-shared");var de=(r,e=0,t=0)=>{switch(t){case 0:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return r;let i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,go.assertNever)(t)}return r},So=(r,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:(0,go.assertNever)(e)}};var A=(r,e,t=!1)=>{let i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};var rt=require("@vkontakte/videoplayer-shared"),H=class{constructor(e){this.transitionStarted$=new rt.Subject;this.transitionEnded$=new rt.Subject;this.transitionUpdated$=new rt.Subject;this.forceChanged$=new rt.Subject;this.stateChangeStarted$=(0,rt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,rt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,rt.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Dh=require("@vkontakte/videoplayer-shared"),Bh=r=>{switch(r){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,Dh.assertNever)(r)}};var R=require("@vkontakte/videoplayer-shared");var KI=5,JI=5,XI=500,Oh=7e3,pr=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(),i=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: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(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)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Bh(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)(XI)).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)>KI)&&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<JI&&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 i=(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(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(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(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,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),i=l,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];(0,R.assertNonNullable)(u),i=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),i=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),i=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),i=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??i,a);n.contentUrl=i,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 i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add((0,R.timeout)(Oh).subscribe(()=>s(`timeout(${Oh})`)))});(0,Vh.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},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 Io=require("@vkontakte/videoplayer-shared");var _h=require("@vkontakte/videoplayer-shared"),Nh=r=>{try{r.pause(),r.playbackRate=0,(0,_h.clearVideoElement)(r),r.remove()}catch(e){console.error(e)}};var is=require("@vkontakte/videoplayer-shared"),vo=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)}},yo=window.WeakMap?new WeakMap:new vo,To=window.WeakMap?new WeakMap:new Map,ZI=(r,e=20)=>{let t=0;return(0,is.fromEvent)(r,"ratechange").subscribe(i=>{t++,t>=e&&(r.currentTime=r.currentTime,t=0)})},ve=(r,{audioVideoSyncRate:e})=>{let t=r.querySelector("video"),i=!!t;t?(0,Io.clearVideoElement)(t):(t=document.createElement("video"),r.appendChild(t)),yo.set(t,i);let a=new is.Subscription;return a.add(ZI(t,e)),To.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ye=r=>{To.get(r)?.unsubscribe(),To.delete(r);let t=yo.get(r);yo.delete(r),t?(0,Io.clearVideoElement)(r):Nh(r)};var L=require("@vkontakte/videoplayer-shared");var $t=require("@vkontakte/videoplayer-shared"),rs=(r,e,t,{equal:i=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=r.getState(),o=e(),c=(0,$t.isNullable)(a),u=new $t.Subscription;return a&&u.add(a.subscribe(d=>{let l=r.getState();i(d,l)&&r.setState(d)},s)),i(o,n)||(t(n),c&&r.setState(n)),u.add(r.stateChangeStarted$.subscribe(d=>{t(d.to),c&&r.setState(d.to)},s)),u},at=(r,e,t)=>rs(e,()=>r.loop,i=>{(0,$t.isNonNullable)(i)&&(r.loop=i)},{onError:t}),Te=(r,e,t,i)=>rs(e,()=>({muted:r.muted,volume:r.volume}),a=>{(0,$t.isNonNullable)(a)&&(r.muted=a.muted,r.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:i}),Oe=(r,e,t,i)=>rs(e,()=>r.playbackRate,a=>{(0,$t.isNonNullable)(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),Mt=rs;var eE=r=>["__",r.language,r.label].join("|"),tE=(r,e)=>{if(r.id===e)return!0;let[t,i,a]=e.split("|");return r.language===i&&r.label===a},Eo=class r{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Mt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Mt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe((0,L.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,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,L.filterChanged)((i,a)=>i.length===a.length&&i.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,L.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,L.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(i=>{i.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))};i.track?.addEventListener("cuechange",a)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let a=i;(0,L.isNonNullable)(t.align)&&(a.align=t.align),(0,L.isNonNullable)(t.position)&&(a.position=t.position),(0,L.isNonNullable)(t.size)&&(a.size=t.size),(0,L.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(r.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,a=e.id?e.id:eE(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:i,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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:a,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!tE(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,L.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,L.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},st=Eo;var gt=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 Fh=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},xo=r=>{let e=Fh(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},qh=r=>{let e=Fh(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};var $=require("@vkontakte/videoplayer-shared");var iE=3,Uh=(r,e,t=iE)=>{let i=0,a=0;for(let s=0;s<r.length;s++){let n=r.start(s),o=r.end(s);if(n<=e&&e<=o){if(i=n,a=o,!t)return{from:i,to:a};for(let c=s-1;c>=0;c--)r.end(c)+t>=i&&(i=r.start(c));for(let c=s+1;c<r.length;c++)r.start(c)-t<=a&&(a=r.end(c))}}return{from:i,to:a}};var Ie=r=>{let e=x=>(0,$.fromEvent)(r,x).pipe((0,$.mapTo)(void 0)),i=(0,$.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,$.fromEvent)(r,x))).pipe((0,$.map)(x=>x.type==="ended"?r.readyState<2:r.readyState<3),(0,$.filterChanged)()),a=(0,$.merge)((0,$.fromEvent)(r,"progress"),(0,$.fromEvent)(r,"timeupdate")).pipe((0,$.map)(()=>Uh(r.buffered,r.currentTime))),s=$.clientChecker.isSafari?(0,$.combine)({play:e("play").pipe((0,$.once)()),playing:e("playing")}).pipe((0,$.mapTo)(void 0)):e("playing"),n=(0,$.fromEvent)(r,"volumechange").pipe((0,$.map)(()=>({muted:r.muted,volume:r.volume}))),o=(0,$.fromEvent)(r,"ratechange").pipe((0,$.map)(()=>r.playbackRate)),c=(0,$.fromEvent)(r,"error").pipe((0,$.filter)(()=>!!(r.error||r.played.length)),(0,$.map)(()=>{let x=r.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:$.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:r.error??void 0}})),u=(0,$.fromEvent)(r,"timeupdate").pipe((0,$.map)(()=>r.currentTime)),d=new $.Subject,l=.3,h;u.subscribe(x=>{r.loop&&(0,$.isNonNullable)(h)&&(0,$.isNonNullable)(x)&&h>=r.duration-l&&x<=l&&d.next(h),h=x});let f=e("pause").pipe((0,$.filter)(()=>!r.error&&h!==r.duration)),b=(0,$.fromEvent)(r,"enterpictureinpicture"),g=(0,$.fromEvent)(r,"leavepictureinpicture"),y=new $.ValueSubject(qh(r));b.subscribe(()=>y.next(!0)),g.subscribe(()=>y.next(!1));let E=new $.ValueSubject(xo(r));return(0,$.fromEvent)(r,"fullscreenchange").pipe((0,$.map)(()=>xo(r))).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,$.fromEvent)(r,"durationchange").pipe((0,$.map)(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:y,inFullscreen$:E}};var St=require("@vkontakte/videoplayer-shared"),Ct=r=>{switch(r){case"mobile":return St.VideoQuality.Q_144P;case"lowest":return St.VideoQuality.Q_240P;case"low":return St.VideoQuality.Q_360P;case"sd":case"medium":return St.VideoQuality.Q_480P;case"hd":case"high":return St.VideoQuality.Q_720P;case"fullhd":case"full":return St.VideoQuality.Q_1080P;case"quadhd":case"quad":return St.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return St.VideoQuality.Q_2160P}};var Yt=Ge(hr(),1),O=require("@vkontakte/videoplayer-shared");var Po=!1,vt={},zh=r=>{Po=r},Kh=()=>{vt={}},Jh=r=>{r(vt)},fr=(r,e)=>{Po&&(vt.meta=vt.meta??{},vt.meta[r]=e)},me=class{constructor(e){this.name=e}next(e){if(!Po)return;vt.series=vt.series??{};let t=vt.series[this.name]??[];t.push([Date.now(),e]),vt.series[this.name]=t}};var dE=new me("best_bitrate"),Zh=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;var Ao=r=>(e,t)=>r*(Number(e.bitrate)-Number(t.bitrate)),mr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,O.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ef='Assertion "ABR Tracks is empty array" failed',as=(r,e,t,i)=>{let a=[...e].sort(Ao(1)),s=[...t].sort(Ao(1)),n=s.filter(c=>(0,O.isNonNullable)(c.bitrate)&&(0,O.isNonNullable)(r.bitrate)?r.bitrate/c.bitrate>i:!0),o=(0,Yt.default)(s,Math.round(s.length*a.indexOf(r)/(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)},Xh=r=>"quality"in r,tf=(r,e,t,i)=>{let a=t&&i&&i.history[t.id]&&(0,O.now)()-i.history[t.id]<=r.trackCooldown&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let s=i.last;i?.recordSwitch(s);let n=Xh(s)?"video":"audio",o=Xh(s)?s.quality:s.bitrate;return e({message:`
|
|
6
|
+
"use strict";var Bm=Object.create;var ga=Object.defineProperty;var Om=Object.getOwnPropertyDescriptor;var Vm=Object.getOwnPropertyNames;var _m=Object.getPrototypeOf,Nm=Object.prototype.hasOwnProperty;var m=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Fm=(r,e)=>{for(var t in e)ga(r,t,{get:e[t],enumerable:!0})},au=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Vm(e))!Nm.call(r,a)&&a!==t&&ga(r,a,{get:()=>e[a],enumerable:!(i=Om(e,a))||i.enumerable});return r};var Ye=(r,e,t)=>(t=r!=null?Bm(_m(r)):{},au(e||!r||!r.__esModule?ga(t,"default",{value:r,enumerable:!0}):t,r)),qm=r=>au(ga({},"__esModule",{value:!0}),r);var ke=m((eP,nu)=>{"use strict";nu.exports=function(r){try{return!!r()}catch{return!0}}});var Ui=m((tP,ou)=>{"use strict";var Hm=ke();ou.exports=!Hm(function(){var r=function(){}.bind();return typeof r!="function"||r.hasOwnProperty("prototype")})});var Se=m((iP,lu)=>{"use strict";var uu=Ui(),cu=Function.prototype,$s=cu.call,jm=uu&&cu.bind.bind($s,$s);lu.exports=uu?jm:function(r){return function(){return $s.apply(r,arguments)}}});var ui=m((rP,pu)=>{"use strict";var du=Se(),Gm=du({}.toString),Wm=du("".slice);pu.exports=function(r){return Wm(Gm(r),8,-1)}});var fu=m((aP,hu)=>{"use strict";var Ym=Se(),Qm=ke(),zm=ui(),Ms=Object,Km=Ym("".split);hu.exports=Qm(function(){return!Ms("z").propertyIsEnumerable(0)})?function(r){return zm(r)==="String"?Km(r,""):Ms(r)}:Ms});var ci=m((sP,mu)=>{"use strict";mu.exports=function(r){return r==null}});var Hi=m((nP,bu)=>{"use strict";var Jm=ci(),Xm=TypeError;bu.exports=function(r){if(Jm(r))throw new Xm("Can't call method on "+r);return r}});var li=m((oP,gu)=>{"use strict";var Zm=fu(),eb=Hi();gu.exports=function(r){return Zm(eb(r))}});var Cs=m((uP,Su)=>{"use strict";Su.exports=function(){}});var qt=m((cP,vu)=>{"use strict";vu.exports={}});var ae=m((Ds,yu)=>{"use strict";var ji=function(r){return r&&r.Math===Math&&r};yu.exports=ji(typeof globalThis=="object"&&globalThis)||ji(typeof window=="object"&&window)||ji(typeof self=="object"&&self)||ji(typeof global=="object"&&global)||ji(typeof Ds=="object"&&Ds)||function(){return this}()||Function("return this")()});var ie=m((lP,Tu)=>{"use strict";var Bs=typeof document=="object"&&document.all;Tu.exports=typeof Bs>"u"&&Bs!==void 0?function(r){return typeof r=="function"||r===Bs}:function(r){return typeof r=="function"}});var xu=m((dP,Eu)=>{"use strict";var tb=ae(),ib=ie(),Iu=tb.WeakMap;Eu.exports=ib(Iu)&&/native code/.test(String(Iu))});var Ce=m((pP,Pu)=>{"use strict";var rb=ie();Pu.exports=function(r){return typeof r=="object"?r!==null:rb(r)}});var De=m((hP,Au)=>{"use strict";var ab=ke();Au.exports=!ab(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ta=m((fP,wu)=>{"use strict";var sb=ae(),ku=Ce(),Os=sb.document,nb=ku(Os)&&ku(Os.createElement);wu.exports=function(r){return nb?Os.createElement(r):{}}});var Vs=m((mP,Ru)=>{"use strict";var ob=De(),ub=ke(),cb=Ta();Ru.exports=!ob&&!ub(function(){return Object.defineProperty(cb("div"),"a",{get:function(){return 7}}).a!==7})});var _s=m((bP,Lu)=>{"use strict";var lb=De(),db=ke();Lu.exports=lb&&db(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var rt=m((gP,$u)=>{"use strict";var pb=Ce(),hb=String,fb=TypeError;$u.exports=function(r){if(pb(r))return r;throw new fb(hb(r)+" is not an object")}});var we=m((SP,Mu)=>{"use strict";var mb=Ui(),Ia=Function.prototype.call;Mu.exports=mb?Ia.bind(Ia):function(){return Ia.apply(Ia,arguments)}});var Ea=m((vP,Cu)=>{"use strict";Cu.exports={}});var ht=m((yP,Bu)=>{"use strict";var Ns=Ea(),Fs=ae(),bb=ie(),Du=function(r){return bb(r)?r:void 0};Bu.exports=function(r,e){return arguments.length<2?Du(Ns[r])||Du(Fs[r]):Ns[r]&&Ns[r][e]||Fs[r]&&Fs[r][e]}});var Gi=m((TP,Ou)=>{"use strict";var gb=Se();Ou.exports=gb({}.isPrototypeOf)});var di=m((IP,Nu)=>{"use strict";var Sb=ae(),Vu=Sb.navigator,_u=Vu&&Vu.userAgent;Nu.exports=_u?String(_u):""});var Us=m((EP,Gu)=>{"use strict";var ju=ae(),qs=di(),Fu=ju.process,qu=ju.Deno,Uu=Fu&&Fu.versions||qu&&qu.version,Hu=Uu&&Uu.v8,Qe,xa;Hu&&(Qe=Hu.split("."),xa=Qe[0]>0&&Qe[0]<4?1:+(Qe[0]+Qe[1]));!xa&&qs&&(Qe=qs.match(/Edge\/(\d+)/),(!Qe||Qe[1]>=74)&&(Qe=qs.match(/Chrome\/(\d+)/),Qe&&(xa=+Qe[1])));Gu.exports=xa});var Hs=m((xP,Yu)=>{"use strict";var Wu=Us(),vb=ke(),yb=ae(),Tb=yb.String;Yu.exports=!!Object.getOwnPropertySymbols&&!vb(function(){var r=Symbol("symbol detection");return!Tb(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&Wu&&Wu<41})});var js=m((PP,Qu)=>{"use strict";var Ib=Hs();Qu.exports=Ib&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Gs=m((AP,zu)=>{"use strict";var Eb=ht(),xb=ie(),Pb=Gi(),Ab=js(),kb=Object;zu.exports=Ab?function(r){return typeof r=="symbol"}:function(r){var e=Eb("Symbol");return xb(e)&&Pb(e.prototype,kb(r))}});var Wi=m((kP,Ku)=>{"use strict";var wb=String;Ku.exports=function(r){try{return wb(r)}catch{return"Object"}}});var ft=m((wP,Ju)=>{"use strict";var Rb=ie(),Lb=Wi(),$b=TypeError;Ju.exports=function(r){if(Rb(r))return r;throw new $b(Lb(r)+" is not a function")}});var Yi=m((RP,Xu)=>{"use strict";var Mb=ft(),Cb=ci();Xu.exports=function(r,e){var t=r[e];return Cb(t)?void 0:Mb(t)}});var ec=m((LP,Zu)=>{"use strict";var Ws=we(),Ys=ie(),Qs=Ce(),Db=TypeError;Zu.exports=function(r,e){var t,i;if(e==="string"&&Ys(t=r.toString)&&!Qs(i=Ws(t,r))||Ys(t=r.valueOf)&&!Qs(i=Ws(t,r))||e!=="string"&&Ys(t=r.toString)&&!Qs(i=Ws(t,r)))return i;throw new Db("Can't convert object to primitive value")}});var ze=m(($P,tc)=>{"use strict";tc.exports=!0});var ac=m((MP,rc)=>{"use strict";var ic=ae(),Bb=Object.defineProperty;rc.exports=function(r,e){try{Bb(ic,r,{value:e,configurable:!0,writable:!0})}catch{ic[r]=e}return e}});var Qi=m((CP,oc)=>{"use strict";var Ob=ze(),Vb=ae(),_b=ac(),sc="__core-js_shared__",nc=oc.exports=Vb[sc]||_b(sc,{});(nc.versions||(nc.versions=[])).push({version:"3.38.0",mode:Ob?"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 zs=m((DP,cc)=>{"use strict";var uc=Qi();cc.exports=function(r,e){return uc[r]||(uc[r]=e||{})}});var zi=m((BP,lc)=>{"use strict";var Nb=Hi(),Fb=Object;lc.exports=function(r){return Fb(Nb(r))}});var Ke=m((OP,dc)=>{"use strict";var qb=Se(),Ub=zi(),Hb=qb({}.hasOwnProperty);dc.exports=Object.hasOwn||function(e,t){return Hb(Ub(e),t)}});var Ks=m((VP,pc)=>{"use strict";var jb=Se(),Gb=0,Wb=Math.random(),Yb=jb(1 .toString);pc.exports=function(r){return"Symbol("+(r===void 0?"":r)+")_"+Yb(++Gb+Wb,36)}});var me=m((_P,fc)=>{"use strict";var Qb=ae(),zb=zs(),hc=Ke(),Kb=Ks(),Jb=Hs(),Xb=js(),pi=Qb.Symbol,Js=zb("wks"),Zb=Xb?pi.for||pi:pi&&pi.withoutSetter||Kb;fc.exports=function(r){return hc(Js,r)||(Js[r]=Jb&&hc(pi,r)?pi[r]:Zb("Symbol."+r)),Js[r]}});var Sc=m((NP,gc)=>{"use strict";var eg=we(),mc=Ce(),bc=Gs(),tg=Yi(),ig=ec(),rg=me(),ag=TypeError,sg=rg("toPrimitive");gc.exports=function(r,e){if(!mc(r)||bc(r))return r;var t=tg(r,sg),i;if(t){if(e===void 0&&(e="default"),i=eg(t,r,e),!mc(i)||bc(i))return i;throw new ag("Can't convert object to primitive value")}return e===void 0&&(e="number"),ig(r,e)}});var Xs=m((FP,vc)=>{"use strict";var ng=Sc(),og=Gs();vc.exports=function(r){var e=ng(r,"string");return og(e)?e:e+""}});var Ut=m(Tc=>{"use strict";var ug=De(),cg=Vs(),lg=_s(),Pa=rt(),yc=Xs(),dg=TypeError,Zs=Object.defineProperty,pg=Object.getOwnPropertyDescriptor,en="enumerable",tn="configurable",rn="writable";Tc.f=ug?lg?function(e,t,i){if(Pa(e),t=yc(t),Pa(i),typeof e=="function"&&t==="prototype"&&"value"in i&&rn in i&&!i[rn]){var a=pg(e,t);a&&a[rn]&&(e[t]=i.value,i={configurable:tn in i?i[tn]:a[tn],enumerable:en in i?i[en]:a[en],writable:!1})}return Zs(e,t,i)}:Zs:function(e,t,i){if(Pa(e),t=yc(t),Pa(i),cg)try{return Zs(e,t,i)}catch{}if("get"in i||"set"in i)throw new dg("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ki=m((UP,Ic)=>{"use strict";Ic.exports=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}}});var hi=m((HP,Ec)=>{"use strict";var hg=De(),fg=Ut(),mg=Ki();Ec.exports=hg?function(r,e,t){return fg.f(r,e,mg(1,t))}:function(r,e,t){return r[e]=t,r}});var Aa=m((jP,Pc)=>{"use strict";var bg=zs(),gg=Ks(),xc=bg("keys");Pc.exports=function(r){return xc[r]||(xc[r]=gg(r))}});var ka=m((GP,Ac)=>{"use strict";Ac.exports={}});var on=m((WP,Rc)=>{"use strict";var Sg=xu(),wc=ae(),vg=Ce(),yg=hi(),an=Ke(),sn=Qi(),Tg=Aa(),Ig=ka(),kc="Object already initialized",nn=wc.TypeError,Eg=wc.WeakMap,wa,Ji,Ra,xg=function(r){return Ra(r)?Ji(r):wa(r,{})},Pg=function(r){return function(e){var t;if(!vg(e)||(t=Ji(e)).type!==r)throw new nn("Incompatible receiver, "+r+" required");return t}};Sg||sn.state?(Je=sn.state||(sn.state=new Eg),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,wa=function(r,e){if(Je.has(r))throw new nn(kc);return e.facade=r,Je.set(r,e),e},Ji=function(r){return Je.get(r)||{}},Ra=function(r){return Je.has(r)}):(Ht=Tg("state"),Ig[Ht]=!0,wa=function(r,e){if(an(r,Ht))throw new nn(kc);return e.facade=r,yg(r,Ht,e),e},Ji=function(r){return an(r,Ht)?r[Ht]:{}},Ra=function(r){return an(r,Ht)});var Je,Ht;Rc.exports={set:wa,get:Ji,has:Ra,enforce:xg,getterFor:Pg}});var un=m((YP,Cc)=>{"use strict";var Ag=Ui(),Mc=Function.prototype,Lc=Mc.apply,$c=Mc.call;Cc.exports=typeof Reflect=="object"&&Reflect.apply||(Ag?$c.bind(Lc):function(){return $c.apply(Lc,arguments)})});var cn=m((QP,Dc)=>{"use strict";var kg=ui(),wg=Se();Dc.exports=function(r){if(kg(r)==="Function")return wg(r)}});var _c=m(Vc=>{"use strict";var Bc={}.propertyIsEnumerable,Oc=Object.getOwnPropertyDescriptor,Rg=Oc&&!Bc.call({1:2},1);Vc.f=Rg?function(e){var t=Oc(this,e);return!!t&&t.enumerable}:Bc});var qc=m(Fc=>{"use strict";var Lg=De(),$g=we(),Mg=_c(),Cg=Ki(),Dg=li(),Bg=Xs(),Og=Ke(),Vg=Vs(),Nc=Object.getOwnPropertyDescriptor;Fc.f=Lg?Nc:function(e,t){if(e=Dg(e),t=Bg(t),Vg)try{return Nc(e,t)}catch{}if(Og(e,t))return Cg(!$g(Mg.f,e,t),e[t])}});var ln=m((JP,Uc)=>{"use strict";var _g=ke(),Ng=ie(),Fg=/#|\.prototype\./,Xi=function(r,e){var t=Ug[qg(r)];return t===jg?!0:t===Hg?!1:Ng(e)?_g(e):!!e},qg=Xi.normalize=function(r){return String(r).replace(Fg,".").toLowerCase()},Ug=Xi.data={},Hg=Xi.NATIVE="N",jg=Xi.POLYFILL="P";Uc.exports=Xi});var Zi=m((XP,jc)=>{"use strict";var Hc=cn(),Gg=ft(),Wg=Ui(),Yg=Hc(Hc.bind);jc.exports=function(r,e){return Gg(r),e===void 0?r:Wg?Yg(r,e):function(){return r.apply(e,arguments)}}});var Be=m((ZP,Wc)=>{"use strict";var er=ae(),Qg=un(),zg=cn(),Kg=ie(),Jg=qc().f,Xg=ln(),fi=Ea(),Zg=Zi(),mi=hi(),Gc=Ke();Qi();var eS=function(r){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new r;case 1:return new r(t);case 2:return new r(t,i)}return new r(t,i,a)}return Qg(r,this,arguments)};return e.prototype=r.prototype,e};Wc.exports=function(r,e){var t=r.target,i=r.global,a=r.stat,s=r.proto,n=i?er:a?er[t]:er[t]&&er[t].prototype,o=i?fi:fi[t]||mi(fi,t,{})[t],c=o.prototype,u,d,l,p,f,b,g,y,E;for(p in e)u=Xg(i?p:t+(a?".":"#")+p,r.forced),d=!u&&n&&Gc(n,p),b=o[p],d&&(r.dontCallGetSet?(E=Jg(n,p),g=E&&E.value):g=n[p]),f=d&&g?g:e[p],!(!u&&!s&&typeof b==typeof f)&&(r.bind&&d?y=Zg(f,er):r.wrap&&d?y=eS(f):s&&Kg(f)?y=zg(f):y=f,(r.sham||f&&f.sham||b&&b.sham)&&mi(y,"sham",!0),mi(o,p,y),s&&(l=t+"Prototype",Gc(fi,l)||mi(fi,l,{}),mi(fi[l],p,f),r.real&&c&&(u||!c[p])&&mi(c,p,f)))}});var zc=m((eA,Qc)=>{"use strict";var dn=De(),tS=Ke(),Yc=Function.prototype,iS=dn&&Object.getOwnPropertyDescriptor,pn=tS(Yc,"name"),rS=pn&&function(){}.name==="something",aS=pn&&(!dn||dn&&iS(Yc,"name").configurable);Qc.exports={EXISTS:pn,PROPER:rS,CONFIGURABLE:aS}});var Jc=m((tA,Kc)=>{"use strict";var sS=Math.ceil,nS=Math.floor;Kc.exports=Math.trunc||function(e){var t=+e;return(t>0?nS:sS)(t)}});var La=m((iA,Xc)=>{"use strict";var oS=Jc();Xc.exports=function(r){var e=+r;return e!==e||e===0?0:oS(e)}});var el=m((rA,Zc)=>{"use strict";var uS=La(),cS=Math.max,lS=Math.min;Zc.exports=function(r,e){var t=uS(r);return t<0?cS(t+e,0):lS(t,e)}});var il=m((aA,tl)=>{"use strict";var dS=La(),pS=Math.min;tl.exports=function(r){var e=dS(r);return e>0?pS(e,9007199254740991):0}});var $a=m((sA,rl)=>{"use strict";var hS=il();rl.exports=function(r){return hS(r.length)}});var nl=m((nA,sl)=>{"use strict";var fS=li(),mS=el(),bS=$a(),al=function(r){return function(e,t,i){var a=fS(e),s=bS(a);if(s===0)return!r&&-1;var n=mS(i,s),o;if(r&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((r||n in a)&&a[n]===t)return r||n||0;return!r&&-1}};sl.exports={includes:al(!0),indexOf:al(!1)}});var cl=m((oA,ul)=>{"use strict";var gS=Se(),hn=Ke(),SS=li(),vS=nl().indexOf,yS=ka(),ol=gS([].push);ul.exports=function(r,e){var t=SS(r),i=0,a=[],s;for(s in t)!hn(yS,s)&&hn(t,s)&&ol(a,s);for(;e.length>i;)hn(t,s=e[i++])&&(~vS(a,s)||ol(a,s));return a}});var fn=m((uA,ll)=>{"use strict";ll.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var pl=m((cA,dl)=>{"use strict";var TS=cl(),IS=fn();dl.exports=Object.keys||function(e){return TS(e,IS)}});var fl=m(hl=>{"use strict";var ES=De(),xS=_s(),PS=Ut(),AS=rt(),kS=li(),wS=pl();hl.f=ES&&!xS?Object.defineProperties:function(e,t){AS(e);for(var i=kS(t),a=wS(t),s=a.length,n=0,o;s>n;)PS.f(e,o=a[n++],i[o]);return e}});var mn=m((dA,ml)=>{"use strict";var RS=ht();ml.exports=RS("document","documentElement")});var vn=m((pA,Il)=>{"use strict";var LS=rt(),$S=fl(),bl=fn(),MS=ka(),CS=mn(),DS=Ta(),BS=Aa(),gl=">",Sl="<",gn="prototype",Sn="script",yl=BS("IE_PROTO"),bn=function(){},Tl=function(r){return Sl+Sn+gl+r+Sl+"/"+Sn+gl},vl=function(r){r.write(Tl("")),r.close();var e=r.parentWindow.Object;return r=null,e},OS=function(){var r=DS("iframe"),e="java"+Sn+":",t;return r.style.display="none",CS.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(Tl("document.F=Object")),t.close(),t.F},Ma,Ca=function(){try{Ma=new ActiveXObject("htmlfile")}catch{}Ca=typeof document<"u"?document.domain&&Ma?vl(Ma):OS():vl(Ma);for(var r=bl.length;r--;)delete Ca[gn][bl[r]];return Ca()};MS[yl]=!0;Il.exports=Object.create||function(e,t){var i;return e!==null?(bn[gn]=LS(e),i=new bn,bn[gn]=null,i[yl]=e):i=Ca(),t===void 0?i:$S.f(i,t)}});var xl=m((hA,El)=>{"use strict";var VS=ke();El.exports=!VS(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype})});var Tn=m((fA,Al)=>{"use strict";var _S=Ke(),NS=ie(),FS=zi(),qS=Aa(),US=xl(),Pl=qS("IE_PROTO"),yn=Object,HS=yn.prototype;Al.exports=US?yn.getPrototypeOf:function(r){var e=FS(r);if(_S(e,Pl))return e[Pl];var t=e.constructor;return NS(t)&&e instanceof t?t.prototype:e instanceof yn?HS:null}});var bi=m((mA,kl)=>{"use strict";var jS=hi();kl.exports=function(r,e,t,i){return i&&i.enumerable?r[e]=t:jS(r,e,t),r}});var Pn=m((bA,Ll)=>{"use strict";var GS=ke(),WS=ie(),YS=Ce(),QS=vn(),wl=Tn(),zS=bi(),KS=me(),JS=ze(),xn=KS("iterator"),Rl=!1,mt,In,En;[].keys&&(En=[].keys(),"next"in En?(In=wl(wl(En)),In!==Object.prototype&&(mt=In)):Rl=!0);var XS=!YS(mt)||GS(function(){var r={};return mt[xn].call(r)!==r});XS?mt={}:JS&&(mt=QS(mt));WS(mt[xn])||zS(mt,xn,function(){return this});Ll.exports={IteratorPrototype:mt,BUGGY_SAFARI_ITERATORS:Rl}});var Da=m((gA,Ml)=>{"use strict";var ZS=me(),ev=ZS("toStringTag"),$l={};$l[ev]="z";Ml.exports=String($l)==="[object z]"});var tr=m((SA,Cl)=>{"use strict";var tv=Da(),iv=ie(),Ba=ui(),rv=me(),av=rv("toStringTag"),sv=Object,nv=Ba(function(){return arguments}())==="Arguments",ov=function(r,e){try{return r[e]}catch{}};Cl.exports=tv?Ba:function(r){var e,t,i;return r===void 0?"Undefined":r===null?"Null":typeof(t=ov(e=sv(r),av))=="string"?t:nv?Ba(e):(i=Ba(e))==="Object"&&iv(e.callee)?"Arguments":i}});var Bl=m((vA,Dl)=>{"use strict";var uv=Da(),cv=tr();Dl.exports=uv?{}.toString:function(){return"[object "+cv(this)+"]"}});var ir=m((yA,Vl)=>{"use strict";var lv=Da(),dv=Ut().f,pv=hi(),hv=Ke(),fv=Bl(),mv=me(),Ol=mv("toStringTag");Vl.exports=function(r,e,t,i){var a=t?r:r&&r.prototype;a&&(hv(a,Ol)||dv(a,Ol,{configurable:!0,value:e}),i&&!lv&&pv(a,"toString",fv))}});var Nl=m((TA,_l)=>{"use strict";var bv=Pn().IteratorPrototype,gv=vn(),Sv=Ki(),vv=ir(),yv=qt(),Tv=function(){return this};_l.exports=function(r,e,t,i){var a=e+" Iterator";return r.prototype=gv(bv,{next:Sv(+!i,t)}),vv(r,a,!1,!0),yv[a]=Tv,r}});var ql=m((IA,Fl)=>{"use strict";var Iv=Se(),Ev=ft();Fl.exports=function(r,e,t){try{return Iv(Ev(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}}});var Hl=m((EA,Ul)=>{"use strict";var xv=Ce();Ul.exports=function(r){return xv(r)||r===null}});var Gl=m((xA,jl)=>{"use strict";var Pv=Hl(),Av=String,kv=TypeError;jl.exports=function(r){if(Pv(r))return r;throw new kv("Can't set "+Av(r)+" as a prototype")}});var An=m((PA,Wl)=>{"use strict";var wv=ql(),Rv=Ce(),Lv=Hi(),$v=Gl();Wl.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=wv(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(a,s){return Lv(a),$v(s),Rv(a)&&(r?t(a,s):a.__proto__=s),a}}():void 0)});var rd=m((AA,id)=>{"use strict";var Mv=Be(),Cv=we(),Oa=ze(),ed=zc(),Dv=ie(),Bv=Nl(),Yl=Tn(),Ql=An(),Ov=ir(),Vv=hi(),kn=bi(),_v=me(),zl=qt(),td=Pn(),Nv=ed.PROPER,Fv=ed.CONFIGURABLE,Kl=td.IteratorPrototype,Va=td.BUGGY_SAFARI_ITERATORS,rr=_v("iterator"),Jl="keys",ar="values",Xl="entries",Zl=function(){return this};id.exports=function(r,e,t,i,a,s,n){Bv(t,e,i);var o=function(E){if(E===a&&p)return p;if(!Va&&E&&E in d)return d[E];switch(E){case Jl:return function(){return new t(this,E)};case ar:return function(){return new t(this,E)};case Xl:return function(){return new t(this,E)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=r.prototype,l=d[rr]||d["@@iterator"]||a&&d[a],p=!Va&&l||o(a),f=e==="Array"&&d.entries||l,b,g,y;if(f&&(b=Yl(f.call(new r)),b!==Object.prototype&&b.next&&(!Oa&&Yl(b)!==Kl&&(Ql?Ql(b,Kl):Dv(b[rr])||kn(b,rr,Zl)),Ov(b,c,!0,!0),Oa&&(zl[c]=Zl))),Nv&&a===ar&&l&&l.name!==ar&&(!Oa&&Fv?Vv(d,"name",ar):(u=!0,p=function(){return Cv(l,this)})),a)if(g={values:o(ar),keys:s?p:o(Jl),entries:o(Xl)},n)for(y in g)(Va||u||!(y in d))&&kn(d,y,g[y]);else Mv({target:e,proto:!0,forced:Va||u},g);return(!Oa||n)&&d[rr]!==p&&kn(d,rr,p,{name:a}),zl[e]=p,g}});var sd=m((kA,ad)=>{"use strict";ad.exports=function(r,e){return{value:r,done:e}}});var Rn=m((wA,ld)=>{"use strict";var qv=li(),wn=Cs(),nd=qt(),ud=on(),Uv=Ut().f,Hv=rd(),_a=sd(),jv=ze(),Gv=De(),cd="Array Iterator",Wv=ud.set,Yv=ud.getterFor(cd);ld.exports=Hv(Array,"Array",function(r,e){Wv(this,{type:cd,target:qv(r),index:0,kind:e})},function(){var r=Yv(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=void 0,_a(void 0,!0);switch(r.kind){case"keys":return _a(t,!1);case"values":return _a(e[t],!1)}return _a([t,e[t]],!1)},"values");var od=nd.Arguments=nd.Array;wn("keys");wn("values");wn("entries");if(!jv&&Gv&&od.name!=="values")try{Uv(od,"name",{value:"values"})}catch{}});var pd=m((RA,dd)=>{"use strict";var Qv=me(),zv=qt(),Kv=Qv("iterator"),Jv=Array.prototype;dd.exports=function(r){return r!==void 0&&(zv.Array===r||Jv[Kv]===r)}});var Ln=m((LA,fd)=>{"use strict";var Xv=tr(),hd=Yi(),Zv=ci(),ey=qt(),ty=me(),iy=ty("iterator");fd.exports=function(r){if(!Zv(r))return hd(r,iy)||hd(r,"@@iterator")||ey[Xv(r)]}});var bd=m(($A,md)=>{"use strict";var ry=we(),ay=ft(),sy=rt(),ny=Wi(),oy=Ln(),uy=TypeError;md.exports=function(r,e){var t=arguments.length<2?oy(r):e;if(ay(t))return sy(ry(t,r));throw new uy(ny(r)+" is not iterable")}});var vd=m((MA,Sd)=>{"use strict";var cy=we(),gd=rt(),ly=Yi();Sd.exports=function(r,e,t){var i,a;gd(r);try{if(i=ly(r,"return"),!i){if(e==="throw")throw t;return t}i=cy(i,r)}catch(s){a=!0,i=s}if(e==="throw")throw t;if(a)throw i;return gd(i),t}});var Fa=m((CA,Ed)=>{"use strict";var dy=Zi(),py=we(),hy=rt(),fy=Wi(),my=pd(),by=$a(),yd=Gi(),gy=bd(),Sy=Ln(),Td=vd(),vy=TypeError,Na=function(r,e){this.stopped=r,this.result=e},Id=Na.prototype;Ed.exports=function(r,e,t){var i=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,i),u,d,l,p,f,b,g,y=function(C){return u&&Td(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=r.iterator;else if(n)u=r;else{if(d=Sy(r),!d)throw new vy(fy(r)+" is not iterable");if(my(d)){for(l=0,p=by(r);p>l;l++)if(f=E(r[l]),f&&yd(Id,f))return f;return new Na(!1)}u=gy(r,d)}for(b=s?r.next:u.next;!(g=py(b,u)).done;){try{f=E(g.value)}catch(C){Td(u,"throw",C)}if(typeof f=="object"&&f&&yd(Id,f))return f}return new Na(!1)}});var Pd=m((DA,xd)=>{"use strict";var yy=De(),Ty=Ut(),Iy=Ki();xd.exports=function(r,e,t){yy?Ty.f(r,e,Iy(0,t)):r[e]=t}});var Ad=m(()=>{"use strict";var Ey=Be(),xy=Fa(),Py=Pd();Ey({target:"Object",stat:!0},{fromEntries:function(e){var t={};return xy(e,function(i,a){Py(t,i,a)},{AS_ENTRIES:!0}),t}})});var wd=m((VA,kd)=>{"use strict";Rn();Ad();var Ay=Ea();kd.exports=Ay.Object.fromEntries});var Ld=m((_A,Rd)=>{"use strict";Rd.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 Md=m(()=>{"use strict";Rn();var ky=Ld(),wy=ae(),Ry=ir(),$d=qt();for(qa in ky)Ry(wy[qa],qa),$d[qa]=$d.Array;var qa});var Dd=m((qA,Cd)=>{"use strict";var Ly=wd();Md();Cd.exports=Ly});var $n=m((UA,Bd)=>{"use strict";var $y=Dd();Bd.exports=$y});var Od=m(()=>{"use strict"});var Mn=m((GA,Vd)=>{"use strict";var sr=ae(),My=di(),Cy=ui(),Ua=function(r){return My.slice(0,r.length)===r};Vd.exports=function(){return Ua("Bun/")?"BUN":Ua("Cloudflare-Workers")?"CLOUDFLARE":Ua("Deno/")?"DENO":Ua("Node.js/")?"NODE":sr.Bun&&typeof Bun.version=="string"?"BUN":sr.Deno&&typeof Deno.version=="object"?"DENO":Cy(sr.process)==="process"?"NODE":sr.window&&sr.document?"BROWSER":"REST"}()});var Ha=m((WA,_d)=>{"use strict";var Dy=Mn();_d.exports=Dy==="NODE"});var Fd=m((YA,Nd)=>{"use strict";var By=Ut();Nd.exports=function(r,e,t){return By.f(r,e,t)}});var Hd=m((QA,Ud)=>{"use strict";var Oy=ht(),Vy=Fd(),_y=me(),Ny=De(),qd=_y("species");Ud.exports=function(r){var e=Oy(r);Ny&&e&&!e[qd]&&Vy(e,qd,{configurable:!0,get:function(){return this}})}});var Gd=m((zA,jd)=>{"use strict";var Fy=Gi(),qy=TypeError;jd.exports=function(r,e){if(Fy(e,r))return r;throw new qy("Incorrect invocation")}});var Dn=m((KA,Wd)=>{"use strict";var Uy=Se(),Hy=ie(),Cn=Qi(),jy=Uy(Function.toString);Hy(Cn.inspectSource)||(Cn.inspectSource=function(r){return jy(r)});Wd.exports=Cn.inspectSource});var Xd=m((JA,Jd)=>{"use strict";var Gy=Se(),Wy=ke(),Yd=ie(),Yy=tr(),Qy=ht(),zy=Dn(),Qd=function(){},zd=Qy("Reflect","construct"),Bn=/^\s*(?:class|function)\b/,Ky=Gy(Bn.exec),Jy=!Bn.test(Qd),nr=function(e){if(!Yd(e))return!1;try{return zd(Qd,[],e),!0}catch{return!1}},Kd=function(e){if(!Yd(e))return!1;switch(Yy(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jy||!!Ky(Bn,zy(e))}catch{return!0}};Kd.sham=!0;Jd.exports=!zd||Wy(function(){var r;return nr(nr.call)||!nr(Object)||!nr(function(){r=!0})||r})?Kd:nr});var ep=m((XA,Zd)=>{"use strict";var Xy=Xd(),Zy=Wi(),eT=TypeError;Zd.exports=function(r){if(Xy(r))return r;throw new eT(Zy(r)+" is not a constructor")}});var On=m((ZA,ip)=>{"use strict";var tp=rt(),tT=ep(),iT=ci(),rT=me(),aT=rT("species");ip.exports=function(r,e){var t=tp(r).constructor,i;return t===void 0||iT(i=tp(t)[aT])?e:tT(i)}});var ap=m((ek,rp)=>{"use strict";var sT=Se();rp.exports=sT([].slice)});var np=m((tk,sp)=>{"use strict";var nT=TypeError;sp.exports=function(r,e){if(r<e)throw new nT("Not enough arguments");return r}});var Vn=m((ik,op)=>{"use strict";var oT=di();op.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(oT)});var Wn=m((rk,bp)=>{"use strict";var Re=ae(),uT=un(),cT=Zi(),up=ie(),lT=Ke(),mp=ke(),cp=mn(),dT=ap(),lp=Ta(),pT=np(),hT=Vn(),fT=Ha(),Hn=Re.setImmediate,jn=Re.clearImmediate,mT=Re.process,_n=Re.Dispatch,bT=Re.Function,dp=Re.MessageChannel,gT=Re.String,Nn=0,or={},pp="onreadystatechange",ur,jt,Fn,qn;mp(function(){ur=Re.location});var Gn=function(r){if(lT(or,r)){var e=or[r];delete or[r],e()}},Un=function(r){return function(){Gn(r)}},hp=function(r){Gn(r.data)},fp=function(r){Re.postMessage(gT(r),ur.protocol+"//"+ur.host)};(!Hn||!jn)&&(Hn=function(e){pT(arguments.length,1);var t=up(e)?e:bT(e),i=dT(arguments,1);return or[++Nn]=function(){uT(t,void 0,i)},jt(Nn),Nn},jn=function(e){delete or[e]},fT?jt=function(r){mT.nextTick(Un(r))}:_n&&_n.now?jt=function(r){_n.now(Un(r))}:dp&&!hT?(Fn=new dp,qn=Fn.port2,Fn.port1.onmessage=hp,jt=cT(qn.postMessage,qn)):Re.addEventListener&&up(Re.postMessage)&&!Re.importScripts&&ur&&ur.protocol!=="file:"&&!mp(fp)?(jt=fp,Re.addEventListener("message",hp,!1)):pp in lp("script")?jt=function(r){cp.appendChild(lp("script"))[pp]=function(){cp.removeChild(this),Gn(r)}}:jt=function(r){setTimeout(Un(r),0)});bp.exports={set:Hn,clear:jn}});var vp=m((ak,Sp)=>{"use strict";var gp=ae(),ST=De(),vT=Object.getOwnPropertyDescriptor;Sp.exports=function(r){if(!ST)return gp[r];var e=vT(gp,r);return e&&e.value}});var Yn=m((sk,Tp)=>{"use strict";var yp=function(){this.head=null,this.tail=null};yp.prototype={add:function(r){var e={item:r,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var r=this.head;if(r){var e=this.head=r.next;return e===null&&(this.tail=null),r.item}}};Tp.exports=yp});var Ep=m((nk,Ip)=>{"use strict";var yT=di();Ip.exports=/ipad|iphone|ipod/i.test(yT)&&typeof Pebble<"u"});var Pp=m((ok,xp)=>{"use strict";var TT=di();xp.exports=/web0s(?!.*chrome)/i.test(TT)});var Mp=m((uk,$p)=>{"use strict";var Si=ae(),IT=vp(),Ap=Zi(),Qn=Wn().set,ET=Yn(),xT=Vn(),PT=Ep(),AT=Pp(),zn=Ha(),kp=Si.MutationObserver||Si.WebKitMutationObserver,wp=Si.document,Rp=Si.process,ja=Si.Promise,Xn=IT("queueMicrotask"),gi,Kn,Jn,Ga,Lp;Xn||(cr=new ET,lr=function(){var r,e;for(zn&&(r=Rp.domain)&&r.exit();e=cr.get();)try{e()}catch(t){throw cr.head&&gi(),t}r&&r.enter()},!xT&&!zn&&!AT&&kp&&wp?(Kn=!0,Jn=wp.createTextNode(""),new kp(lr).observe(Jn,{characterData:!0}),gi=function(){Jn.data=Kn=!Kn}):!PT&&ja&&ja.resolve?(Ga=ja.resolve(void 0),Ga.constructor=ja,Lp=Ap(Ga.then,Ga),gi=function(){Lp(lr)}):zn?gi=function(){Rp.nextTick(lr)}:(Qn=Ap(Qn,Si),gi=function(){Qn(lr)}),Xn=function(r){cr.head||gi(),cr.add(r)});var cr,lr;$p.exports=Xn});var Dp=m((ck,Cp)=>{"use strict";Cp.exports=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}}});var Wa=m((lk,Bp)=>{"use strict";Bp.exports=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}}});var Gt=m((dk,Op)=>{"use strict";var kT=ae();Op.exports=kT.Promise});var vi=m((pk,Fp)=>{"use strict";var wT=ae(),dr=Gt(),RT=ie(),LT=ln(),$T=Dn(),MT=me(),Vp=Mn(),CT=ze(),Zn=Us(),_p=dr&&dr.prototype,DT=MT("species"),eo=!1,Np=RT(wT.PromiseRejectionEvent),BT=LT("Promise",function(){var r=$T(dr),e=r!==String(dr);if(!e&&Zn===66||CT&&!(_p.catch&&_p.finally))return!0;if(!Zn||Zn<51||!/native code/.test(r)){var t=new dr(function(s){s(1)}),i=function(s){s(function(){},function(){})},a=t.constructor={};if(a[DT]=i,eo=t.then(function(){})instanceof i,!eo)return!0}return!e&&(Vp==="BROWSER"||Vp==="DENO")&&!Np});Fp.exports={CONSTRUCTOR:BT,REJECTION_EVENT:Np,SUBCLASSING:eo}});var yi=m((hk,Up)=>{"use strict";var qp=ft(),OT=TypeError,VT=function(r){var e,t;this.promise=new r(function(i,a){if(e!==void 0||t!==void 0)throw new OT("Bad Promise constructor");e=i,t=a}),this.resolve=qp(e),this.reject=qp(t)};Up.exports.f=function(r){return new VT(r)}});var oh=m(()=>{"use strict";var _T=Be(),NT=ze(),Ka=Ha(),Lt=ae(),xi=we(),Hp=bi(),jp=An(),FT=ir(),qT=Hd(),UT=ft(),za=ie(),HT=Ce(),jT=Gd(),GT=On(),zp=Wn().set,so=Mp(),WT=Dp(),YT=Wa(),QT=Yn(),Kp=on(),Ja=Gt(),no=vi(),Jp=yi(),Xa="Promise",Xp=no.CONSTRUCTOR,zT=no.REJECTION_EVENT,KT=no.SUBCLASSING,to=Kp.getterFor(Xa),JT=Kp.set,Ti=Ja&&Ja.prototype,Wt=Ja,Ya=Ti,Zp=Lt.TypeError,io=Lt.document,oo=Lt.process,ro=Jp.f,XT=ro,ZT=!!(io&&io.createEvent&&Lt.dispatchEvent),eh="unhandledrejection",eI="rejectionhandled",Gp=0,th=1,tI=2,uo=1,ih=2,Qa,Wp,iI,Yp,rh=function(r){var e;return HT(r)&&za(e=r.then)?e:!1},ah=function(r,e){var t=e.value,i=e.state===th,a=i?r.ok:r.fail,s=r.resolve,n=r.reject,o=r.domain,c,u,d;try{a?(i||(e.rejection===ih&&aI(e),e.rejection=uo),a===!0?c=t:(o&&o.enter(),c=a(t),o&&(o.exit(),d=!0)),c===r.promise?n(new Zp("Promise-chain cycle")):(u=rh(c))?xi(u,c,s,n):s(c)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},sh=function(r,e){r.notified||(r.notified=!0,so(function(){for(var t=r.reactions,i;i=t.get();)ah(i,r);r.notified=!1,e&&!r.rejection&&rI(r)}))},nh=function(r,e,t){var i,a;ZT?(i=io.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(r,!1,!0),Lt.dispatchEvent(i)):i={promise:e,reason:t},!zT&&(a=Lt["on"+r])?a(i):r===eh&&WT("Unhandled promise rejection",t)},rI=function(r){xi(zp,Lt,function(){var e=r.facade,t=r.value,i=Qp(r),a;if(i&&(a=YT(function(){Ka?oo.emit("unhandledRejection",t,e):nh(eh,e,t)}),r.rejection=Ka||Qp(r)?ih:uo,a.error))throw a.value})},Qp=function(r){return r.rejection!==uo&&!r.parent},aI=function(r){xi(zp,Lt,function(){var e=r.facade;Ka?oo.emit("rejectionHandled",e):nh(eI,e,r.value)})},Ii=function(r,e,t){return function(i){r(e,i,t)}},Ei=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=tI,sh(r,!0))},ao=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new Zp("Promise can't be resolved itself");var i=rh(e);i?so(function(){var a={done:!1};try{xi(i,e,Ii(ao,a,r),Ii(Ei,a,r))}catch(s){Ei(a,s,r)}}):(r.value=e,r.state=th,sh(r,!1))}catch(a){Ei({done:!1},a,r)}}};if(Xp&&(Wt=function(e){jT(this,Ya),UT(e),xi(Qa,this);var t=to(this);try{e(Ii(ao,t),Ii(Ei,t))}catch(i){Ei(t,i)}},Ya=Wt.prototype,Qa=function(e){JT(this,{type:Xa,done:!1,notified:!1,parent:!1,reactions:new QT,rejection:!1,state:Gp,value:void 0})},Qa.prototype=Hp(Ya,"then",function(e,t){var i=to(this),a=ro(GT(this,Wt));return i.parent=!0,a.ok=za(e)?e:!0,a.fail=za(t)&&t,a.domain=Ka?oo.domain:void 0,i.state===Gp?i.reactions.add(a):so(function(){ah(a,i)}),a.promise}),Wp=function(){var r=new Qa,e=to(r);this.promise=r,this.resolve=Ii(ao,e),this.reject=Ii(Ei,e)},Jp.f=ro=function(r){return r===Wt||r===iI?new Wp(r):XT(r)},!NT&&za(Ja)&&Ti!==Object.prototype)){Yp=Ti.then,KT||Hp(Ti,"then",function(e,t){var i=this;return new Wt(function(a,s){xi(Yp,i,a,s)}).then(e,t)},{unsafe:!0});try{delete Ti.constructor}catch{}jp&&jp(Ti,Ya)}_T({global:!0,constructor:!0,wrap:!0,forced:Xp},{Promise:Wt});FT(Wt,Xa,!1,!0);qT(Xa)});var ph=m((bk,dh)=>{"use strict";var sI=me(),ch=sI("iterator"),lh=!1;try{uh=0,co={next:function(){return{done:!!uh++}},return:function(){lh=!0}},co[ch]=function(){return this},Array.from(co,function(){throw 2})}catch{}var uh,co;dh.exports=function(r,e){try{if(!e&&!lh)return!1}catch{return!1}var t=!1;try{var i={};i[ch]=function(){return{next:function(){return{done:t=!0}}}},r(i)}catch{}return t}});var lo=m((gk,hh)=>{"use strict";var nI=Gt(),oI=ph(),uI=vi().CONSTRUCTOR;hh.exports=uI||!oI(function(r){nI.all(r).then(void 0,function(){})})});var fh=m(()=>{"use strict";var cI=Be(),lI=we(),dI=ft(),pI=yi(),hI=Wa(),fI=Fa(),mI=lo();cI({target:"Promise",stat:!0,forced:mI},{all:function(e){var t=this,i=pI.f(t),a=i.resolve,s=i.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),i.promise}})});var bh=m(()=>{"use strict";var bI=Be(),gI=ze(),SI=vi().CONSTRUCTOR,ho=Gt(),vI=ht(),yI=ie(),TI=bi(),mh=ho&&ho.prototype;bI({target:"Promise",proto:!0,forced:SI,real:!0},{catch:function(r){return this.then(void 0,r)}});!gI&&yI(ho)&&(po=vI("Promise").prototype.catch,mh.catch!==po&&TI(mh,"catch",po,{unsafe:!0}));var po});var gh=m(()=>{"use strict";var II=Be(),EI=we(),xI=ft(),PI=yi(),AI=Wa(),kI=Fa(),wI=lo();II({target:"Promise",stat:!0,forced:wI},{race:function(e){var t=this,i=PI.f(t),a=i.reject,s=AI(function(){var n=xI(t.resolve);kI(e,function(o){EI(n,t,o).then(i.resolve,a)})});return s.error&&a(s.value),i.promise}})});var Sh=m(()=>{"use strict";var RI=Be(),LI=yi(),$I=vi().CONSTRUCTOR;RI({target:"Promise",stat:!0,forced:$I},{reject:function(e){var t=LI.f(this),i=t.reject;return i(e),t.promise}})});var fo=m((Ak,vh)=>{"use strict";var MI=rt(),CI=Ce(),DI=yi();vh.exports=function(r,e){if(MI(r),CI(e)&&e.constructor===r)return e;var t=DI.f(r),i=t.resolve;return i(e),t.promise}});var Ih=m(()=>{"use strict";var BI=Be(),OI=ht(),yh=ze(),VI=Gt(),Th=vi().CONSTRUCTOR,_I=fo(),NI=OI("Promise"),FI=yh&&!Th;BI({target:"Promise",stat:!0,forced:yh||Th},{resolve:function(e){return _I(FI&&this===NI?VI:this,e)}})});var Eh=m(()=>{"use strict";oh();fh();bh();gh();Sh();Ih()});var kh=m(()=>{"use strict";var qI=Be(),UI=ze(),Za=Gt(),HI=ke(),Ph=ht(),Ah=ie(),jI=On(),xh=fo(),GI=bi(),bo=Za&&Za.prototype,WI=!!Za&&HI(function(){bo.finally.call({then:function(){}},function(){})});qI({target:"Promise",proto:!0,real:!0,forced:WI},{finally:function(r){var e=jI(this,Ph("Promise")),t=Ah(r);return this.then(t?function(i){return xh(e,r()).then(function(){return i})}:r,t?function(i){return xh(e,r()).then(function(){throw i})}:r)}});!UI&&Ah(Za)&&(mo=Ph("Promise").prototype.finally,bo.finally!==mo&&GI(bo,"finally",mo,{unsafe:!0}));var mo});var es=m((Ck,wh)=>{"use strict";var YI=ht();wh.exports=YI});var Lh=m((Dk,Rh)=>{"use strict";Od();Eh();kh();var QI=es();Rh.exports=QI("Promise","finally")});var Mh=m((Bk,$h)=>{"use strict";var zI=Lh();$h.exports=zI});var ts=m((Ok,Ch)=>{"use strict";var KI=Mh();Ch.exports=KI});var Hh=m(()=>{"use strict";var aE=Be(),sE=zi(),nE=$a(),oE=La(),uE=Cs();aE({target:"Array",proto:!0},{at:function(e){var t=sE(this),i=nE(t),a=oE(e),s=a>=0?a:i+a;return s<0||s>=i?void 0:t[s]}});uE("at")});var Gh=m((Dw,jh)=>{"use strict";Hh();var cE=es();jh.exports=cE("Array","at")});var Yh=m((Bw,Wh)=>{"use strict";var lE=Gh();Wh.exports=lE});var hr=m((Ow,Qh)=>{"use strict";var dE=Yh();Qh.exports=dE});var Lf=m(()=>{"use strict"});var $f=m(()=>{"use strict"});var Cf=m((xM,Mf)=>{"use strict";var GE=Ce(),WE=ui(),YE=me(),QE=YE("match");Mf.exports=function(r){var e;return GE(r)&&((e=r[QE])!==void 0?!!e:WE(r)==="RegExp")}});var Bf=m((PM,Df)=>{"use strict";var zE=tr(),KE=String;Df.exports=function(r){if(zE(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return KE(r)}});var Vf=m((AM,Of)=>{"use strict";var JE=rt();Of.exports=function(){var r=JE(this),e="";return r.hasIndices&&(e+="d"),r.global&&(e+="g"),r.ignoreCase&&(e+="i"),r.multiline&&(e+="m"),r.dotAll&&(e+="s"),r.unicode&&(e+="u"),r.unicodeSets&&(e+="v"),r.sticky&&(e+="y"),e}});var Ff=m((kM,Nf)=>{"use strict";var XE=we(),ZE=Ke(),ex=Gi(),tx=Vf(),_f=RegExp.prototype;Nf.exports=function(r){var e=r.flags;return e===void 0&&!("flags"in _f)&&!ZE(r,"flags")&&ex(_f,r)?XE(tx,r):e}});var Uf=m((wM,qf)=>{"use strict";var No=Se(),ix=zi(),rx=Math.floor,Vo=No("".charAt),ax=No("".replace),_o=No("".slice),sx=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,nx=/\$([$&'`]|\d{1,2})/g;qf.exports=function(r,e,t,i,a,s){var n=t+r.length,o=i.length,c=nx;return a!==void 0&&(a=ix(a),c=sx),ax(s,c,function(u,d){var l;switch(Vo(d,0)){case"$":return"$";case"&":return r;case"`":return _o(e,0,t);case"'":return _o(e,n);case"<":l=a[_o(d,1,-1)];break;default:var p=+d;if(p===0)return u;if(p>o){var f=rx(p/10);return f===0?u:f<=o?i[f-1]===void 0?Vo(d,1):i[f-1]+Vo(d,1):u}l=i[p-1]}return l===void 0?"":l})}});var Gf=m(()=>{"use strict";var ox=Be(),ux=we(),qo=Se(),Hf=Hi(),cx=ie(),lx=ci(),dx=Cf(),Di=Bf(),px=Yi(),hx=Ff(),fx=Uf(),mx=me(),bx=ze(),gx=mx("replace"),Sx=TypeError,Fo=qo("".indexOf),vx=qo("".replace),jf=qo("".slice),yx=Math.max;ox({target:"String",proto:!0},{replaceAll:function(e,t){var i=Hf(this),a,s,n,o,c,u,d,l,p,f,b=0,g="";if(!lx(e)){if(a=dx(e),a&&(s=Di(Hf(hx(e))),!~Fo(s,"g")))throw new Sx("`.replaceAll` does not allow non-global regexes");if(n=px(e,gx),n)return ux(n,e,i,t);if(bx&&a)return vx(Di(i),e,t)}for(o=Di(i),c=Di(e),u=cx(t),u||(t=Di(t)),d=c.length,l=yx(1,d),p=Fo(o,c);p!==-1;)f=u?Di(t(c,p,o)):fx(c,o,p,[],void 0,t),g+=jf(o,b,p)+f,b=p+d,p=p+l>o.length?-1:Fo(o,c,p+l);return b<o.length&&(g+=jf(o,b)),g}})});var Yf=m(($M,Wf)=>{"use strict";Lf();$f();Gf();var Tx=es();Wf.exports=Tx("String","replaceAll")});var zf=m((MM,Qf)=>{"use strict";var Ix=Yf();Qf.exports=Ix});var Jf=m((CM,Kf)=>{"use strict";var Ex=zf();Kf.exports=Ex});var Fx={};Fm(Fx,{ChromecastState:()=>qi,HttpConnectionType:()=>Sa,Observable:()=>ct.Observable,PlaybackState:()=>fe,Player:()=>la,SDK_VERSION:()=>Nx,Subject:()=>ct.Subject,Subscription:()=>ct.Subscription,Surface:()=>va,VERSION:()=>Ls,ValueSubject:()=>ct.ValueSubject,VideoFormat:()=>pt,VideoQuality:()=>ct.VideoQuality});module.exports=qm(Fx);var Ls="2.0.113-dev.85777574.0";var fe=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(fe||{}),pt=(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))(pt||{});var qi=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(qi||{}),Sa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(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 su=r=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});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 i=(0,F.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||su("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),i=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(i,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=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,F.assertNever)(a.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(i,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)([i.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=i.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,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Um=r=>{switch(r){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)(r)}};var vm=Ye($n(),1);var Vh=Ye(ts(),1);var go=require("@vkontakte/videoplayer-shared");var de=(r,e=0,t=0)=>{switch(t){case 0:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return r;let i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,go.assertNever)(t)}return r},So=(r,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:(0,go.assertNever)(e)}};var A=(r,e,t=!1)=>{let i=r.getTransition();(t||!i||i.to===e)&&r.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,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,at.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Dh=require("@vkontakte/videoplayer-shared"),Bh=r=>{switch(r){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,Dh.assertNever)(r)}};var R=require("@vkontakte/videoplayer-shared");var JI=5,XI=5,ZI=500,Oh=7e3,pr=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(),i=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: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(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)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Bh(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 i=(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(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(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(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,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),i=l,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];(0,R.assertNonNullable)(u),i=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),i=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),i=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),i=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??i,a);n.contentUrl=i,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 i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add((0,R.timeout)(Oh).subscribe(()=>s(`timeout(${Oh})`)))});(0,Vh.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},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 Io=require("@vkontakte/videoplayer-shared");var _h=require("@vkontakte/videoplayer-shared"),Nh=r=>{try{r.pause(),r.playbackRate=0,(0,_h.clearVideoElement)(r),r.remove()}catch(e){console.error(e)}};var is=require("@vkontakte/videoplayer-shared"),vo=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)}},yo=window.WeakMap?new WeakMap:new vo,To=window.WeakMap?new WeakMap:new Map,eE=(r,e=20)=>{let t=0;return(0,is.fromEvent)(r,"ratechange").subscribe(i=>{t++,t>=e&&(r.currentTime=r.currentTime,t=0)})},ve=(r,{audioVideoSyncRate:e})=>{let t=r.querySelector("video"),i=!!t;t?(0,Io.clearVideoElement)(t):(t=document.createElement("video"),r.appendChild(t)),yo.set(t,i);let a=new is.Subscription;return a.add(eE(t,e)),To.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ye=r=>{To.get(r)?.unsubscribe(),To.delete(r);let t=yo.get(r);yo.delete(r),t?(0,Io.clearVideoElement)(r):Nh(r)};var L=require("@vkontakte/videoplayer-shared");var $t=require("@vkontakte/videoplayer-shared"),rs=(r,e,t,{equal:i=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=r.getState(),o=e(),c=(0,$t.isNullable)(a),u=new $t.Subscription;return a&&u.add(a.subscribe(d=>{let l=r.getState();i(d,l)&&r.setState(d)},s)),i(o,n)||(t(n),c&&r.setState(n)),u.add(r.stateChangeStarted$.subscribe(d=>{t(d.to),c&&r.setState(d.to)},s)),u},st=(r,e,t)=>rs(e,()=>r.loop,i=>{(0,$t.isNonNullable)(i)&&(r.loop=i)},{onError:t}),Te=(r,e,t,i)=>rs(e,()=>({muted:r.muted,volume:r.volume}),a=>{(0,$t.isNonNullable)(a)&&(r.muted=a.muted,r.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:i}),Oe=(r,e,t,i)=>rs(e,()=>r.playbackRate,a=>{(0,$t.isNonNullable)(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),Mt=rs;var tE=r=>["__",r.language,r.label].join("|"),iE=(r,e)=>{if(r.id===e)return!0;let[t,i,a]=e.split("|");return r.language===i&&r.label===a},Eo=class r{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Mt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Mt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe((0,L.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,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,L.filterChanged)((i,a)=>i.length===a.length&&i.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,L.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,L.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(i=>{i.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))};i.track?.addEventListener("cuechange",a)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let a=i;(0,L.isNonNullable)(t.align)&&(a.align=t.align),(0,L.isNonNullable)(t.position)&&(a.position=t.position),(0,L.isNonNullable)(t.size)&&(a.size=t.size),(0,L.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(r.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=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:i,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:i,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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:a,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!iE(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,L.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,L.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ve=Eo;var gt=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 Fh=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},xo=r=>{let e=Fh(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},qh=r=>{let e=Fh(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};var $=require("@vkontakte/videoplayer-shared");var rE=3,Uh=(r,e,t=rE)=>{let i=0,a=0;for(let s=0;s<r.length;s++){let n=r.start(s),o=r.end(s);if(n<=e&&e<=o){if(i=n,a=o,!t)return{from:i,to:a};for(let c=s-1;c>=0;c--)r.end(c)+t>=i&&(i=r.start(c));for(let c=s+1;c<r.length;c++)r.start(c)-t<=a&&(a=r.end(c))}}return{from:i,to:a}};var Ie=r=>{let e=x=>(0,$.fromEvent)(r,x).pipe((0,$.mapTo)(void 0)),i=(0,$.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,$.fromEvent)(r,x))).pipe((0,$.map)(x=>x.type==="ended"?r.readyState<2:r.readyState<3),(0,$.filterChanged)()),a=(0,$.merge)((0,$.fromEvent)(r,"progress"),(0,$.fromEvent)(r,"timeupdate")).pipe((0,$.map)(()=>Uh(r.buffered,r.currentTime))),s=$.clientChecker.isSafari?(0,$.combine)({play:e("play").pipe((0,$.once)()),playing:e("playing")}).pipe((0,$.mapTo)(void 0)):e("playing"),n=(0,$.fromEvent)(r,"volumechange").pipe((0,$.map)(()=>({muted:r.muted,volume:r.volume}))),o=(0,$.fromEvent)(r,"ratechange").pipe((0,$.map)(()=>r.playbackRate)),c=(0,$.fromEvent)(r,"error").pipe((0,$.filter)(()=>!!(r.error||r.played.length)),(0,$.map)(()=>{let x=r.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:$.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:r.error??void 0}})),u=(0,$.fromEvent)(r,"timeupdate").pipe((0,$.map)(()=>r.currentTime)),d=new $.Subject,l=.3,p;u.subscribe(x=>{r.loop&&(0,$.isNonNullable)(p)&&(0,$.isNonNullable)(x)&&p>=r.duration-l&&x<=l&&d.next(p),p=x});let f=e("pause").pipe((0,$.filter)(()=>!r.error&&p!==r.duration)),b=(0,$.fromEvent)(r,"enterpictureinpicture"),g=(0,$.fromEvent)(r,"leavepictureinpicture"),y=new $.ValueSubject(qh(r));b.subscribe(()=>y.next(!0)),g.subscribe(()=>y.next(!1));let E=new $.ValueSubject(xo(r));return(0,$.fromEvent)(r,"fullscreenchange").pipe((0,$.map)(()=>xo(r))).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,$.fromEvent)(r,"durationchange").pipe((0,$.map)(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:y,inFullscreen$:E}};var St=require("@vkontakte/videoplayer-shared"),Ct=r=>{switch(r){case"mobile":return St.VideoQuality.Q_144P;case"lowest":return St.VideoQuality.Q_240P;case"low":return St.VideoQuality.Q_360P;case"sd":case"medium":return St.VideoQuality.Q_480P;case"hd":case"high":return St.VideoQuality.Q_720P;case"fullhd":case"full":return St.VideoQuality.Q_1080P;case"quadhd":case"quad":return St.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return St.VideoQuality.Q_2160P}};var Yt=Ye(hr(),1),O=require("@vkontakte/videoplayer-shared");var Po=!1,vt={},zh=r=>{Po=r},Kh=()=>{vt={}},Jh=r=>{r(vt)},fr=(r,e)=>{Po&&(vt.meta=vt.meta??{},vt.meta[r]=e)},be=class{constructor(e){this.name=e}next(e){if(!Po)return;vt.series=vt.series??{};let t=vt.series[this.name]??[];t.push([Date.now(),e]),vt.series[this.name]=t}};var pE=new be("best_bitrate"),Zh=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;var Ao=r=>(e,t)=>r*(Number(e.bitrate)-Number(t.bitrate)),mr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,O.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ef='Assertion "ABR Tracks is empty array" failed',as=(r,e,t,i)=>{let a=[...e].sort(Ao(1)),s=[...t].sort(Ao(1)),n=s.filter(c=>(0,O.isNonNullable)(c.bitrate)&&(0,O.isNonNullable)(r.bitrate)?r.bitrate/c.bitrate>i:!0),o=(0,Yt.default)(s,Math.round(s.length*a.indexOf(r)/(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)},Xh=r=>"quality"in r,tf=(r,e,t,i)=>{let a=t&&i&&i.history[t.id]&&(0,O.now)()-i.history[t.id]<=r.trackCooldown&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let s=i.last;i?.recordSwitch(s);let n=Xh(s)?"video":"audio",o=Xh(s)?s.quality:s.bitrate;return e({message:`
|
|
7
7
|
[last ${n} selected] ${o}
|
|
8
|
-
`}),s}return i?.recordSwitch(t),t},Dt=(r,{container:e,throughput:t,tuning:i,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:c,history:u,visible:d,droppedVideoMaxQualityLimit:l,abrLogger:
|
|
8
|
+
`}),s}return i?.recordSwitch(t),t},Dt=(r,{container:e,throughput:t,tuning:i,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:c,history:u,visible:d,droppedVideoMaxQualityLimit:l,abrLogger:p})=>{(0,O.assertNotEmptyArray)(r,ef);let f=i.usePixelRatio?window.devicePixelRatio??1:1,b=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*i.containerSizeFactor,height:e.height*f*i.containerSizeFactor},g=b&&(0,O.videoSizeToQuality)(b),y=i.considerPlaybackRate&&(0,O.isNonNullable)(o)?o:1,E=r.filter(D=>!(0,O.isInvariantQuality)(D.quality)).sort((D,B)=>(0,O.isHigher)(D.quality,B.quality)?-1:1),C=(0,Yt.default)(E,-1)?.quality,x=(0,Yt.default)(E,0)?.quality,I=(0,O.isNullable)(a)||(0,O.isNonNullable)(a.min)&&(0,O.isNonNullable)(a.max)&&(0,O.isLower)(a.max,a.min)||(0,O.isNonNullable)(a.min)&&x&&(0,O.isHigher)(a.min,x)||(0,O.isNonNullable)(a.max)&&C&&(0,O.isLower)(a.max,C),P=y*Zh(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},z=E.filter(D=>{if(!(g?(0,O.isLower)(D.quality,g):!0))return k[D.quality]="FitsContainer",!1;if(!((0,O.isNonNullable)(t)&&isFinite(t)&&(0,O.isNonNullable)(D.bitrate)?t-s>=D.bitrate*P:!0))return k[D.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,O.isNonNullable)(i.minBufferToSwitchUp)&&c&&!(0,O.isInvariantQuality)(c.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,O.isHigher)(D.quality,c.quality))return k[D.quality]="Buffer",!1;if(!!l&&(0,O.isHigherOrEqual)(D.quality,l))return k[D.quality]="DroppedFramesLimit",!1;let ge=I||((0,O.isNullable)(a.max)||(0,O.isLowerOrEqual)(D.quality,a.max))&&((0,O.isNullable)(a.min)||(0,O.isHigherOrEqual)(D.quality,a.min)),w=(0,O.isNonNullable)(d)&&!d?(0,O.isLowerOrEqual)(D.quality,i.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)]??r[0];return X.quality!==u?.last?.quality&&p({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
11
|
${r.map(D=>`{ id: ${D.id}, quality: ${D.quality}, bitrate: ${D.bitrate} }`).join(`
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
|
|
36
36
|
[best video track] ${z?.quality}
|
|
37
37
|
[selected video track] ${X?.quality}
|
|
38
|
-
`}),tf(i,
|
|
38
|
+
`}),tf(i,p,X,u)},rf=(r,e,t,{throughput:i,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:c})=>{(0,O.assertNotEmptyArray)(t,ef);let u=a.considerPlaybackRate&&(0,O.isNonNullable)(s)?s:1,d=[...t].sort(Ao(-1)),l=r.bitrate;(0,O.assertNonNullable)(l);let p=u*Zh(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f;return(0,O.isNonNullable)(i)&&isFinite(i)&&(f=d.find(b=>(0,O.isNonNullable)(b.bitrate)?i-l>=b.bitrate*p:!0)),f||(f=as(r,e,t,a.minVideoAudioRatio)),f?.bitrate!==o?.last?.bitrate&&c({message:`
|
|
39
39
|
[AUDIO TRACKS ABR]
|
|
40
40
|
[available audio tracks]
|
|
41
41
|
${t.map(b=>`{ id: ${b.id}, bitrate: ${b.bitrate} }`).join(`
|
|
@@ -51,11 +51,11 @@
|
|
|
51
51
|
playbackRate: ${s},
|
|
52
52
|
playbackRateFactor: ${u},
|
|
53
53
|
forwardBufferHealth: ${n},
|
|
54
|
-
bitrateFactor: ${
|
|
54
|
+
bitrateFactor: ${p},
|
|
55
55
|
minBufferToSwitchUp: ${a.minBufferToSwitchUp},
|
|
56
56
|
|
|
57
57
|
[selected audio track] ${f?.id}
|
|
58
|
-
`}),f&&tf(a,c,f,o)};var ue=r=>new URL(r).hostname;var V=require("@vkontakte/videoplayer-shared");var af=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))},Ee=async r=>{let e=r.muted;try{await r.play()}catch(t){if(!af(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(i){return af(i)&&(r.muted=!1,console.warn(i)),!1}}return!0};var Le=require("@vkontakte/videoplayer-shared");var nt=require("@vkontakte/videoplayer-shared");function ce(){return(0,nt.now)()}function ko(r){return ce()-r}function wo(r){let e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=n=>i.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 sf(r,e,t){let i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Pi(r,e,t,i){let a=window.XMLHttpRequest,s,n,o,c=!1,u=0,d,l,h=!1,f="arraybuffer",b=7e3,g=2e3,y=()=>{if(c)return;(0,nt.assertNonNullable)(d);let N=ko(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),I=()=>{if(!c){if(--u>=0){y(),i&&i();return}c=!0,l&&l(),t&&t()}},P=N=>(h=N,B),k=()=>{d=ce(),n=new a,n.open("get",r);let N=0,ee,Fe=0,be=()=>((0,nt.assertNonNullable)(d),Math.max(d,Math.max(ee||0,Fe||0)));if(s&&n.addEventListener("progress",w=>{let M=ce();s.updateChunk&&w.loaded>N&&(s.updateChunk(be(),w.loaded-N),N=w.loaded,ee=M)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),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 M=n.response.byteLength-N;M&&s.updateChunk&&s.updateChunk(be(),M)}n.responseType==="json"&&!Object.values(n.response).length?I():(l&&l(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),h){let w=()=>{(0,nt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Fe=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 br=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=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;i+=n;let c=s.bytes*n/o;a+=c,s.start=t,s.bytes-=c}}}if(a>0&&i>0){let s=a*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var gr=class{constructor(e,t,i,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=i,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 i=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()-i,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=Pi(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 i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,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}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=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,Ro=3;var hE=6e4,fE=10,mE=1,bE=500,Sr=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 br(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=wo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){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=wo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,i,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):(!i||i.bitrate>s.bitrate)&&(i=s));return a||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Le.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("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=()=>{sf(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 gr(Ro,ss,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:a}=this.params,s=!1,n=null,o=null,c=null,u=null,d=!1,l=()=>{let I=s&&(!d||d===this.rep);return I||t("Not running!"),I},h=(I,P,k)=>{c&&c.abort(),c=Pi(this.urlResolver.resolve(I,!1),P,k,()=>this._retryCallback()).withTimeout(ss).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ro).withFinally(()=>{c=null}).send()},f=(I,P,k)=>{(0,Le.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),P,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=I=>{let P=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${P}=>${I}`),i.playbackRate=I)},g=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let I=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];I=Math.min(I,D.buf),D.ts<k&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${I} drop=${Y} jitter=${this.sourceJitter}`);let z=I-mE;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=I=>{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,M)=>({chunkIdx:X(w),startTS:Y(w),dur:z(w),discontinuity:M}),B=()=>{let w=0;if(P&&P.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,se=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,le=M;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 M=k();if(!(M<=0)){if((0,Le.isNonNullable)(w)){for(let se=0;se<M;se++)if(Y(se)>w)return D(se)}return B()}},ee=w=>{let M=k(),se=w?w.chunkIdx+1:0,le=se-P.fragIndex;if(!(M<=0)){if(!w||le<0||le-M>fE)return t(`Resync: offset=${le} bChunks=${M} chunk=`+JSON.stringify(w)),B();if(!(le>=M))return D(se-P.fragIndex,!1)}},Fe=(w,M,se)=>{u&&u.abort(),u=Pi(this.urlResolver.resolve(w,!0,this.lowLatency),M,se,()=>this._retryCallback()).withTimeout(ss).withRetryCount(Ro).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(w,M)=>{Fe(I,se=>{if(!l())return;P=se;let le=!!P.lowLatency;le!==this.lowLatency&&g(le);let Ae=0;for(let Xe=0;Xe<P.dur.length;++Xe)Ae+=P.dur[Xe];Ae>0&&((0,Le.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(M))},()=>this._handleNetworkError())},nextChunk:ee}},C=()=>{s=!1,o&&o.abort(),c&&c.abort(),u&&u.abort(),(0,Le.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:P,logger:k}=this.params,Y=E(e.jidxUrl),z,X,D,B,N=0,ee,Fe,be,w=()=>{ee&&(clearTimeout(ee),ee=void 0);let Q=Math.max(bE,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=N+Q,ge=ce(),oe=Math.min(1e4,ne-ge);N=ge;let qe=()=>{u||l()&&Y.seek(()=>{l()&&(N=ce(),M(),w())})};oe>0?ee=window.setTimeout(()=>{this.paused?w():qe()},oe):qe()},M=()=>{let Q;for(;Q=Y.nextChunk(B);)B=Q,ri(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}Xe(ne)}else w()},se=(Q,ne)=>{if(!l()||!this.sourceBuffer)return;let ge,oe,qe,kt=Ze=>{window.setTimeout(()=>{l()&&se(Q,ne)},Ze)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),kt(100);else{let Ze=ce(),Ue=P.currentTime;!this.paused&&P.buffered.length>1&&Fe===Ue&&Ze-be>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),Fe!==Ue&&(Fe=Ue,be=Ze);let Vt=this._getBufferSizeSec();if(Vt>30)k(`Buffered ${Vt} seconds; delaying appendBuffer`),kt(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:Ze,buf:Vt}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(lt){if(lt.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),qe=this.sourceBuffer.buffered.length,qe!==0&&(ge=this.sourceBuffer.buffered.start(0),oe=Ue,oe-ge>4&&this.sourceBuffer.remove(ge,oe-3)),kt(1e3);else throw lt}}},le=()=>{X&&z&&(k([`Appending chunk, sz=${X.byteLength}:`,JSON.stringify(D)]),se(X,function(){X=null,M()}))},Ae=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),Xe=Q=>{l()&&f(Ae(Q),(ne,ge)=>{if(l()){if(ge/=1e3,X=ne,D=Q,n=Q.startTS,ge){let oe=Math.min(10,Q.dur/ge);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*oe:oe}le()}},()=>this._handleNetworkError())},ri=Q=>{l()&&((0,Le.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ae(Q),!1)))},Ot=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,Le.isNullable)(I)||Q.startTS>I?Xe(Q):(D=Q,M())}},I),e.cachedHeader?Ot(e.cachedHeader):h(e.headerUrl,Ot,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,Le.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,Le.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Le.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let h,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}h=this._selectQuality(l),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${l}`)},s={updateChunk:(h,f)=>{let b=ce();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,c=!0,u=()=>{let l=s.get();if(l&&o&&this.autoQuality){if(c&&l>o&&ko(n)<3e4)return;i(l)}c=this.autoQuality};return{updateChunk:(l,h)=>{let f=s.updateChunk(l,h);return f&&u(),f},notifySwitch:l=>{let h=ce();l<o&&(n=h),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=Pi(this.urlResolver.resolve(e,!0),t,i,()=>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:i,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):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},hE))}_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(),i=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(i-a)/i;!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)),i=(0,te.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[a])=>(0,te.isLower)(i,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"),nf=require("@vkontakte/videoplayer-shared");var vr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var gE=(r,e)=>new os.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(c=>t.next(c.isIntersecting||vr()))},{...i,...e});a.observe(r);let s=(0,nf.fromEvent)(document,"visibilitychange").pipe((0,os.map)(n=>!document.hidden||vr())).subscribe(n=>t.next(n));return()=>{a.unobserve(r),s.unsubscribe}}),Ve=gE;var SE=["paused","playing","ready"],vE=["paused","playing","ready"],yr=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new H("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new st;this.droppedFramesManager=new ns;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new gt;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,i=[];for(let a of t){let s=a.name??a.index.toString(10),n=Ct(a.name)??(0,V.videoSizeToQuality)(a.video),o=a.bitrate/1e3,c={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:c};i.push({track:u,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=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)(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(vE.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&SE.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(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let c=a?.from;c&&c==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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,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=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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ie(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$:i.playing$,pause$:i.pause$,tracks:a}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((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:i.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(at(this.video,this.params.desiredState.isLooped,t)).add(Te(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Oe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ve(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),ye(this.video)}createLiveDashPlayer(){let e=new Sr({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(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&(0,V.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(i),n||c||s!==o){let u=e.find(({track:d})=>d.id===s)?.representation;(0,V.assertNonNullable)(u,"Representations missing"),this.dash.startPlay(u,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.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(),i=this.videoState.getState(),a=t==="paused"&&i==="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 of=yr;var ot=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){let a=r.start(i)*1e3,s=r.end(i)*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,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let a=0,s=i.length;a<s;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let a=0,s=i.length;a<s;a++){let n=i[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}},Ai=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)}},Tr=class{constructor(){Object.defineProperty(this,"signal",{value:new Ai,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 i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Tr.prototype[Symbol.toStringTag]="AbortController",Ai.prototype[Symbol.toStringTag]="AbortSignal");function cs(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function $o(r){typeof r=="function"&&(r={fetch:r});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!cs({fetch:e,Request:t,AbortController:i,__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 h=new t(u,d);return l&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),h},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 h=new Promise((f,b)=>{d.addEventListener("abort",()=>b(l),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([h,n(c,u)])}return n(c,u)},Request:s}}var Ir=cs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),uf=Ir?$o({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,yt=Ir?uf.fetch:window.fetch,KR=Ir?uf.Request:window.Request,Tt=Ir?Tr:window.AbortController,JR=Ir?Ai:window.AbortSignal;var df=Ge(hr(),1);var It=()=>window.ManagedMediaSource||window.MediaSource,ls=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),cf=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),lf=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ut=require("@vkontakte/videoplayer-shared"),ps=document.createElement("video"),IE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',EE='video/mp4; codecs="hev1.1.6.L93.B0"',pf='video/webm; codecs="vp09.00.10.08"',hf='video/webm; codecs="av01.0.00M.08"',xE='audio/mp4; codecs="mp4a.40.2"',PE='audio/webm; codecs="opus"',Qt={mms:ls(),mse:cf(),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?.(IE),h265:!!It()?.isTypeSupported?.(EE),vp9:!!It()?.isTypeSupported?.(pf),av1:!!It()?.isTypeSupported?.(hf),aac:!!It()?.isTypeSupported?.(xE),opus:!!It()?.isTypeSupported?.(PE)},ki=(Pe.h264||Pe.h265)&&Pe.aac,zt,AE=async()=>{if(!window.navigator.mediaCapabilities)return;let r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:hf}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:pf}})]);zt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{AE()}catch(r){console.error(r)}var wi=Qt.hls&&xe.mp4,ff=()=>Object.keys(Pe).filter(r=>Pe[r]),mf=(r,e=!1,t=!1)=>{let i=Qt.mse||Qt.mms&&t;return r.filter(a=>{switch(a){case"DASH_SEP":return i&&xe.mp4&&ki;case"DASH_WEBM":return i&&xe.webm&&Pe.vp9&&Pe.opus;case"DASH_WEBM_AV1":return i&&xe.webm&&Pe.av1&&Pe.opus;case"DASH_STREAMS":return i&&(xe.mp4&&ki||xe.webm&&(Pe.vp9||Pe.av1)&&(Pe.opus||Pe.aac));case"DASH_LIVE":return Qt.mse&&xe.mp4&&ki;case"DASH_LIVE_CMAF":return i&&xe.mp4&&ki&&xe.cmaf;case"DASH_ONDEMAND":return i&&xe.mp4&&ki;case"HLS":case"HLS_ONDEMAND":return wi||e&&Qt.mse&&xe.mp4&&ki;case"HLS_LIVE":case"HLS_LIVE_CMAF":return wi;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,ut.assertNever)(a)}})},ds=r=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(r){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,ut.assertNever)(r)}return[e,t]},bf=({webmCodec:r,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...ds(r),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ut.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...ds(r),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ds(r),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ds(r),...a,"HLS","HLS_ONDEMAND"];default:(0,ut.assertNever)(e)}return wi?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},gf=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...a],n=[...a,...i],o,c=ut.clientChecker.isMac&&ut.clientChecker.isSafari;if(ut.clientChecker.isAndroid)switch(r){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,ut.assertNever)(r)}else wi&&!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"]},Mo=r=>r?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Sf=r=>{if(r.size!==0){if(r.size===1)return r.values().next().value.split(".").at(0);for(let e of r){let t=(0,df.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return r.values().next().value.split(".").at(0)}};var Ri=require("@vkontakte/videoplayer-shared"),vf=r=>{if(!r)return{id:"EmptyResponse",category:Ri.ErrorCategory.PARSER,message:"Empty response"};if(r.length<=2&&r.match(/^\d+$/))return{id:`UVError#${r}`,category:Ri.ErrorCategory.NETWORK,message:`UV Error ${r}`};let e=r.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ri.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(r,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ri.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ri.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Li=(r,e)=>{for(let t=0;t<r.length;t++)if(r.start(t)*1e3<=e&&r.end(t)*1e3>e)return!0;return!1};var S=require("@vkontakte/videoplayer-shared");var Oi=Ge(hr(),1);var kE=(r,e={})=>{let i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},wE=r=>window.clearTimeout(r),yf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Co=yf?kE:window.requestIdleCallback,cL=yf?wE:window.cancelIdleCallback;var sm=Ge(ts(),1);var _e=require("@vkontakte/videoplayer-shared"),RE=16,Tf=!1;try{Tf=_e.clientChecker.isSafari&&!!_e.clientChecker.macVersion&&_e.clientChecker.macVersion<=RE}catch(r){console.error(r)}var Do=class{constructor(e){this.bufferFull$=new _e.Subject;this.error$=new _e.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:_e.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(i=>{let a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i;Tf&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)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:_e.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,_e.assertNever)(t)}}},If=Do;var Bo=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};var T=require("@vkontakte/videoplayer-shared");var K=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i: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 $i=class extends K{};var Er=class extends K{};var xr=class extends K{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let a=this.readString(4);this.compatibleBrands.push(a),i-=4}}};var Pr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ar=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var kr=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 i=this.readUint32();this.version=i>>>24,this.flags=i&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 i=0;i<this.referenceCount;i++){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 wr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Rr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Lr=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 $r=class extends ae{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Mr=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 Cr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Dr=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 Br=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Or=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vr=class extends ae{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var _r=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Nr=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 Fr=class extends ae{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var qr=class extends ae{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let 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 $E={ftyp:xr,moov:Pr,moof:Ar,mdat:kr,sidx:Kt,trak:wr,mdia:Cr,mfhd:Vr,tkhd:Dr,traf:_r,tfhd:Nr,tfdt:Fr,trun:qr,minf:Br,sv3d:Rr,st3d:Lr,prhd:$r,proj:Or,equi:Mr,uuid:Er,unknown:$i},Jt=class r{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=$E[e];return i?new i(t,new r):new $i(t,new r)}};var Mi=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 CE=new TextDecoder("ascii"),DE=r=>CE.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",BE=r=>{let e=new Kt(r,new Jt),t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},OE=(r,e)=>{let i=new Jt().parse(r),a=new Mi(i),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(r.buffer,u,l)},VE=(r,e)=>{let i=new Jt().parse(r),s=new Mi(i).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,h)=>l+h,0):u=n.defaultSampleDuration*c.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},_E=r=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Jt().parse(r),a=new Mi(i);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},Ef={validateData:DE,parseInit:_E,getIndexRange:()=>{},parseSegments:BE,parseFeedableSegmentChunk:OE,getSegmentEndTime:VE};var Et=require("@vkontakte/videoplayer-shared");var Pf=require("@vkontakte/videoplayer-shared");var xf={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"}},Af=r=>{let e=r.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ur(r,t),a=i in xf,s=a?xf[i].type:"binary",n=r.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(r.buffer,r.byteOffset+t+1,o-1),u=n&255>>o,d=Ur(c),l=u*2**((o-1)*8)+d,h=t+o,f;return h+l>r.byteLength?f=new DataView(r.buffer,r.byteOffset+h):f=new DataView(r.buffer,r.byteOffset+h,l),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+l,value:f,valueSize:l}},Ur=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{let t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ke=(r,e)=>{switch(e){case"int":return r.getInt8(0);case"uint":return Ur(r);case"float":return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case"string":return new TextDecoder("ascii").decode(r);case"utf8":return new TextDecoder("utf-8").decode(r);case"date":return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case"master":return r;case"binary":return r;default:(0,Pf.assertNever)(e)}},Xt=(r,e)=>{let t=0;for(;t<r.byteLength;){let i=new DataView(r.buffer,r.byteOffset+t),a=Af(i);if(!e(a))return;a.type==="master"&&Xt(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},kf=r=>{if(r.getUint32(0)!==440786851)return!1;let e,t,i,a=Af(r);return Xt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Ke(o,n):s===17026?t=Ke(o,n):s===17029&&(i=Ke(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var wf=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],NE=[231,22612,22743,167,171,163,160,175],FE=r=>{let e,t,i,a,s=!1,n=!1,o=!1,c,u,d=!1,l=0;return Xt(r,({tag:h,type:f,value:b,valueSize:g})=>{if(h===21419){let y=Ke(b,f);u=Ur(y)}else h!==21420&&(u=void 0);return h===408125543?(e=b.byteOffset,t=b.byteOffset+g):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=Ke(b,f):h===17545?a=Ke(b,f):h===21420&&u===475249515?c=Ke(b,f):h===374648427?Xt(b,({tag:y,type:E,value:C})=>y===30321?(d=Ke(C,E)===1,!1):!0):s&&n&&wf.includes(h)&&(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"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*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}}}},qE=r=>{if((0,Et.isNullable)(r.cuesSeekPosition))return;let e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},UE=(r,e)=>{let t=!1,i=!1,a=o=>(0,Et.isNonNullable)(o.time)&&(0,Et.isNonNullable)(o.position),s=[],n;return Xt(r,({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=Ke(u,c));break;case 183:break;case 241:n&&(n.position=Ke(u,c));break;default:t&&wf.includes(o)&&(i=!0)}return!(t&&i)}),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}}})},HE=r=>{let e=0,t=!1;try{Xt(r,i=>i.tag===524531317?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):NE.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Rf={validateData:kf,parseInit:FE,getIndexRange:qE,parseSegments:UE,parseFeedableSegmentChunk:HE};var Ci=r=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(r);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Rf;case"mp4":return Ef}}throw new ReferenceError(`Unsupported mime type ${r}`)};var Ho=Ge(Jf(),1);var Uo=r=>{let e=r.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=i;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=i[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 Bi=require("@vkontakte/videoplayer-shared");var Xf=r=>{if(r.includes("/")){let e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};var Zf=r=>{if(!r.startsWith("P"))return;let e=(n,o)=>{let c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),a=i?.[1]==="-"?-1:1,s={days:e(i?.[5],a),hours:e(i?.[6],a),minutes:e(i?.[7],a),seconds:e(i?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},xt=(r,e)=>{let t=r;t=(0,Ho.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(i)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ho.default)(t,n,(o,c)=>(0,Bi.isNullable)(s)?o:(0,Bi.isNullable)(c)?s:s.padStart(parseInt(c,10),"0"))}return t},em=(r,e)=>{let i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},s=i.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,h,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),y=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)h=Zf(f);else if(b){let I=Zf(b);(0,Bi.isNonNullable)(I)&&(h=I)}else y&&(h=parseInt(y,10));let E=0,C=s.getAttribute("profiles")?.split(",")??[];for(let I of c){let P=I.getAttribute("id")??"id"+(E++).toString(10),k=I.getAttribute("mimeType")??"",Y=I.getAttribute("codecs")??"",z=I.getAttribute("contentType")??k?.split("/")[0],X=I.getAttribute("profiles")?.split(",")??[],D=I.getAttribute("lang")??void 0,B=I.querySelector("Label")?.textContent?.trim()??void 0,N=I.querySelectorAll("Representation"),ee=I.querySelector("SegmentTemplate"),Fe=I.querySelector("Role")?.getAttribute("value")??void 0,be=z,w={id:P,language:D,isDefault:Fe==="main",label:B,codecs:Y,hdr:be==="video"&&Uo(Y),mime:k,representations:[]};for(let M of N){let se=M.getAttribute("lang")??void 0,le=M.getAttribute("label")??void 0,Ae=M.querySelector("BaseURL")?.textContent?.trim()??"",Xe=new URL(Ae||o,e).toString(),ri=M.getAttribute("mimeType")??k,Ot=M.getAttribute("codecs")??Y??"",Q;if(z==="text"){let ne=M.getAttribute("id")||"",ge=ne.includes("_auto"),oe=M.querySelector("SegmentTemplate");if(!oe)continue;let qe={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},kt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,Ze=parseInt(oe.getAttribute("startNumber")??"",10)??1,Ue=parseInt(oe.getAttribute("timescale")??"",10),Vt=oe.querySelectorAll("SegmentTimeline S")??[],lt=oe.getAttribute("media");if(!lt)continue;let da=[],pa=0,ha="",ai=0,_i=Ze,pe=0;for(let He of Vt){let _t=parseInt(He.getAttribute("d")??"",10),Me=parseInt(He.getAttribute("r")??"",10)||0,wt=parseInt(He.getAttribute("t")??"",10);pe=Number.isFinite(wt)?wt:pe;let Nt=_t/Ue*1e3,si=pe/Ue*1e3;for(let et=0;et<Me+1;et++){let Rt=xt(lt,{...qe,segmentNumber:_i.toString(10),segmentTime:(pe+et*_t).toString(10)}),ni=(si??0)+et*Nt,Fi=ni+Nt;_i++,da.push({time:{from:ni,to:Fi},url:Rt})}pe+=(Me+1)*_t,pa+=(Me+1)*Nt}ai=pe/Ue*1e3,ha=xt(lt,{...qe,segmentNumber:_i.toString(10),segmentTime:pe.toString(10)});let Ni={time:{from:ai,to:1/0},url:ha},dt={type:"template",baseUrl:Xe,segmentTemplateUrl:lt,initUrl:"",totalSegmentsDurationMs:pa,segments:da,nextSegmentBeyondManifest:Ni,timescale:Ue};Q={id:ne,kind:"text",segmentReference:dt,profiles:[],duration:h,bitrate:kt,mime:"",codecs:"",width:0,height:0,isAuto:ge}}else{let ne=M.getAttribute("contentType")??ri?.split("/")[0]??z,ge=I.getAttribute("profiles")?.split(",")??[],oe=parseInt(M.getAttribute("width")??"",10),qe=parseInt(M.getAttribute("height")??"",10),kt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,Ze=M.getAttribute("frameRate")??"",Ue=M.getAttribute("quality")??void 0,Vt=Ze?Xf(Ze):void 0,lt=M.getAttribute("id")??"id"+(E++).toString(10),da=ne==="video"?`${qe}p`:ne==="audio"?`${kt}Kbps`:Ot,pa=`${lt}@${da}`,ha=[...C,...X,...ge],ai,_i=M.querySelector("SegmentBase"),pe=M.querySelector("SegmentTemplate")??ee;if(_i){let dt=M.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[He,_t]=dt.split("-").map(Rt=>parseInt(Rt,10)),Me={from:He,to:_t},wt=M.querySelector("SegmentBase")?.getAttribute("indexRange"),[Nt,si]=wt?wt.split("-").map(Rt=>parseInt(Rt,10)):[],et=wt?{from:Nt,to:si}:void 0;ai={type:"byteRange",url:Xe,initRange:Me,indexRange:et}}else if(pe){let dt={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},He=parseInt(pe.getAttribute("timescale")??"",10),_t=pe.getAttribute("initialization")??"",Me=pe.getAttribute("media"),wt=parseInt(pe.getAttribute("startNumber")??"",10)??1,Nt=xt(_t,dt);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let si=pe.querySelectorAll("SegmentTimeline S")??[],et=[],Rt=0,ni="",Fi=0;if(si.length){let fa=wt,je=0;for(let oi of si){let tt=parseInt(oi.getAttribute("d")??"",10),Ft=parseInt(oi.getAttribute("r")??"",10)||0,ma=parseInt(oi.getAttribute("t")??"",10);je=Number.isFinite(ma)?ma:je;let Rs=tt/He*1e3,$m=je/He*1e3;for(let ba=0;ba<Ft+1;ba++){let Mm=xt(Me,{...dt,segmentNumber:fa.toString(10),segmentTime:(je+ba*tt).toString(10)}),ru=($m??0)+ba*Rs,Cm=ru+Rs;fa++,et.push({time:{from:ru,to:Cm},url:Mm})}je+=(Ft+1)*tt,Rt+=(Ft+1)*Rs}Fi=je/He*1e3,ni=xt(Me,{...dt,segmentNumber:fa.toString(10),segmentTime:je.toString(10)})}else if((0,Bi.isNonNullable)(h)){let je=parseInt(pe.getAttribute("duration")??"",10)/He*1e3,oi=Math.ceil(h/je),tt=0;for(let Ft=1;Ft<oi;Ft++){let ma=xt(Me,{...dt,segmentNumber:Ft.toString(10),segmentTime:tt.toString(10)});et.push({time:{from:tt,to:tt+je},url:ma}),tt+=je}Fi=tt,ni=xt(Me,{...dt,segmentNumber:oi.toString(10),segmentTime:tt.toString(10)})}let Lm={time:{from:Fi,to:1/0},url:ni};ai={type:"template",baseUrl:Xe,segmentTemplateUrl:Me,initUrl:Nt,totalSegmentsDurationMs:Rt,segments:et,nextSegmentBeyondManifest:Lm,timescale:He}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ne||!ri)continue;let Ni={video:"video",audio:"audio",text:"text"}[ne];if(!Ni)continue;be||=Ni,Q={id:pa,kind:Ni,segmentReference:ai,profiles:ha,duration:h,bitrate:kt,mime:ri,codecs:Ot,width:oe,height:qe,fps:Vt,quality:Ue}}w.language||=se,w.label||=le,w.mime||=ri,w.codecs||=Ot,w.hdr||=be==="video"&&Uo(Ot),w.representations.push(Q)}be&&a[be].push(w)}return{dynamic:u,liveAvailabilityStartTime:l,duration:h,streams:a}};var Hr=Ge(hr(),1);var tm=require("@vkontakte/videoplayer-shared"),im=({id:r,width:e,height:t,bitrate:i,fps:a,quality:s})=>{let n=(s?Ct(s):void 0)??(0,tm.videoSizeToQuality)({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:a}},rm=({id:r,bitrate:e})=>({id:r,bitrate:e}),hs=(r,e,t)=>{let i=e.indexOf(r);return(0,Hr.default)(t,Math.round(t.length*i/e.length))??(0,Hr.default)(t,-1)},am=({language:r,label:e,id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),Wo=({id:r,language:e,label:t,codecs:i,isDefault:a})=>({id:r,language:e,label:t,codec:(0,Hr.default)(i.split("."),0),isDefault:a}),Yo=({id:r,language:e,label:t,hdr:i,codecs:a})=>({id:r,language:e,hdr:i,label:t,codec:(0,Hr.default)(a.split("."),0)}),fs=r=>"url"in r,Ne=r=>r.type==="template",jr=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);var Gr=class{constructor(e,t,i,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:c=!1,manifest:u}){this.currentSegmentLength$=new T.ValueSubject(0);this.onLastSegment$=new T.ValueSubject(!1);this.fullyBuffered$=new T.ValueSubject(!1);this.playingRepresentation$=new T.ValueSubject(void 0);this.playingRepresentationInit$=new T.ValueSubject(void 0);this.error$=new T.Subject;this.gaps=[];this.subscription=new T.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.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,T.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 If(this.sourceBuffer),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,c=this.mediaSource.readyState;c!=="open"&&(o={id:`SegmentEjection_source_${c}`,category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:T.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,Bo(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=c,this.tuning.useNewPruneBufferStrategy){let u=ot(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 i=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,T.assertNonNullable)(i,"No init buffer for starting representation"),(0,T.assertNonNullable)(a,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,T.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,T.assertNonNullable)(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,T.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,T.isNonNullable)(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,T.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(h=>h.id===c);u&&this.representations.set(c,u);let d=this.representations.get(c);if(!d||!Ne(d.segmentReference))return;let l=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(i);(0,T.assertNonNullable)(a);let s=this.segments.get(i);(0,T.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,T.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(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}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,T.isNullable)(e)||(0,T.isNullable)(this.downloadingRepresentationId)||(0,T.isNullable)(this.playingRepresentationId)||(0,T.isNullable)(this.sourceBuffer)||!(0,T.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,T.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let a=i.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=ot(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)&&Bo(this.sourceBuffer.buffered)>=this.bufferLimit){let u=ot(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(i,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,Oi.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&&ot(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Oi.default)(i,-1);c&&c.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===c))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+a}),i=s.time.to;(0,T.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[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 i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Ne(i.segmentReference))return;let a=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=this.segments.get(i.id)??[],n=(0,Oi.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(i.segmentReference);this.segments.set(i.id,c)}else{let c=a.slice(o+1);this.segments.set(i.id,[...s,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,T.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}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 i=t.segmentReference;if(!Ne(i))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*i.timescale/1e3).toString(10),c=xt(i.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 i=this.segments.get(t);return i?i.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,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let a=e.findIndex(({status:l,time:{from:h,to:f}},b)=>{let g=h<=i&&f>=i,y=h>i||g||b===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&h<=i+E||f<=i+E;return(l==="none"||l==="partially_ejected"&&y&&C&&this.sourceBuffer&&!(Li(this.sourceBuffer.buffered,h)&&Li(this.sourceBuffer.buffered,f)))&&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 h=s[l];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")c.push(h);else break}return c}async loadSegments(e,t,i="auto"){Ne(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let 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,T.abortable)(o,async function*(){let d=(0,T.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:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,T.now)(),!d)return;let l=new DataView(d);if(!isFinite(a.segment.time.to)){let h=t.segmentReference.timescale,f=Ci(t.mime);a.segment.time.to=f.getSegmentEndTime(l,h)}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]),jr(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="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,T.abortable)(n,async function*(){let c=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,c),(0,T.fromEvent)(window,"online").pipe((0,T.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:i}),this.lastDataObtainedTimestampMs=(0,T.now)(),this.failedDownloads=0}catch(c){this.abortActiveSegments(e),jr(c)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Ne(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,a={from:(0,Oi.default)(e,0).byte.from,to:(0,Oi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:a,signal:s,onProgress:(o,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)(),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:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ne(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let a=i.toString(),{signal:s}=this.downloadAbortController,n=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)();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:T.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:i,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=i,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Ci(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:i,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:i,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,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,h=c==="byteRange",f=h?l.byte.to-l.byte.from+1:u;if(d.representationId!==t||!(!h||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(s.aborted){n();continue}let g=h?l.byte.from-i:0,y=h?l.byte.to-i: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),I=this.getCurrentPosition();(0,T.isNonNullable)(I)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-I,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,T.isNullable)(I))&&(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),I=d.loadedBytes===f?x:Ci(o.mime).parseFeedableSegmentChunk(x);I?.byteLength&&(l.status="partially_fed",d.feedingBytes+=I.byteLength,this.sourceBufferTaskQueue.append(I,s).then(P=>{if(s.aborted)n();else if(P)d.fedBytes+=I.byteLength,d.fedBytes===f&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<f)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,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-i,l=u.byte.to-i,h=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,h);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(h,a-d),c.loadedBytes>c.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===h?g:Ci(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===h&&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",fs(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let a of this.segments.get(i.id)??[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");(0,T.assertNonNullable)(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[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 i=this.representations.get(e);i&&(this.initLoadIdleCallback=Co(()=>(0,sm.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,T.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ci(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 h=d;this.isLive&&Ne(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:T.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,T.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:h}=c[d],f=u[u.length-1];f.to>=l?f.to=Math.max(f.to,h):u.push(c[d])}return u},o=c=>{if(s>=t)return a;a.push({...c.time}),a=n(a);let u=fs(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 h of this.segments.values())for(let f of h)["none","partially_ejected"].includes(f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let h={time:{from:u,to:d},url:"",status:"none"};o(h)}}if(a.length&&i){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,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,T.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=fs(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 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(l)){s=d,n=l;break}}if(o=isFinite(s)&&isFinite(n),!o&&i){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)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,T.isNullable)(e)?0:ot(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let a={representation:e,from:i.time.from,to:i.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<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){a=void 0;break}o>i.time.from&&o<i.time.to&&(a.from=o),n<i.time.to&&n>i.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){if(!this.gapDetectionIdleCallback){(0,T.assertNonNullable)(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Co(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:T.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,T.isNullable)(this.sourceBuffer)||(0,T.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let a=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:s})}let t=100;for(let i of this.segments.values())for(let a of i){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&&n<d.to-t||o>d.from+t&&o<=d.to);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 Wr=r=>{let e=new URL(r);return e.searchParams.set("quic","1"),e.toString()};var nm=r=>{let e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:a}};var G=require("@vkontakte/videoplayer-shared");var ms=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,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"),i=e;this.requestQuic&&(i=Wr(i));let a=yield yt(i,{signal:this.abortAllController.signal}).catch(Yr);return a?(t.log("success",(0,G.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",(0,G.flattenObject)({url:i,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:i,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(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let B=new URL(u,location.href);B.searchParams.append("bytes",`${i.from}-${i.to}`),u=B.toString();break}default:(0,G.assertNever)(t)}this.requestQuic&&(u=Wr(u));let h=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){Yr(N)}}),this.abortAllController.signal.aborted||n.aborted)try{B.abort()}catch(N){Yr(N)}h=B.signal}let b=(0,G.now)();l.log("startRequest",(0,G.flattenObject)({url:u,priority:s,rangeMethod:t,range:i,isLowLatency:c,requestStartedAt:b}));let g=yield yt(u,{priority:s,headers:d,signal:h}).catch(Yr),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 I=0,P=new Uint8Array(0),k=!1,Y=B=>{f?.unsubscribe(),k=!0,Yr(B)},z=(0,G.abortable)(h,async function*({done:B,value:N}){if(I===0&&this.lastRequestFirstBytes$.next((0,G.now)()-b),h.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,I+=N.byteLength,a?.(new DataView(P.buffer),I),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,i){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:i,measureThroughput:!1});if(!l)return null;let h=new DataView(l,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 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:i,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 i=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(i,{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=i.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:i}=nm(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,G.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Yr=r=>{if(!jr(r))throw r};var Zt=(r,e,t)=>t*e+(1-t)*r,Qo=(r,e)=>r.reduce((t,i)=>t+i,0)/e,om=(r,e,t,i)=>{let a=0,s=t,n=Qo(r,e),o=e<i?e:i;for(let c=0;c<o;c++)r[s]>n?a++:a--,s=(r.length+s-1)%r.length;return Math.abs(a)===o};var Qr=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 Qr.ValueSubject(e.initial),this.debounced$=new Qr.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new me(`raw_${t}`),this.smoothedSeries$=new me(`smoothed_${t}`),this.reportedSeries$=new me(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let 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,Qr.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 bs=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 gs=class extends Bt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Qo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Zt(this.emaSmoothed,e,this.params.emaAlpha);let i=om(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ss=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 ei=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new bs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new gs({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Ss({initial:e,label:"liveEdgeDelay",...t})}};var zo=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)};var vs=require("@vkontakte/videoplayer-shared");var zr=class r{constructor(e,t){this.currentRepresentation$=new vs.ValueSubject(null);this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,vs.isNullable)(e))for(let t of this.representations){let i=t.segmentReference.segments.find(a=>a.time.from<=e&&a.time.to>=e);if(!i||this.currentSegment?.time.from===i.time.from&&this.currentSegment.time.to===i.time.to)return;this.currentSegment=i,this.currentRepresentation$.next({...t,label:"Live Text",language:"ru",isAuto:!0,url:new URL(i.url,t.segmentReference.baseUrl).toString()})}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=r.filterRepresentations(t.representations);if(i){this.representations=i;break}}}static isSupported(e){return!!e?.some(t=>r.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ne(t.segmentReference))}};var Px=["timeupdate","progress","play","seeked","stalled","waiting"],Ax=["timeupdate","progress","loadeddata","playing","seeked"];var ys=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.isActiveLowLatency$=new S.ValueSubject(!1);this.timeInWaiting=0;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,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=de(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category: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=em(e??"",this.manifestUrlString)}catch(n){let o=vf(e)??{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(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:h})=>i(n,l,h)),u=new Set(c.map(({codecs:l})=>l)),d=Sf(u);if(d&&(a[n]=c.filter(({codecs:l})=>l.startsWith(d))),n==="video"){let l=this.tuning.preferHDR,h=a.video.some(b=>b.hdr),f=a.video.some(b=>!b.hdr);S.clientChecker.isHDR&&l&&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,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(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)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?lf():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(i){let l=document.createElement("source");a(l),l.type="application/x-mpegurl",l.src=i.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,h)=>[...l,...h.representations],[]);if(this.videoBufferManager=new Gr("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let l=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Gr("audio",this.source,l,n),this.bufferManagers.push(this.audioBufferManager)}if(zr.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new zr(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 h=So(this.manifestUrlString,2);this.manifestUrlString=de(this.manifestUrlString,h+1e3,2)}})),this.representationSubscription.add((0,S.merge)(...Ax.map(l=>(0,S.fromEvent)(this.element,l))).pipe((0,S.map)(l=>this.element?ot(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&(this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(h=>zo(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add((0,S.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,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=h-b,C=1;Math.abs(E)>g&&(C=1+Math.sign(E)*y),zo(this.element,C)})),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 l=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=So(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,I=isFinite(h)?h: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&&I<E?Y="live_forward_buffering":I<E+x&&(Y="live_with_target_offset"),isFinite(h)&&(l=h>l?h: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;!h||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:h})=>l&&h))).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 h=[];return l.duration&&h.push(l.duration),Ne(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&h.push(l.segmentReference.totalSegmentsDurationMs),h})];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 ms({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=ei.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)(...Px.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&&Li(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},i=(0,S.now)(),a=100,s=this.videoBufferManager?.lastDataObtainedTimestamp??0,n=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,c=this.audioBufferManager?.getForwardBufferDuration()??0,u=o<a&&i-s>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=c<a&&i-n>this.tuning.dash.crashOnStallTWithoutDataTimeout;if(this.tuning.useNewProviderReinitLogic&&(u||d)||this.tuning.useNewProviderReinitLogic&&this.timeInWaiting>=2*this.tuning.dash.crashOnStallTimeout||!this.tuning.useNewProviderReinitLogic&&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 l=this.element.currentTime*1e3;this.videoBufferManager?.maintain(l),this.audioBufferManager?.maintain(l),t={...t,position:l}}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:this.tuning.useNewProviderReinitLogic?S.ErrorCategory.NETWORK:S.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Li(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}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 i=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<=i&&o.to+s>i&&(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 Ts=class{constructor(e,t){this.fov=e,this.orientation=t}};var Is=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let 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*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var cm=`attribute vec2 a_vertex;
|
|
58
|
+
`}),f&&tf(a,c,f,o)};var ue=r=>new URL(r).hostname;var V=require("@vkontakte/videoplayer-shared");var af=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))},Ee=async r=>{let e=r.muted;try{await r.play()}catch(t){if(!af(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(i){return af(i)&&(r.muted=!1,console.warn(i)),!1}}return!0};var Le=require("@vkontakte/videoplayer-shared");var nt=require("@vkontakte/videoplayer-shared");function ce(){return(0,nt.now)()}function ko(r){return ce()-r}function wo(r){let e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=n=>i.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 sf(r,e,t){let i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Pi(r,e,t,i){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=ko(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),I=()=>{if(!c){if(--u>=0){y(),i&&i();return}c=!0,l&&l(),t&&t()}},P=N=>(p=N,B),k=()=>{d=ce(),n=new a,n.open("get",r);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 M=ce();s.updateChunk&&w.loaded>N&&(s.updateChunk(ge(),w.loaded-N),N=w.loaded,ee=M)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),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 M=n.response.byteLength-N;M&&s.updateChunk&&s.updateChunk(ge(),M)}n.responseType==="json"&&!Object.values(n.response).length?I():(l&&l(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),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 br=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=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;i+=n;let c=s.bytes*n/o;a+=c,s.start=t,s.bytes-=c}}}if(a>0&&i>0){let s=a*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var gr=class{constructor(e,t,i,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=i,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 i=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()-i,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=Pi(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 i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,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}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=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,Ro=3;var fE=6e4,mE=10,bE=1,gE=500,Sr=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 br(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=wo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){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=wo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,i,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):(!i||i.bitrate>s.bitrate)&&(i=s));return a||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Le.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("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=()=>{sf(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 gr(Ro,ss,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:a}=this.params,s=!1,n=null,o=null,c=null,u=null,d=!1,l=()=>{let I=s&&(!d||d===this.rep);return I||t("Not running!"),I},p=(I,P,k)=>{c&&c.abort(),c=Pi(this.urlResolver.resolve(I,!1),P,k,()=>this._retryCallback()).withTimeout(ss).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ro).withFinally(()=>{c=null}).send()},f=(I,P,k)=>{(0,Le.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),P,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=I=>{let P=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${P}=>${I}`),i.playbackRate=I)},g=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let I=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];I=Math.min(I,D.buf),D.ts<k&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${I} drop=${Y} jitter=${this.sourceJitter}`);let z=I-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=I=>{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,M)=>({chunkIdx:X(w),startTS:Y(w),dur:z(w),discontinuity:M}),B=()=>{let w=0;if(P&&P.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ne=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,le=M;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-ne),w=Math.max(w,0)}return D(w,!0)},N=w=>{let M=k();if(!(M<=0)){if((0,Le.isNonNullable)(w)){for(let ne=0;ne<M;ne++)if(Y(ne)>w)return D(ne)}return B()}},ee=w=>{let M=k(),ne=w?w.chunkIdx+1:0,le=ne-P.fragIndex;if(!(M<=0)){if(!w||le<0||le-M>mE)return t(`Resync: offset=${le} bChunks=${M} chunk=`+JSON.stringify(w)),B();if(!(le>=M))return D(ne-P.fragIndex,!1)}},qe=(w,M,ne)=>{u&&u.abort(),u=Pi(this.urlResolver.resolve(w,!0,this.lowLatency),M,ne,()=>this._retryCallback()).withTimeout(ss).withRetryCount(Ro).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(w,M)=>{qe(I,ne=>{if(!l())return;P=ne;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,Le.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(M))},()=>this._handleNetworkError())},nextChunk:ee}},C=()=>{s=!1,o&&o.abort(),c&&c.abort(),u&&u.abort(),(0,Le.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{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)),re=N+Q,pe=ce(),oe=Math.min(1e4,re-pe);N=pe;let He=()=>{u||l()&&Y.seek(()=>{l()&&(N=ce(),M(),w())})};oe>0?ee=window.setTimeout(()=>{this.paused?w():He()},oe):He()},M=()=>{let Q;for(;Q=Y.nextChunk(B);)B=Q,ri(Q);let re=Y.nextChunk(D);if(re){if(D&&re.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?w():(C(),this._initPlayerWith(e));return}Ue(re)}else w()},ne=(Q,re)=>{if(!l()||!this.sourceBuffer)return;let pe,oe,He,kt=et=>{window.setTimeout(()=>{l()&&ne(Q,re)},et)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),kt(100);else{let et=ce(),je=P.currentTime;!this.paused&&P.buffered.length>1&&qe===je&&et-ge>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),qe!==je&&(qe=je,ge=et);let Vt=this._getBufferSizeSec();if(Vt>30)k(`Buffered ${Vt} seconds; delaying appendBuffer`),kt(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:et,buf:Vt}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),re&&re()}catch(lt){if(lt.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),He=this.sourceBuffer.buffered.length,He!==0&&(pe=this.sourceBuffer.buffered.start(0),oe=je,oe-pe>4&&this.sourceBuffer.remove(pe,oe-3)),kt(1e3);else throw lt}}},le=()=>{X&&z&&(k([`Appending chunk, sz=${X.byteLength}:`,JSON.stringify(D)]),ne(X,function(){X=null,M()}))},Ae=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),Ue=Q=>{l()&&f(Ae(Q),(re,pe)=>{if(l()){if(pe/=1e3,X=re,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())},ri=Q=>{l()&&((0,Le.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ae(Q),!1)))},Ot=Q=>{l()&&(e.cachedHeader=Q,ne(Q,()=>{z=!0,le()}))};s=!0,Y.seek(Q=>{if(l()){if(N=ce(),!Q){w();return}B=Q,!(0,Le.isNullable)(I)||Q.startTS>I?Ue(Q):(D=Q,M())}},I),e.cachedHeader?Ot(e.cachedHeader):p(e.headerUrl,Ot,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,Le.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,Le.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Le.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=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&&ko(n)<3e4)return;i(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,i){this.manifestRequest=Pi(this.urlResolver.resolve(e,!0),t,i,()=>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:i,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):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},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(),i=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(i-a)/i;!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)),i=(0,te.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[a])=>(0,te.isLower)(i,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"),nf=require("@vkontakte/videoplayer-shared");var vr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var SE=(r,e)=>new os.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(c=>t.next(c.isIntersecting||vr()))},{...i,...e});a.observe(r);let s=(0,nf.fromEvent)(document,"visibilitychange").pipe((0,os.map)(n=>!document.hidden||vr())).subscribe(n=>t.next(n));return()=>{a.unobserve(r),s.unsubscribe}}),_e=SE;var vE=["paused","playing","ready"],yE=["paused","playing","ready"],yr=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new H("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new Ve;this.droppedFramesManager=new ns;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new gt;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,i=[];for(let a of t){let s=a.name??a.index.toString(10),n=Ct(a.name)??(0,V.videoSizeToQuality)(a.video),o=a.bitrate/1e3,c={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:c};i.push({track:u,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=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)(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(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(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let c=a?.from;c&&c==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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,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=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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ie(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$:i.playing$,pause$:i.pause$,tracks:a}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((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:i.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,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Oe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(_e(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),ye(this.video)}createLiveDashPlayer(){let e=new Sr({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(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&(0,V.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(i),n||c||s!==o){let u=e.find(({track:d})=>d.id===s)?.representation;(0,V.assertNonNullable)(u,"Representations missing"),this.dash.startPlay(u,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.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(),i=this.videoState.getState(),a=t==="paused"&&i==="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 of=yr;var ot=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){let a=r.start(i)*1e3,s=r.end(i)*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,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let a=0,s=i.length;a<s;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let a=0,s=i.length;a<s;a++){let n=i[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}},Ai=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)}},Tr=class{constructor(){Object.defineProperty(this,"signal",{value:new Ai,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 i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Tr.prototype[Symbol.toStringTag]="AbortController",Ai.prototype[Symbol.toStringTag]="AbortSignal");function cs(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function $o(r){typeof r=="function"&&(r={fetch:r});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!cs({fetch:e,Request:t,AbortController:i,__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 Ir=cs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),uf=Ir?$o({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,yt=Ir?uf.fetch:window.fetch,JR=Ir?uf.Request:window.Request,Tt=Ir?Tr:window.AbortController,XR=Ir?Ai:window.AbortSignal;var df=Ye(hr(),1);var It=()=>window.ManagedMediaSource||window.MediaSource,ls=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),cf=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),lf=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ut=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"',pf='video/webm; codecs="vp09.00.10.08"',hf='video/webm; codecs="av01.0.00M.08"',PE='audio/mp4; codecs="mp4a.40.2"',AE='audio/webm; codecs="opus"',Qt={mms:ls(),mse:cf(),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?.(pf),av1:!!It()?.isTypeSupported?.(hf),aac:!!It()?.isTypeSupported?.(PE),opus:!!It()?.isTypeSupported?.(AE)},ki=(Pe.h264||Pe.h265)&&Pe.aac,zt,kE=async()=>{if(!window.navigator.mediaCapabilities)return;let r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:hf}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:pf}})]);zt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{kE()}catch(r){console.error(r)}var wi=Qt.hls&&xe.mp4,ff=()=>Object.keys(Pe).filter(r=>Pe[r]),mf=(r,e=!1,t=!1)=>{let i=Qt.mse||Qt.mms&&t;return r.filter(a=>{switch(a){case"DASH_SEP":return i&&xe.mp4&&ki;case"DASH_WEBM":return i&&xe.webm&&Pe.vp9&&Pe.opus;case"DASH_WEBM_AV1":return i&&xe.webm&&Pe.av1&&Pe.opus;case"DASH_STREAMS":return i&&(xe.mp4&&ki||xe.webm&&(Pe.vp9||Pe.av1)&&(Pe.opus||Pe.aac));case"DASH_LIVE":return Qt.mse&&xe.mp4&&ki;case"DASH_LIVE_CMAF":return i&&xe.mp4&&ki&&xe.cmaf;case"DASH_ONDEMAND":return i&&xe.mp4&&ki;case"HLS":case"HLS_ONDEMAND":return wi||e&&Qt.mse&&xe.mp4&&ki;case"HLS_LIVE":case"HLS_LIVE_CMAF":return wi;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,ut.assertNever)(a)}})},ds=r=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(r){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,ut.assertNever)(r)}return[e,t]},bf=({webmCodec:r,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...ds(r),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ut.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...ds(r),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ds(r),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ds(r),...a,"HLS","HLS_ONDEMAND"];default:(0,ut.assertNever)(e)}return wi?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},gf=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...a],n=[...a,...i],o,c=ut.clientChecker.isMac&&ut.clientChecker.isSafari;if(ut.clientChecker.isAndroid)switch(r){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,ut.assertNever)(r)}else wi&&!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"]},Mo=r=>r?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Sf=r=>{if(r.size!==0){if(r.size===1)return r.values().next().value.split(".").at(0);for(let e of r){let t=(0,df.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return r.values().next().value.split(".").at(0)}};var Ri=require("@vkontakte/videoplayer-shared"),vf=r=>{if(!r)return{id:"EmptyResponse",category:Ri.ErrorCategory.PARSER,message:"Empty response"};if(r.length<=2&&r.match(/^\d+$/))return{id:`UVError#${r}`,category:Ri.ErrorCategory.NETWORK,message:`UV Error ${r}`};let e=r.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ri.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(r,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ri.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ri.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Li=(r,e)=>{for(let t=0;t<r.length;t++)if(r.start(t)*1e3<=e&&r.end(t)*1e3>e)return!0;return!1};var S=require("@vkontakte/videoplayer-shared");var Oi=Ye(hr(),1);var wE=(r,e={})=>{let i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},RE=r=>window.clearTimeout(r),yf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Co=yf?wE:window.requestIdleCallback,lL=yf?RE:window.cancelIdleCallback;var nm=Ye(ts(),1);var Ne=require("@vkontakte/videoplayer-shared"),LE=16,Tf=!1;try{Tf=Ne.clientChecker.isSafari&&!!Ne.clientChecker.macVersion&&Ne.clientChecker.macVersion<=LE}catch(r){console.error(r)}var Do=class{constructor(e){this.bufferFull$=new Ne.Subject;this.error$=new Ne.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:Ne.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(i=>{let a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i;Tf&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)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:Ne.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,Ne.assertNever)(t)}}},If=Do;var Bo=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};var T=require("@vkontakte/videoplayer-shared");var K=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i: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 $i=class extends K{};var Er=class extends K{};var xr=class extends K{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let a=this.readString(4);this.compatibleBrands.push(a),i-=4}}};var Pr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ar=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var kr=class extends K{constructor(e,t){super(e,t),this.data=this.content}};var se=class extends K{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Kt=class extends se{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 i=0;i<this.referenceCount;i++){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 wr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Rr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Lr=class extends se{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 $r=class extends se{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Mr=class extends se{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Cr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Dr=class extends se{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 Br=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Or=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vr=class extends se{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var _r=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Nr=class extends se{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 Fr=class extends se{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var qr=class extends se{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let 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:xr,moov:Pr,moof:Ar,mdat:kr,sidx:Kt,trak:wr,mdia:Cr,mfhd:Vr,tkhd:Dr,traf:_r,tfhd:Nr,tfdt:Fr,trun:qr,minf:Br,sv3d:Rr,st3d:Lr,prhd:$r,proj:Or,equi:Mr,uuid:Er,unknown:$i},Jt=class r{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=ME[e];return i?new i(t,new r):new $i(t,new r)}};var Mi=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=r=>DE.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",OE=r=>{let e=new Kt(r,new Jt),t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},VE=(r,e)=>{let i=new Jt().parse(r),a=new Mi(i),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(r.buffer,u,l)},_E=(r,e)=>{let i=new Jt().parse(r),s=new Mi(i).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=r=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Jt().parse(r),a=new Mi(i);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},Ef={validateData:BE,parseInit:NE,getIndexRange:()=>{},parseSegments:OE,parseFeedableSegmentChunk:VE,getSegmentEndTime:_E};var Et=require("@vkontakte/videoplayer-shared");var Pf=require("@vkontakte/videoplayer-shared");var xf={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"}},Af=r=>{let e=r.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ur(r,t),a=i in xf,s=a?xf[i].type:"binary",n=r.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(r.buffer,r.byteOffset+t+1,o-1),u=n&255>>o,d=Ur(c),l=u*2**((o-1)*8)+d,p=t+o,f;return p+l>r.byteLength?f=new DataView(r.buffer,r.byteOffset+p):f=new DataView(r.buffer,r.byteOffset+p,l),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:f,valueSize:l}},Ur=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{let t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Xe=(r,e)=>{switch(e){case"int":return r.getInt8(0);case"uint":return Ur(r);case"float":return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case"string":return new TextDecoder("ascii").decode(r);case"utf8":return new TextDecoder("utf-8").decode(r);case"date":return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case"master":return r;case"binary":return r;default:(0,Pf.assertNever)(e)}},Xt=(r,e)=>{let t=0;for(;t<r.byteLength;){let i=new DataView(r.buffer,r.byteOffset+t),a=Af(i);if(!e(a))return;a.type==="master"&&Xt(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},kf=r=>{if(r.getUint32(0)!==440786851)return!1;let e,t,i,a=Af(r);return Xt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Xe(o,n):s===17026?t=Xe(o,n):s===17029&&(i=Xe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var wf=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],FE=[231,22612,22743,167,171,163,160,175],qE=r=>{let e,t,i,a,s=!1,n=!1,o=!1,c,u,d=!1,l=0;return Xt(r,({tag:p,type:f,value:b,valueSize:g})=>{if(p===21419){let y=Xe(b,f);u=Ur(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?i=Xe(b,f):p===17545?a=Xe(b,f):p===21420&&u===475249515?c=Xe(b,f):p===374648427?Xt(b,({tag:y,type:E,value:C})=>y===30321?(d=Xe(C,E)===1,!1):!0):s&&n&&wf.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"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*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=r=>{if((0,Et.isNullable)(r.cuesSeekPosition))return;let e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},HE=(r,e)=>{let t=!1,i=!1,a=o=>(0,Et.isNonNullable)(o.time)&&(0,Et.isNonNullable)(o.position),s=[],n;return Xt(r,({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=Xe(u,c));break;case 183:break;case 241:n&&(n.position=Xe(u,c));break;default:t&&wf.includes(o)&&(i=!0)}return!(t&&i)}),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=r=>{let e=0,t=!1;try{Xt(r,i=>i.tag===524531317?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):FE.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Rf={validateData:kf,parseInit:qE,getIndexRange:UE,parseSegments:HE,parseFeedableSegmentChunk:jE};var Ci=r=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(r);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Rf;case"mp4":return Ef}}throw new ReferenceError(`Unsupported mime type ${r}`)};var Ho=Ye(Jf(),1);var Uo=r=>{let e=r.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=i;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=i[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 Bi=require("@vkontakte/videoplayer-shared");var Xf=r=>{if(r.includes("/")){let e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};var Zf=r=>{if(!r.startsWith("P"))return;let e=(n,o)=>{let c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),a=i?.[1]==="-"?-1:1,s={days:e(i?.[5],a),hours:e(i?.[6],a),minutes:e(i?.[7],a),seconds:e(i?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},xt=(r,e)=>{let t=r;t=(0,Ho.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(i)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ho.default)(t,n,(o,c)=>(0,Bi.isNullable)(s)?o:(0,Bi.isNullable)(c)?s:s.padStart(parseInt(c,10),"0"))}return t},em=(r,e)=>{let i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},s=i.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=Zf(f);else if(b){let I=Zf(b);(0,Bi.isNonNullable)(I)&&(p=I)}else y&&(p=parseInt(y,10));let E=0,C=s.getAttribute("profiles")?.split(",")??[];for(let I of c){let P=I.getAttribute("id")??"id"+(E++).toString(10),k=I.getAttribute("mimeType")??"",Y=I.getAttribute("codecs")??"",z=I.getAttribute("contentType")??k?.split("/")[0],X=I.getAttribute("profiles")?.split(",")??[],D=I.getAttribute("lang")??void 0,B=I.querySelector("Label")?.textContent?.trim()??void 0,N=I.querySelectorAll("Representation"),ee=I.querySelector("SegmentTemplate"),qe=I.querySelector("Role")?.getAttribute("value")??void 0,ge=z,w={id:P,language:D,isDefault:qe==="main",label:B,codecs:Y,hdr:ge==="video"&&Uo(Y),mime:k,representations:[]};for(let M of N){let ne=M.getAttribute("lang")??void 0,le=M.getAttribute("label")??void 0,Ae=M.querySelector("BaseURL")?.textContent?.trim()??"",Ue=new URL(Ae||o,e).toString(),ri=M.getAttribute("mimeType")??k,Ot=M.getAttribute("codecs")??Y??"",Q;if(z==="text"){let re=M.getAttribute("id")||"",pe=re.includes("_auto"),oe=M.querySelector("SegmentTemplate");if(oe){let He={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},kt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,et=parseInt(oe.getAttribute("startNumber")??"",10)??1,je=parseInt(oe.getAttribute("timescale")??"",10),Vt=oe.querySelectorAll("SegmentTimeline S")??[],lt=oe.getAttribute("media");if(!lt)continue;let da=[],pa=0,ha="",ai=0,_i=et,he=0;for(let Ge of Vt){let _t=parseInt(Ge.getAttribute("d")??"",10),Me=parseInt(Ge.getAttribute("r")??"",10)||0,wt=parseInt(Ge.getAttribute("t")??"",10);he=Number.isFinite(wt)?wt:he;let Nt=_t/je*1e3,si=he/je*1e3;for(let tt=0;tt<Me+1;tt++){let Rt=xt(lt,{...He,segmentNumber:_i.toString(10),segmentTime:(he+tt*_t).toString(10)}),ni=(si??0)+tt*Nt,Fi=ni+Nt;_i++,da.push({time:{from:ni,to:Fi},url:Rt})}he+=(Me+1)*_t,pa+=(Me+1)*Nt}ai=he/je*1e3,ha=xt(lt,{...He,segmentNumber:_i.toString(10),segmentTime:he.toString(10)});let Ni={time:{from:ai,to:1/0},url:ha},dt={type:"template",baseUrl:Ue,segmentTemplateUrl:lt,initUrl:"",totalSegmentsDurationMs:pa,segments:da,nextSegmentBeyondManifest:Ni,timescale:je};Q={id:re,kind:"text",segmentReference:dt,profiles:[],duration:p,bitrate:kt,mime:"",codecs:"",width:0,height:0,isAuto:pe}}else Q={id:re,isAuto:pe,kind:"text",url:Ue}}else{let re=M.getAttribute("contentType")??ri?.split("/")[0]??z,pe=I.getAttribute("profiles")?.split(",")??[],oe=parseInt(M.getAttribute("width")??"",10),He=parseInt(M.getAttribute("height")??"",10),kt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,et=M.getAttribute("frameRate")??"",je=M.getAttribute("quality")??void 0,Vt=et?Xf(et):void 0,lt=M.getAttribute("id")??"id"+(E++).toString(10),da=re==="video"?`${He}p`:re==="audio"?`${kt}Kbps`:Ot,pa=`${lt}@${da}`,ha=[...C,...X,...pe],ai,_i=M.querySelector("SegmentBase"),he=M.querySelector("SegmentTemplate")??ee;if(_i){let dt=M.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ge,_t]=dt.split("-").map(Rt=>parseInt(Rt,10)),Me={from:Ge,to:_t},wt=M.querySelector("SegmentBase")?.getAttribute("indexRange"),[Nt,si]=wt?wt.split("-").map(Rt=>parseInt(Rt,10)):[],tt=wt?{from:Nt,to:si}:void 0;ai={type:"byteRange",url:Ue,initRange:Me,indexRange:tt}}else if(he){let dt={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},Ge=parseInt(he.getAttribute("timescale")??"",10),_t=he.getAttribute("initialization")??"",Me=he.getAttribute("media"),wt=parseInt(he.getAttribute("startNumber")??"",10)??1,Nt=xt(_t,dt);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let si=he.querySelectorAll("SegmentTimeline S")??[],tt=[],Rt=0,ni="",Fi=0;if(si.length){let fa=wt,We=0;for(let oi of si){let it=parseInt(oi.getAttribute("d")??"",10),Ft=parseInt(oi.getAttribute("r")??"",10)||0,ma=parseInt(oi.getAttribute("t")??"",10);We=Number.isFinite(ma)?ma:We;let Rs=it/Ge*1e3,Mm=We/Ge*1e3;for(let ba=0;ba<Ft+1;ba++){let Cm=xt(Me,{...dt,segmentNumber:fa.toString(10),segmentTime:(We+ba*it).toString(10)}),ru=(Mm??0)+ba*Rs,Dm=ru+Rs;fa++,tt.push({time:{from:ru,to:Dm},url:Cm})}We+=(Ft+1)*it,Rt+=(Ft+1)*Rs}Fi=We/Ge*1e3,ni=xt(Me,{...dt,segmentNumber:fa.toString(10),segmentTime:We.toString(10)})}else if((0,Bi.isNonNullable)(p)){let We=parseInt(he.getAttribute("duration")??"",10)/Ge*1e3,oi=Math.ceil(p/We),it=0;for(let Ft=1;Ft<oi;Ft++){let ma=xt(Me,{...dt,segmentNumber:Ft.toString(10),segmentTime:it.toString(10)});tt.push({time:{from:it,to:it+We},url:ma}),it+=We}Fi=it,ni=xt(Me,{...dt,segmentNumber:oi.toString(10),segmentTime:it.toString(10)})}let $m={time:{from:Fi,to:1/0},url:ni};ai={type:"template",baseUrl:Ue,segmentTemplateUrl:Me,initUrl:Nt,totalSegmentsDurationMs:Rt,segments:tt,nextSegmentBeyondManifest:$m,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!re||!ri)continue;let Ni={video:"video",audio:"audio",text:"text"}[re];if(!Ni)continue;ge||=Ni,Q={id:pa,kind:Ni,segmentReference:ai,profiles:ha,duration:p,bitrate:kt,mime:ri,codecs:Ot,width:oe,height:He,fps:Vt,quality:je}}w.language||=ne,w.label||=le,w.mime||=ri,w.codecs||=Ot,w.hdr||=ge==="video"&&Uo(Ot),w.representations.push(Q)}ge&&a[ge].push(w)}return{dynamic:u,liveAvailabilityStartTime:l,duration:p,streams:a}};var Hr=Ye(hr(),1);var tm=require("@vkontakte/videoplayer-shared"),im=({id:r,width:e,height:t,bitrate:i,fps:a,quality:s})=>{let n=(s?Ct(s):void 0)??(0,tm.videoSizeToQuality)({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:a}},rm=({id:r,bitrate:e})=>({id:r,bitrate:e}),hs=(r,e,t)=>{let i=e.indexOf(r);return(0,Hr.default)(t,Math.round(t.length*i/e.length))??(0,Hr.default)(t,-1)},am=({language:r,label:e},{id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),sm=({language:r,label:e,id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),Wo=({id:r,language:e,label:t,codecs:i,isDefault:a})=>({id:r,language:e,label:t,codec:(0,Hr.default)(i.split("."),0),isDefault:a}),Yo=({id:r,language:e,label:t,hdr:i,codecs:a})=>({id:r,language:e,hdr:i,label:t,codec:(0,Hr.default)(a.split("."),0)}),fs=r=>"url"in r,Fe=r=>r.type==="template",jr=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);var Gr=class{constructor(e,t,i,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:c=!1,manifest:u}){this.currentSegmentLength$=new T.ValueSubject(0);this.onLastSegment$=new T.ValueSubject(!1);this.fullyBuffered$=new T.ValueSubject(!1);this.playingRepresentation$=new T.ValueSubject(void 0);this.playingRepresentationInit$=new T.ValueSubject(void 0);this.error$=new T.Subject;this.gaps=[];this.subscription=new T.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.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,T.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 If(this.sourceBuffer),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,c=this.mediaSource.readyState;c!=="open"&&(o={id:`SegmentEjection_source_${c}`,category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:T.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,Bo(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=c,this.tuning.useNewPruneBufferStrategy){let u=ot(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 i=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,T.assertNonNullable)(i,"No init buffer for starting representation"),(0,T.assertNonNullable)(a,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,T.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,T.assertNonNullable)(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,T.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,T.isNonNullable)(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,T.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||!Fe(d.segmentReference))return;let l=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(i);(0,T.assertNonNullable)(a);let s=this.segments.get(i);(0,T.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,T.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(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}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,T.isNullable)(e)||(0,T.isNullable)(this.downloadingRepresentationId)||(0,T.isNullable)(this.playingRepresentationId)||(0,T.isNullable)(this.sourceBuffer)||!(0,T.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,T.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let a=i.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=ot(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)&&Bo(this.sourceBuffer.buffered)>=this.bufferLimit){let u=ot(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(i,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,Oi.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&&ot(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Oi.default)(i,-1);c&&c.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===c))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+a}),i=s.time.to;(0,T.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[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 i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Fe(i.segmentReference))return;let a=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=this.segments.get(i.id)??[],n=(0,Oi.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(i.segmentReference);this.segments.set(i.id,c)}else{let c=a.slice(o+1);this.segments.set(i.id,[...s,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,T.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}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 i=t.segmentReference;if(!Fe(i))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*i.timescale/1e3).toString(10),c=xt(i.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 i=this.segments.get(t);return i?i.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,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let a=e.findIndex(({status:l,time:{from:p,to:f}},b)=>{let g=p<=i&&f>=i,y=p>i||g||b===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&p<=i+E||f<=i+E;return(l==="none"||l==="partially_ejected"&&y&&C&&this.sourceBuffer&&!(Li(this.sourceBuffer.buffered,p)&&Li(this.sourceBuffer.buffered,f)))&&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,i="auto"){Fe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let 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,T.abortable)(o,async function*(){let d=(0,T.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:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,T.now)(),!d)return;let l=new DataView(d);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,f=Ci(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]),jr(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="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,T.abortable)(n,async function*(){let c=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,c),(0,T.fromEvent)(window,"online").pipe((0,T.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:i}),this.lastDataObtainedTimestampMs=(0,T.now)(),this.failedDownloads=0}catch(c){this.abortActiveSegments(e),jr(c)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Fe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,a={from:(0,Oi.default)(e,0).byte.from,to:(0,Oi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:a,signal:s,onProgress:(o,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)(),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:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Fe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let a=i.toString(),{signal:s}=this.downloadAbortController,n=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)();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:T.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:i,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=i,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Ci(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:i,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:i,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,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>=i&&l.byte.to<i+e.byteLength))continue;if(s.aborted){n();continue}let g=p?l.byte.from-i:0,y=p?l.byte.to-i: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),I=this.getCurrentPosition();(0,T.isNonNullable)(I)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-I,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,T.isNullable)(I))&&(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),I=d.loadedBytes===f?x:Ci(o.mime).parseFeedableSegmentChunk(x);I?.byteLength&&(l.status="partially_fed",d.feedingBytes+=I.byteLength,this.sourceBufferTaskQueue.append(I,s).then(P=>{if(s.aborted)n();else if(P)d.fedBytes+=I.byteLength,d.fedBytes===f&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<f)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,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-i,l=u.byte.to-i,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:Ci(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",fs(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let a of this.segments.get(i.id)??[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");(0,T.assertNonNullable)(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[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 i=this.representations.get(e);i&&(this.initLoadIdleCallback=Co(()=>(0,nm.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,T.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ci(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&&Fe(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),i&&this.error$.next({id:"LoadInits",category:T.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,T.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=fs(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)["none","partially_ejected"].includes(f.status)&&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&&i){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,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,T.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=fs(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&&i){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)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,T.isNullable)(e)?0:ot(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let a={representation:e,from:i.time.from,to:i.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<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){a=void 0;break}o>i.time.from&&o<i.time.to&&(a.from=o),n<i.time.to&&n>i.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){if(!this.gapDetectionIdleCallback){(0,T.assertNonNullable)(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Co(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:T.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,T.isNullable)(this.sourceBuffer)||(0,T.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let a=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:s})}let t=100;for(let i of this.segments.values())for(let a of i){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&&n<d.to-t||o>d.from+t&&o<=d.to);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 Wr=r=>{let e=new URL(r);return e.searchParams.set("quic","1"),e.toString()};var om=r=>{let e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:a}};var G=require("@vkontakte/videoplayer-shared");var ms=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,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"),i=e;this.requestQuic&&(i=Wr(i));let a=yield yt(i,{signal:this.abortAllController.signal}).catch(Yr);return a?(t.log("success",(0,G.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",(0,G.flattenObject)({url:i,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:i,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(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let B=new URL(u,location.href);B.searchParams.append("bytes",`${i.from}-${i.to}`),u=B.toString();break}default:(0,G.assertNever)(t)}this.requestQuic&&(u=Wr(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){Yr(N)}}),this.abortAllController.signal.aborted||n.aborted)try{B.abort()}catch(N){Yr(N)}p=B.signal}let b=(0,G.now)();l.log("startRequest",(0,G.flattenObject)({url:u,priority:s,rangeMethod:t,range:i,isLowLatency:c,requestStartedAt:b}));let g=yield yt(u,{priority:s,headers:d,signal:p}).catch(Yr),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 I=0,P=new Uint8Array(0),k=!1,Y=B=>{f?.unsubscribe(),k=!0,Yr(B)},z=(0,G.abortable)(p,async function*({done:B,value:N}){if(I===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,I+=N.byteLength,a?.(new DataView(P.buffer),I),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,i){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:i,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:i,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 i=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(i,{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=i.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:i}=om(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,G.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Yr=r=>{if(!jr(r))throw r};var Zt=(r,e,t)=>t*e+(1-t)*r,Qo=(r,e)=>r.reduce((t,i)=>t+i,0)/e,um=(r,e,t,i)=>{let a=0,s=t,n=Qo(r,e),o=e<i?e:i;for(let c=0;c<o;c++)r[s]>n?a++:a--,s=(r.length+s-1)%r.length;return Math.abs(a)===o};var Qr=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 Qr.ValueSubject(e.initial),this.debounced$=new Qr.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,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let 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,Qr.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 bs=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 gs=class extends Bt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Qo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Zt(this.emaSmoothed,e,this.params.emaAlpha);let i=um(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ss=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 ei=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new bs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new gs({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Ss({initial:e,label:"liveEdgeDelay",...t})}};var zo=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)};var vs=require("@vkontakte/videoplayer-shared");var zr=class r{constructor(e,t){this.currentRepresentation$=new vs.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,vs.isNullable)(e))for(let t of this.representations)for(let i of t){let a=i.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let c=a.segments.find(u=>u.time.from<=e&&u.time.to>=e);!c||this.currentSegment?.time.from===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=r.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>r.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Fe(t.segmentReference))}};var Ax=["timeupdate","progress","play","seeked","stalled","waiting"],kx=["timeupdate","progress","loadeddata","playing","seeked"];var ys=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.isActiveLowLatency$=new S.ValueSubject(!1);this.timeInWaiting=0;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,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=de(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category: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=em(e??"",this.manifestUrlString)}catch(n){let o=vf(e)??{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(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})=>i(n,l,p)),u=new Set(c.map(({codecs:l})=>l)),d=Sf(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,i){this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(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?lf():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(i){let l=document.createElement("source");a(l),l.type="application/x-mpegurl",l.src=i.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 Gr("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 Gr("audio",this.source,l,n),this.bufferManagers.push(this.audioBufferManager)}if(zr.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new zr(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=So(this.manifestUrlString,2);this.manifestUrlString=de(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add((0,S.merge)(...kx.map(l=>(0,S.fromEvent)(this.element,l))).pipe((0,S.map)(l=>this.element?ot(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&(this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(p=>zo(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),zo(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=So(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,I=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&&I<E?Y="live_forward_buffering":I<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),Fe(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 ms({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=ei.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)(...Ax.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&&Li(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},i=(0,S.now)(),a=100,s=this.videoBufferManager?.lastDataObtainedTimestamp??0,n=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,c=this.audioBufferManager?.getForwardBufferDuration()??0,u=o<a&&i-s>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=c<a&&i-n>this.tuning.dash.crashOnStallTWithoutDataTimeout;if(this.tuning.useNewProviderReinitLogic&&(u||d)||this.tuning.useNewProviderReinitLogic&&this.timeInWaiting>=2*this.tuning.dash.crashOnStallTimeout||!this.tuning.useNewProviderReinitLogic&&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 l=this.element.currentTime*1e3;this.videoBufferManager?.maintain(l),this.audioBufferManager?.maintain(l),t={...t,position:l}}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:this.tuning.useNewProviderReinitLogic?S.ErrorCategory.NETWORK:S.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Li(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}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 i=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<=i&&o.to+s>i&&(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 Ts=class{constructor(e,t){this.fov=e,this.orientation=t}};var Is=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let 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*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var lm=`attribute vec2 a_vertex;
|
|
59
59
|
attribute vec2 a_texel;
|
|
60
60
|
|
|
61
61
|
varying vec2 v_texel;
|
|
@@ -66,7 +66,7 @@ void main(void) {
|
|
|
66
66
|
// save texel vector to pass to fragment shader
|
|
67
67
|
v_texel = a_texel;
|
|
68
68
|
}
|
|
69
|
-
`;var
|
|
69
|
+
`;var dm=`#ifdef GL_ES
|
|
70
70
|
precision highp float;
|
|
71
71
|
precision highp int;
|
|
72
72
|
#else
|
|
@@ -109,5 +109,5 @@ void main(void) {
|
|
|
109
109
|
// sample using new coordinates
|
|
110
110
|
gl_FragColor = texture2D(u_texture, tc);
|
|
111
111
|
}
|
|
112
|
-
`;var Es=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let 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 Ts(this.params.fov,this.params.orientation),this.cameraRotationManager=new Is(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(cm,this.gl.VERTEX_SHADER),i=this.createShader(lm,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-i,n=t-a,o=e+i,c=t-a,u=e+i,d=t+a,l=e-i,h=t+a;return[s,n,o,c,u,d,l,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 ti=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("stopped");this.elementSize$=new q.ValueSubject(void 0);this.droppedFramesManager=new ns;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new mr;this.audioTrackSwitchHistory=new mr;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&i?.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()):i?.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()):i?.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()):i?.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 Es(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ys({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,i=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:i,genericErrorListener:s,connect:(o,c)=>this.subscription.add(o.subscribe(c,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,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$:i.playing$,pause$:i.pause$,tracks:u})})),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.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(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(at(this.video,t.isLooped,a)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,a)),s((0,q.observeElementSize)(this.video),this.elementSize$),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},a)).add(i.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;let d=this.player.getStreams();if((0,q.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Wo(f));let b=[];for(let g of f.representations){let y=rm(g);b.push(y),this.audioTracksMap.set(y,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let l=[];for(let h of d.video){l.push(Yo(h));let f=[];for(let b of h.representations){let g=im(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(l),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)}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[h,f]=l,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 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: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(l),e.currentVideoStream$.next(Yo(h))},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: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(Wo(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));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,i=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=ot(this.video.buffered,this.video.currentTime*1e3),h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(l/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),g=[...this.audioStreamsMap.keys()].find(({id:k})=>k===b?.id)??this.audioStreamsMap.keys().next().value,y=0;if(g){if(n&&!i)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=i?E??n:n??E,x;this.params.tuning.useSeparateAudioVideoABR?x=g&&rf(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 I=this.videoTracksMap.get(C)?.representation,P=x&&this.audioTracksMap.get(x)?.representation;if(I&&P)return[I,P];if(I&&!P&&this.audioTracksMap.size===0)return[I,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.player.destroy(),this.params.output.element$.next(void 0),ye(this.video),this.tracer.end()}};var Jr=class extends ti{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ii=require("@vkontakte/videoplayer-shared");var Xr=class extends ti{constructor(e){super(e),this.liveOffset=new gt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,ii.combine)({interval:(0,ii.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,ii.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ii.map)(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=am(a);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="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 dm=Ge(ts(),1);var j=require("@vkontakte/videoplayer-shared"),Je={};var Vi=(r,e)=>new j.Observable(t=>{let i=(a,s)=>t.next(s);return r.on(e,i),()=>r.off(e,i)}),Zr=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new H("initializing");this.textTracksManager=new st;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.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},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,dm.default)(import("hls.js").then(a=>{e||(Je.Hls=a.default,Je.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){(0,j.assertNonNullable)(Je.Hls,"hls.js not loaded"),this.hls=new Je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,j.assertNonNullable)(Je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=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,i));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(at(this.video,e.isLooped,i)),this.subscription.add(Te(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Oe(this.video,e.playbackRate,a.playbackRateState$,i)),s(Ve(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,j.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Vi(this.hls,Je.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")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(e.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Vi(this.hls,Je.Events.MANIFEST_PARSED).pipe((0,j.map)(({levels:u})=>u.reduce((d,l)=>{let h=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:h.toString(),quality:g,bitrate:l.bitrate/1e3,size:{width:f,height:b},fps:y};return this.trackLevels.set(h,{track:E,level:l}),d.push(E),d},[]))),t.availableVideoTracks$),s(Vi(this.hls,Je.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let d=[];for(let l of u.subtitleTracks){let h=l.name,f=l.attrs.URI||"",b=l.lang;d.push({id:h,url:f,language:b,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Vi(this.hls,Je.Events.LEVEL_LOADING).pipe((0,j.map)(({url:u})=>ue(u))),t.hostname$),s(Vi(this.hls,Je.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:i}));let n=u=>Array.from(this.trackLevels.values()).find(({level:d})=>d===u)?.track,o=Vi(this.hls,Je.Events.LEVEL_SWITCHED).pipe((0,j.map)(({level:u})=>n(this.hls.levels[u])));o.pipe((0,j.filter)(j.isNonNullable)).subscribe(t.currentVideoTrack$,i),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),h=this.hls.currentLevel,f=this.hls.levels[h];!f||d.bitrate>f.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:i})),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,i))}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 pm="X-Playback-Duration",Ko=async r=>{let e=await yt(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(pm)?parseInt(e.headers.get(pm),10):void 0};var U=require("@vkontakte/videoplayer-shared");var Xo=Ge($n(),1);var xs=require("@vkontakte/videoplayer-shared");var $x=r=>{let e=null;if(r.QUALITY&&(e=Ct(r.QUALITY)),!e&&r.RESOLUTION){let[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,xs.videoSizeToQuality)({width:t,height:i})}return e??null},Mx=(r,e)=>{let t=r.split(`
|
|
113
|
-
`),i=[],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,Xo.default)(o[1].split(",").map(y=>y.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,l=$x(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,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&&i.push({id:d,quality:l,url:g,bandwidth:h,size:b,fps:f})}if(c){let u=(0,Xo.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,h=u.NAME;d&&l&&a.push({type:"internal",id:l,label:h,language:l,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},Cx=r=>new Promise(e=>{setTimeout(()=>{e()},r)}),Jo=0,hm=async(r,e=r,t)=>{let a=await(await yt(r)).text();Jo+=1;try{let{qualityManifests:s,textTracks:n}=Mx(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Jo<=t.manifestRetryMaxCount)return await Cx((0,xs.getExponentialDelay)(Jo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),hm(r,e,t)}return{qualityManifests:[],textTracks:[]}},Ps=hm;var ea=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new H("stopped");this.textTracksManager=new st;this.manifests$=new U.ValueSubject([]);this.liveOffset=new gt;this.manifestStartTime$=new U.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=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(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else 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},Ps(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new U.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=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,i));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),i)),this.subscription.add(Te(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Oe(this.video,t.playbackRate,a.playbackRateState$,i)),s(Ve(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")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe((0,U.filterChanged)(),(0,U.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),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 h=this.manifests$.getValue().find(f=>f.id===l);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ue(h.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)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),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),i)),this.subscription.add(this.manifests$.pipe((0,U.map)(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:h})=>({id:c,quality:u,size:d,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.selectManifest();if((0,U.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:c}=t?.to??i??{};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(),Ko(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();Ko(l).then(h=>{(0,U.isNullable)(h)||this.maxSeekBackTime$.next(h)})}})}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,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/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 st;this.manifests$=new W.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=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(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":i==="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),Ps(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:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:W.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=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(at(this.video,t.isLooped,i)),this.subscription.add(Te(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Oe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).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 h=this.manifests$.getValue().find(f=>f.id===l);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ue(h.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)},i))),this.subscription.add(this.manifests$.pipe((0,W.map)(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:h})=>({id:c,quality:u,size:d,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!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"},i))}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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.selectManifest();if((0,W.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};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 ia=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new st;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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(i?.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()):i?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.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,i],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),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,i=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,i));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(at(this.video,t.isLooped,i)),this.subscription.add(Te(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Oe(this.video,t.playbackRate,a.playbackRateState$,i)),s(Ve(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).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()},i)),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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,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=Wr(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,i=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&&(i=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:i})}};var Z=require("@vkontakte/videoplayer-shared");var mm=require("@vkontakte/videoplayer-shared"),fm=["stun:videostun.mycdn.me:80"],Dx=1e3,Bx=3,Zo=()=>null,As=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=Zo;this.externalStopCallback=Zo;this.externalErrorCallback=Zo;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:fm}]};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:mm.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Dx)}normalizeOptions(e={}){let t={stunServerList:fm,maxRetryNumber:Bx,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ra=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(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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()):i?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.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 As(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ye(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category: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,i));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(Ve(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")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Te(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,Z.assertNever)(n.to)}},i)).add((0,Z.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(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"),bm=r=>new Pt.Observable(e=>{let t=new Pt.Subscription,i=r.desiredPlaybackState$.stateChangeStarted$.pipe((0,Pt.map)(({from:u,to:d})=>`${u}-${d}`)),a=r.desiredPlaybackState$.stateChangeEnded$,s=r.providerChanged$.pipe((0,Pt.map)(({type:u})=>u!==void 0)),n=new Pt.Subject,o=0,c="unknown";return t.add(i.subscribe(u=>{o&&window.clearTimeout(o),c=u,o=window.setTimeout(()=>n.next(u),r.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),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var $e=require("@vkontakte/videoplayer-shared");var sa=null,ks=null;function eu(){return sa||(sa=new(window.AudioContext||window.webkitAudioContext)),ks||(ks=new GainNode(sa,{gain:1}),ks.connect(sa.destination)),{audioCtx:sa,gainNode:ks}}var gm=require("@vkontakte/videoplayer-shared");var na=class r{constructor(e,t,i,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=a;this.subscriptions=new $e.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe((0,$e.filter)(n=>!!n.type),(0,$e.once)()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){gm.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,$e.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,$e.filter)(({playbackState:t,video:i,volume:{muted:a,volume:s}})=>t==="playing"&&!!i&&!a&&!!s),(0,$e.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:i,gainNode:a}=eu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,i.resume().then(()=>{if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${r.errorId} destroyed`);a.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(a)}catch(n){this.volumeMultiplierError$.next({id:r.errorId,category:$e.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:r.errorId,category:$e.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=eu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var Ox={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=mf([...gf(this.params.tuning),...bf(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,v.isNonNullable)(e.sources[o])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning,s=[];i?s=[i]: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=[...Mo(!0),...Mo(!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 i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}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,i=this.params.desiredState.seekState.getState(),a=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?i.position:t,forcePrecise:a?i.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:i,desiredState:a}=this.params,s=this.providerOutput,n={container:i,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 Jr({...n,source:o,sourceHls:c})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Xr({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),wi||!this.params.tuning.useHlsJs?new ta({...n,source:o}):new Zr({...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 ia({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new of({...n,source:o,config:{...Ox,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ra({container:i,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:i,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,v.assertNonNullable)(o),new pr({connection:o,meta:s,container:i,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 i=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:i(e.url)}}return(0,Sm.default)(Object.entries(e).map(([a,s])=>[a,i(s)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,i=0;return e.add((0,v.merge)(this.providerOutput.error$,bm({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=i<this.params.tuning.providerErrorLimit&&!c,l=u&&!c&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:c,haveFailoverHost:u,tryFailover:l,canReinitProvider:d},this.params.tuning.useNewProviderReinitLogic?d?(i++,this.reinitProvider()):l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN"):l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",(0,v.flattenObject)(n))})),e}};var _=require("@vkontakte/videoplayer-shared");var Vx=5e3,vm="one_video_throughput",ym="one_video_rtt",ua=window.navigator.connection,Tm=()=>{let r=ua?.downlink;if((0,_.isNonNullable)(r)&&r!==10)return r*1e3},Im=()=>{let r=ua?.rtt;if((0,_.isNonNullable)(r)&&r!==3e3)return r},Em=(r,e,t)=>{let i=t*8,a=i/r;return i/(a+e)},tu=class r{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=r.load(vm)||(e.useBrowserEstimation?Tm():void 0)||Vx,i=r.load(ym)??(e.useBrowserEstimation?Im():void 0)??0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(i),this.rttAdjustedThroughput$=new _.ValueSubject(Em(t,i,e.rttPenaltyRequestSize)),this.throughput=ei.getSmoothedValue(t,-1,e),this.rtt=ei.getSmoothedValue(i,1,e),e.useBrowserEstimation){let a=()=>{let n=Tm();n&&this.throughput.next(n);let o=Im();(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(vm,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{_.safeStorage.set(ym,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})=>Em(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,i=(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,i=(0,_.now)()}));break;case 1:case 0:a.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(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-i;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let a=0,s=(0,_.now)(),n=0,o=(0,_.now)(),c=d=>{this.concurrentDownloads.delete(e),i.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 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=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 i?.read().then(u,c)}};this.concurrentDownloads.add(e),i?.read().then(u,c)}addRawSpeed(e,t,i=1,a=!1){if(r.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return parseInt(t,10)??void 0}},xm=tu;var ca=require("@vkontakte/videoplayer-shared"),Pm={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,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance: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,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,useNewProviderReinitLogic:!1,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},Am=r=>({...(0,ca.fillWithDefault)(r,Pm),configName:[...r.configName??[],...Pm.configName]});var p=require("@vkontakte/videoplayer-shared");var At=require("@vkontakte/videoplayer-shared"),iu=({seekState:r,position$:e})=>(0,At.merge)(r.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)(()=>r.getState().state==="none")));var km=require("@vkontakte/videoplayer-shared"),wm=r=>{let e=typeof r.container=="string"?document.getElementById(r.container):r.container;return(0,km.assertNonNullable)(e,`Wrong container or containerId {${r.container}}`),e};var ws=require("@vkontakte/videoplayer-shared"),Rm=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,ws.filter)(a=>a.length>0),(0,ws.once)()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};var la=class{constructor(e={configName:[]},t=p.Tracer.createRootTracer(!1)){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 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 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:Jh};if(this.initLogs(),this.tuning=Am(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 xm(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,a,s)=>{let n=Reflect.get(i,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(c){let u=o.map(h=>JSON.stringify(h,(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:p.ErrorCategory.WTF,message:l,thrown:c}),c}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",(0,p.flattenObject)(i)),this.domContainer=wm(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&&!vr()?(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 i=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=i&&!a&&(s=i-.1),this.tracer.log("seekTime",{duration:i,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)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,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 Rm(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 i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.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 i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let a=i.getCameraRotation(),s=i.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(),i=t.state==="none"?void 0:t.position;return(0,p.isNonNullable)(i)?i/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((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||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,c)=>(0,p.isInvariantQuality)(o)?1:(0,p.isInvariantQuality)(c)?-1:(0,p.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,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:iu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:n,position:o,isLowLatency:c})=>{let u=this.getActiveLiveDelay(c);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:c})=>n&&(Math.abs(c)-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(iu({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 i=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:n})=>n==="playing"),(0,p.once)()).subscribe(()=>i.next(!1)));let a=0,s=(0,p.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,p.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.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(),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,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)((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t,i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:a})=>a===i),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,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),Kh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>zh(t)),this.providerContainer.current$.subscribe(({type:t})=>fr("provider",t)),e.duration$.subscribe(t=>fr("duration",t)),e.availableVideoTracks$.pipe((0,p.filter)(t=>!!t.length),(0,p.once)()).subscribe(t=>fr("tracks",t)),this.events.fatalError$.subscribe(new me("fatalError")),this.events.managedError$.subscribe(new me("managedError")),e.position$.subscribe(new me("position")),e.currentVideoTrack$.pipe((0,p.map)(t=>t?.quality)).subscribe(new me("quality")),this.info.currentBuffer$.subscribe(new me("buffer")),e.isBuffering$.subscribe(new me("isBuffering"))].forEach(t=>this.subscription.add(t)),fr("codecs",ff())}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:i,videoBitrate:a})=>!!i&&!!a),(0,p.filterChanged)((i,a)=>i.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,p.filter)(i=>i>0),(0,p.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,p.filter)(i=>i>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)(i=>i.end>0),(0,p.filterChanged)((i,a)=>i.end===a.end&&i.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:i,liveBufferTime:a})=>!!i&&!!a),(0,p.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(i=>i===!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)(i=>i===!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:i,rtt:a})=>!!i&&!!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)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=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||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,p.flattenObject)({quality:t,availableTracks:(0,p.flattenObject)(e),track:(0,p.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var ct=require("@vkontakte/videoplayer-shared"),_x=`@vkontakte/videoplayer-core@${Ls}`;
|
|
112
|
+
`;var Es=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let 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 Ts(this.params.fov,this.params.orientation),this.cameraRotationManager=new Is(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(lm,this.gl.VERTEX_SHADER),i=this.createShader(dm,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-i,n=t-a,o=e+i,c=t-a,u=e+i,d=t+a,l=e-i,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 ti=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("stopped");this.elementSize$=new q.ValueSubject(void 0);this.textTracksManager=new Ve;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 mr;this.audioTrackSwitchHistory=new mr;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&i?.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()):i?.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()):i?.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()):i?.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 Es(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ys({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,i=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:i,genericErrorListener:s,connect:(o,c)=>this.subscription.add(o.subscribe(c,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,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$:i.playing$,pause$:i.pause$,tracks:u})})),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.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(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(st(this.video,t.isLooped,a)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,a)),s((0,q.observeElementSize)(this.video),this.elementSize$),s(_e(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},a)).add(i.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(Wo(f));let b=[];for(let g of f.representations){let y=rm(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(Yo(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)}if(this.params.output.availableVideoStreams$.next(l),this.textTracksManager)for(let p of d.text)for(let f of p.representations){let b=am(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&&this.textTracksMap.size&&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(Yo(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(Wo(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,i=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=ot(this.video.buffered,this.video.currentTime*1e3),p=i?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&&!i)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=i?E??n:n??E,x;this.params.tuning.useSeparateAudioVideoABR?x=g&&rf(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 I=this.videoTracksMap.get(C)?.representation,P=x&&this.audioTracksMap.get(x)?.representation;if(I&&P)return[I,P];if(I&&!P&&this.audioTracksMap.size===0)return[I,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 Jr=class extends ti{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ii=require("@vkontakte/videoplayer-shared");var Xr=class extends ti{constructor(e){super(e),this.liveOffset=new gt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,ii.combine)({interval:(0,ii.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,ii.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ii.map)(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=sm(a);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="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=Ye(ts(),1);var j=require("@vkontakte/videoplayer-shared"),Ze={};var Vi=(r,e)=>new j.Observable(t=>{let i=(a,s)=>t.next(s);return r.on(e,i),()=>r.off(e,i)}),Zr=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new H("initializing");this.textTracksManager=new Ve;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.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},i=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(i),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,i=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,i));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,i)),this.subscription.add(Te(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Oe(this.video,e.playbackRate,a.playbackRateState$,i)),s(_e(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,j.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Vi(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")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(e.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Vi(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(Vi(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(Vi(this.hls,Ze.Events.LEVEL_LOADING).pipe((0,j.map)(({url:u})=>ue(u))),t.hostname$),s(Vi(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:i}));let n=u=>Array.from(this.trackLevels.values()).find(({level:d})=>d===u)?.track,o=Vi(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$,i),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:i})),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,i))}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",Ko=async r=>{let e=await yt(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(hm)?parseInt(e.headers.get(hm),10):void 0};var U=require("@vkontakte/videoplayer-shared");var Xo=Ye($n(),1);var xs=require("@vkontakte/videoplayer-shared");var Mx=r=>{let e=null;if(r.QUALITY&&(e=Ct(r.QUALITY)),!e&&r.RESOLUTION){let[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,xs.videoSizeToQuality)({width:t,height:i})}return e??null},Cx=(r,e)=>{let t=r.split(`
|
|
113
|
+
`),i=[],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,Xo.default)(o[1].split(",").map(y=>y.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,l=Mx(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&&i.push({id:d,quality:l,url:g,bandwidth:p,size:b,fps:f})}if(c){let u=(0,Xo.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(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},Dx=r=>new Promise(e=>{setTimeout(()=>{e()},r)}),Jo=0,fm=async(r,e=r,t)=>{let a=await(await yt(r)).text();Jo+=1;try{let{qualityManifests:s,textTracks:n}=Cx(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Jo<=t.manifestRetryMaxCount)return await Dx((0,xs.getExponentialDelay)(Jo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),fm(r,e,t)}return{qualityManifests:[],textTracks:[]}},Ps=fm;var ea=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new H("stopped");this.textTracksManager=new Ve;this.manifests$=new U.ValueSubject([]);this.liveOffset=new gt;this.manifestStartTime$=new U.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=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(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else 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},Ps(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new U.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=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,i));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),i)),this.subscription.add(Te(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Oe(this.video,t.playbackRate,a.playbackRateState$,i)),s(_e(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")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe((0,U.filterChanged)(),(0,U.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),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)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),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),i)),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$,i));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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.selectManifest();if((0,U.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:c}=t?.to??i??{};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(),Ko(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();Ko(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,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/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 Ve;this.manifests$=new W.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=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(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":i==="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),Ps(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:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:W.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=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,i)),this.subscription.add(Te(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Oe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).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)},i))),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$,i)),!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"},i))}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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.selectManifest();if((0,W.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};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 ia=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new Ve;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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(i?.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()):i?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.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,i],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),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,i=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,i));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,i)),this.subscription.add(Te(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Oe(this.video,t.playbackRate,a.playbackRateState$,i)),s(_e(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).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()},i)),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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,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=Wr(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,i=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&&(i=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:i})}};var Z=require("@vkontakte/videoplayer-shared");var bm=require("@vkontakte/videoplayer-shared"),mm=["stun:videostun.mycdn.me:80"],Bx=1e3,Ox=3,Zo=()=>null,As=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=Zo;this.externalStopCallback=Zo;this.externalErrorCallback=Zo;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls: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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Bx)}normalizeOptions(e={}){let t={stunServerList:mm,maxRetryNumber:Ox,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ra=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(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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()):i?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.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 As(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ye(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category: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,i));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(_e(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")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Te(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,Z.assertNever)(n.to)}},i)).add((0,Z.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(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=r=>new Pt.Observable(e=>{let t=new Pt.Subscription,i=r.desiredPlaybackState$.stateChangeStarted$.pipe((0,Pt.map)(({from:u,to:d})=>`${u}-${d}`)),a=r.desiredPlaybackState$.stateChangeEnded$,s=r.providerChanged$.pipe((0,Pt.map)(({type:u})=>u!==void 0)),n=new Pt.Subject,o=0,c="unknown";return t.add(i.subscribe(u=>{o&&window.clearTimeout(o),c=u,o=window.setTimeout(()=>n.next(u),r.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),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var $e=require("@vkontakte/videoplayer-shared");var sa=null,ks=null;function eu(){return sa||(sa=new(window.AudioContext||window.webkitAudioContext)),ks||(ks=new GainNode(sa,{gain:1}),ks.connect(sa.destination)),{audioCtx:sa,gainNode:ks}}var Sm=require("@vkontakte/videoplayer-shared");var na=class r{constructor(e,t,i,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=a;this.subscriptions=new $e.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe((0,$e.filter)(n=>!!n.type),(0,$e.once)()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){Sm.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,$e.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,$e.filter)(({playbackState:t,video:i,volume:{muted:a,volume:s}})=>t==="playing"&&!!i&&!a&&!!s),(0,$e.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:i,gainNode:a}=eu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,i.resume().then(()=>{if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${r.errorId} destroyed`);a.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(a)}catch(n){this.volumeMultiplierError$.next({id:r.errorId,category:$e.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:r.errorId,category:$e.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=eu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var Vx={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=mf([...gf(this.params.tuning),...bf(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,v.isNonNullable)(e.sources[o])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning,s=[];i?s=[i]: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=[...Mo(!0),...Mo(!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 i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}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,i=this.params.desiredState.seekState.getState(),a=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?i.position:t,forcePrecise:a?i.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:i,desiredState:a}=this.params,s=this.providerOutput,n={container:i,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 Jr({...n,source:o,sourceHls:c})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Xr({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),wi||!this.params.tuning.useHlsJs?new ta({...n,source:o}):new Zr({...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 ia({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new of({...n,source:o,config:{...Vx,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ra({container:i,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:i,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,v.assertNonNullable)(o),new pr({connection:o,meta:s,container:i,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 i=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:i(e.url)}}return(0,vm.default)(Object.entries(e).map(([a,s])=>[a,i(s)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,i=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=i<this.params.tuning.providerErrorLimit&&!c,l=u&&!c&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:c,haveFailoverHost:u,tryFailover:l,canReinitProvider:d},this.params.tuning.useNewProviderReinitLogic?d?(i++,this.reinitProvider()):l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN"):l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",(0,v.flattenObject)(n))})),e}};var _=require("@vkontakte/videoplayer-shared");var _x=5e3,ym="one_video_throughput",Tm="one_video_rtt",ua=window.navigator.connection,Im=()=>{let r=ua?.downlink;if((0,_.isNonNullable)(r)&&r!==10)return r*1e3},Em=()=>{let r=ua?.rtt;if((0,_.isNonNullable)(r)&&r!==3e3)return r},xm=(r,e,t)=>{let i=t*8,a=i/r;return i/(a+e)},tu=class r{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=r.load(ym)||(e.useBrowserEstimation?Im():void 0)||_x,i=r.load(Tm)??(e.useBrowserEstimation?Em():void 0)??0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(i),this.rttAdjustedThroughput$=new _.ValueSubject(xm(t,i,e.rttPenaltyRequestSize)),this.throughput=ei.getSmoothedValue(t,-1,e),this.rtt=ei.getSmoothedValue(i,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,i=(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,i=(0,_.now)()}));break;case 1:case 0:a.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(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-i;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let a=0,s=(0,_.now)(),n=0,o=(0,_.now)(),c=d=>{this.concurrentDownloads.delete(e),i.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 i?.read().then(u,c)}};this.concurrentDownloads.add(e),i?.read().then(u,c)}addRawSpeed(e,t,i=1,a=!1){if(r.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return parseInt(t,10)??void 0}},Pm=tu;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,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance: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,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,useNewProviderReinitLogic:!1,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=r=>({...(0,ca.fillWithDefault)(r,Am),configName:[...r.configName??[],...Am.configName]});var h=require("@vkontakte/videoplayer-shared");var At=require("@vkontakte/videoplayer-shared"),iu=({seekState:r,position$:e})=>(0,At.merge)(r.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)(()=>r.getState().state==="none")));var wm=require("@vkontakte/videoplayer-shared"),Rm=r=>{let e=typeof r.container=="string"?document.getElementById(r.container):r.container;return(0,wm.assertNonNullable)(e,`Wrong container or containerId {${r.container}}`),e};var ws=require("@vkontakte/videoplayer-shared"),Lm=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,ws.filter)(a=>a.length>0),(0,ws.once)()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};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:Jh};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:(i,a,s)=>{let n=Reflect.get(i,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,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,...i}=e;return this.tracer.log("initVideo",(0,h.flattenObject)(i)),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&&!vr()?(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 i=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=i&&!a&&(s=i-.1),this.tracer.log("seekTime",{duration:i,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)(i=>i.length>0),(0,h.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,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 Lm(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 i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.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 i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let a=i.getCameraRotation(),s=i.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(),i=t.state==="none"?void 0:t.position;return(0,h.isNonNullable)(i)?i/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((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||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 i=new h.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.filter)(({to:n})=>n==="playing"),(0,h.once)()).subscribe(()=>i.next(!1)));let a=0,s=(0,h.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,h.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.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)((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,h.filter)(i=>i.length>0),(0,h.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t,i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:a})=>a===i),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),Kh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>zh(t)),this.providerContainer.current$.subscribe(({type:t})=>fr("provider",t)),e.duration$.subscribe(t=>fr("duration",t)),e.availableVideoTracks$.pipe((0,h.filter)(t=>!!t.length),(0,h.once)()).subscribe(t=>fr("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)),fr("codecs",ff())}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:i,videoBitrate:a})=>!!i&&!!a),(0,h.filterChanged)((i,a)=>i.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,h.filter)(i=>i>0),(0,h.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,h.filter)(i=>i>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)(i=>i.end>0),(0,h.filterChanged)((i,a)=>i.end===a.end&&i.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:i,liveBufferTime:a})=>!!i&&!!a),(0,h.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,h.filterChanged)(),(0,h.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,h.filterChanged)(),(0,h.filter)(i=>i===!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)(i=>i===!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:i,rtt:a})=>!!i&&!!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)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=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||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,h.flattenObject)({quality:t,availableTracks:(0,h.flattenObject)(e),track:(0,h.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var ct=require("@vkontakte/videoplayer-shared"),Nx=`@vkontakte/videoplayer-core@${Ls}`;
|