@vkontakte/videoplayer-core 2.0.115-dev.4b123642.0 → 2.0.115-dev.c6f77ae4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.esm.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.115-dev.4b123642.0
3
- * Fri, 18 Oct 2024 08:57:16 GMT
2
+ * @vkontakte/videoplayer-core v2.0.115-dev.c6f77ae4.0
3
+ * Mon, 21 Oct 2024 12:29:46 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-115/doc/
5
5
  */
6
- var Gg=Object.create;var Ju=Object.defineProperty;var Wg=Object.getOwnPropertyDescriptor;var Qg=Object.getOwnPropertyNames;var Yg=Object.getPrototypeOf,zg=Object.prototype.hasOwnProperty;var f=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Kg=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Qg(e))!zg.call(r,a)&&a!==t&&Ju(r,a,{get:()=>e[a],enumerable:!(i=Wg(e,a))||i.enumerable});return r};var Ye=(r,e,t)=>(t=r!=null?Gg(Yg(r)):{},Kg(e||!r||!r.__esModule?Ju(t,"default",{value:r,enumerable:!0}):t,r));var ve=f((KR,sl)=>{"use strict";sl.exports=function(r){try{return!!r()}catch{return!0}}});var Fi=f((JR,nl)=>{"use strict";var aS=ve();nl.exports=!aS(function(){var r=function(){}.bind();return typeof r!="function"||r.hasOwnProperty("prototype")})});var ne=f((XR,ll)=>{"use strict";var ol=Fi(),ul=Function.prototype,en=ul.call,sS=ol&&ul.bind.bind(en,en);ll.exports=ol?sS:function(r){return function(){return en.apply(r,arguments)}}});var ri=f((ZR,dl)=>{"use strict";var cl=ne(),nS=cl({}.toString),oS=cl("".slice);dl.exports=function(r){return oS(nS(r),8,-1)}});var hl=f((e$,pl)=>{"use strict";var uS=ne(),lS=ve(),cS=ri(),tn=Object,dS=uS("".split);pl.exports=lS(function(){return!tn("z").propertyIsEnumerable(0)})?function(r){return cS(r)==="String"?dS(r,""):tn(r)}:tn});var ai=f((t$,fl)=>{"use strict";fl.exports=function(r){return r==null}});var qi=f((i$,ml)=>{"use strict";var pS=ai(),hS=TypeError;ml.exports=function(r){if(pS(r))throw new hS("Can't call method on "+r);return r}});var si=f((r$,bl)=>{"use strict";var fS=hl(),mS=qi();bl.exports=function(r){return fS(mS(r))}});var rn=f((a$,gl)=>{"use strict";gl.exports=function(){}});var Mt=f((s$,Sl)=>{"use strict";Sl.exports={}});var j=f((an,vl)=>{"use strict";var Ui=function(r){return r&&r.Math===Math&&r};vl.exports=Ui(typeof globalThis=="object"&&globalThis)||Ui(typeof window=="object"&&window)||Ui(typeof self=="object"&&self)||Ui(typeof global=="object"&&global)||Ui(typeof an=="object"&&an)||function(){return this}()||Function("return this")()});var U=f((n$,yl)=>{"use strict";var sn=typeof document=="object"&&document.all;yl.exports=typeof sn>"u"&&sn!==void 0?function(r){return typeof r=="function"||r===sn}:function(r){return typeof r=="function"}});var El=f((o$,Il)=>{"use strict";var bS=j(),gS=U(),Tl=bS.WeakMap;Il.exports=gS(Tl)&&/native code/.test(String(Tl))});var xe=f((u$,xl)=>{"use strict";var SS=U();xl.exports=function(r){return typeof r=="object"?r!==null:SS(r)}});var Pe=f((l$,Pl)=>{"use strict";var vS=ve();Pl.exports=!vS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Pa=f((c$,kl)=>{"use strict";var yS=j(),Al=xe(),nn=yS.document,TS=Al(nn)&&Al(nn.createElement);kl.exports=function(r){return TS?nn.createElement(r):{}}});var on=f((d$,wl)=>{"use strict";var IS=Pe(),ES=ve(),xS=Pa();wl.exports=!IS&&!ES(function(){return Object.defineProperty(xS("div"),"a",{get:function(){return 7}}).a!==7})});var un=f((p$,Rl)=>{"use strict";var PS=Pe(),AS=ve();Rl.exports=PS&&AS(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=f((h$,$l)=>{"use strict";var kS=xe(),wS=String,RS=TypeError;$l.exports=function(r){if(kS(r))return r;throw new RS(wS(r)+" is not an object")}});var ye=f((f$,Ll)=>{"use strict";var $S=Fi(),Aa=Function.prototype.call;Ll.exports=$S?Aa.bind(Aa):function(){return Aa.apply(Aa,arguments)}});var ka=f((m$,Ml)=>{"use strict";Ml.exports={}});var it=f((b$,Dl)=>{"use strict";var ln=ka(),cn=j(),LS=U(),Cl=function(r){return LS(r)?r:void 0};Dl.exports=function(r,e){return arguments.length<2?Cl(ln[r])||Cl(cn[r]):ln[r]&&ln[r][e]||cn[r]&&cn[r][e]}});var Hi=f((g$,Bl)=>{"use strict";var MS=ne();Bl.exports=MS({}.isPrototypeOf)});var ni=f((S$,_l)=>{"use strict";var CS=j(),Ol=CS.navigator,Vl=Ol&&Ol.userAgent;_l.exports=Vl?String(Vl):""});var pn=f((v$,jl)=>{"use strict";var Hl=j(),dn=ni(),Nl=Hl.process,Fl=Hl.Deno,ql=Nl&&Nl.versions||Fl&&Fl.version,Ul=ql&&ql.v8,_e,wa;Ul&&(_e=Ul.split("."),wa=_e[0]>0&&_e[0]<4?1:+(_e[0]+_e[1]));!wa&&dn&&(_e=dn.match(/Edge\/(\d+)/),(!_e||_e[1]>=74)&&(_e=dn.match(/Chrome\/(\d+)/),_e&&(wa=+_e[1])));jl.exports=wa});var hn=f((y$,Wl)=>{"use strict";var Gl=pn(),DS=ve(),BS=j(),OS=BS.String;Wl.exports=!!Object.getOwnPropertySymbols&&!DS(function(){var r=Symbol("symbol detection");return!OS(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&Gl&&Gl<41})});var fn=f((T$,Ql)=>{"use strict";var VS=hn();Ql.exports=VS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mn=f((I$,Yl)=>{"use strict";var _S=it(),NS=U(),FS=Hi(),qS=fn(),US=Object;Yl.exports=qS?function(r){return typeof r=="symbol"}:function(r){var e=_S("Symbol");return NS(e)&&FS(e.prototype,US(r))}});var ji=f((E$,zl)=>{"use strict";var HS=String;zl.exports=function(r){try{return HS(r)}catch{return"Object"}}});var rt=f((x$,Kl)=>{"use strict";var jS=U(),GS=ji(),WS=TypeError;Kl.exports=function(r){if(jS(r))return r;throw new WS(GS(r)+" is not a function")}});var Gi=f((P$,Jl)=>{"use strict";var QS=rt(),YS=ai();Jl.exports=function(r,e){var t=r[e];return YS(t)?void 0:QS(t)}});var Zl=f((A$,Xl)=>{"use strict";var bn=ye(),gn=U(),Sn=xe(),zS=TypeError;Xl.exports=function(r,e){var t,i;if(e==="string"&&gn(t=r.toString)&&!Sn(i=bn(t,r))||gn(t=r.valueOf)&&!Sn(i=bn(t,r))||e!=="string"&&gn(t=r.toString)&&!Sn(i=bn(t,r)))return i;throw new zS("Can't convert object to primitive value")}});var Ne=f((k$,ec)=>{"use strict";ec.exports=!0});var rc=f((w$,ic)=>{"use strict";var tc=j(),KS=Object.defineProperty;ic.exports=function(r,e){try{KS(tc,r,{value:e,configurable:!0,writable:!0})}catch{tc[r]=e}return e}});var Wi=f((R$,nc)=>{"use strict";var JS=Ne(),XS=j(),ZS=rc(),ac="__core-js_shared__",sc=nc.exports=XS[ac]||ZS(ac,{});(sc.versions||(sc.versions=[])).push({version:"3.38.0",mode:JS?"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 vn=f(($$,uc)=>{"use strict";var oc=Wi();uc.exports=function(r,e){return oc[r]||(oc[r]=e||{})}});var Qi=f((L$,lc)=>{"use strict";var ev=qi(),tv=Object;lc.exports=function(r){return tv(ev(r))}});var Fe=f((M$,cc)=>{"use strict";var iv=ne(),rv=Qi(),av=iv({}.hasOwnProperty);cc.exports=Object.hasOwn||function(e,t){return av(rv(e),t)}});var yn=f((C$,dc)=>{"use strict";var sv=ne(),nv=0,ov=Math.random(),uv=sv(1 .toString);dc.exports=function(r){return"Symbol("+(r===void 0?"":r)+")_"+uv(++nv+ov,36)}});var ie=f((D$,hc)=>{"use strict";var lv=j(),cv=vn(),pc=Fe(),dv=yn(),pv=hn(),hv=fn(),oi=lv.Symbol,Tn=cv("wks"),fv=hv?oi.for||oi:oi&&oi.withoutSetter||dv;hc.exports=function(r){return pc(Tn,r)||(Tn[r]=pv&&pc(oi,r)?oi[r]:fv("Symbol."+r)),Tn[r]}});var gc=f((B$,bc)=>{"use strict";var mv=ye(),fc=xe(),mc=mn(),bv=Gi(),gv=Zl(),Sv=ie(),vv=TypeError,yv=Sv("toPrimitive");bc.exports=function(r,e){if(!fc(r)||mc(r))return r;var t=bv(r,yv),i;if(t){if(e===void 0&&(e="default"),i=mv(t,r,e),!fc(i)||mc(i))return i;throw new vv("Can't convert object to primitive value")}return e===void 0&&(e="number"),gv(r,e)}});var In=f((O$,Sc)=>{"use strict";var Tv=gc(),Iv=mn();Sc.exports=function(r){var e=Tv(r,"string");return Iv(e)?e:e+""}});var Ct=f(yc=>{"use strict";var Ev=Pe(),xv=on(),Pv=un(),Ra=ze(),vc=In(),Av=TypeError,En=Object.defineProperty,kv=Object.getOwnPropertyDescriptor,xn="enumerable",Pn="configurable",An="writable";yc.f=Ev?Pv?function(e,t,i){if(Ra(e),t=vc(t),Ra(i),typeof e=="function"&&t==="prototype"&&"value"in i&&An in i&&!i[An]){var a=kv(e,t);a&&a[An]&&(e[t]=i.value,i={configurable:Pn in i?i[Pn]:a[Pn],enumerable:xn in i?i[xn]:a[xn],writable:!1})}return En(e,t,i)}:En:function(e,t,i){if(Ra(e),t=vc(t),Ra(i),xv)try{return En(e,t,i)}catch{}if("get"in i||"set"in i)throw new Av("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Yi=f((_$,Tc)=>{"use strict";Tc.exports=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}}});var ui=f((N$,Ic)=>{"use strict";var wv=Pe(),Rv=Ct(),$v=Yi();Ic.exports=wv?function(r,e,t){return Rv.f(r,e,$v(1,t))}:function(r,e,t){return r[e]=t,r}});var $a=f((F$,xc)=>{"use strict";var Lv=vn(),Mv=yn(),Ec=Lv("keys");xc.exports=function(r){return Ec[r]||(Ec[r]=Mv(r))}});var La=f((q$,Pc)=>{"use strict";Pc.exports={}});var $n=f((U$,wc)=>{"use strict";var Cv=El(),kc=j(),Dv=xe(),Bv=ui(),kn=Fe(),wn=Wi(),Ov=$a(),Vv=La(),Ac="Object already initialized",Rn=kc.TypeError,_v=kc.WeakMap,Ma,zi,Ca,Nv=function(r){return Ca(r)?zi(r):Ma(r,{})},Fv=function(r){return function(e){var t;if(!Dv(e)||(t=zi(e)).type!==r)throw new Rn("Incompatible receiver, "+r+" required");return t}};Cv||wn.state?(qe=wn.state||(wn.state=new _v),qe.get=qe.get,qe.has=qe.has,qe.set=qe.set,Ma=function(r,e){if(qe.has(r))throw new Rn(Ac);return e.facade=r,qe.set(r,e),e},zi=function(r){return qe.get(r)||{}},Ca=function(r){return qe.has(r)}):(Dt=Ov("state"),Vv[Dt]=!0,Ma=function(r,e){if(kn(r,Dt))throw new Rn(Ac);return e.facade=r,Bv(r,Dt,e),e},zi=function(r){return kn(r,Dt)?r[Dt]:{}},Ca=function(r){return kn(r,Dt)});var qe,Dt;wc.exports={set:Ma,get:zi,has:Ca,enforce:Nv,getterFor:Fv}});var Ln=f((H$,Mc)=>{"use strict";var qv=Fi(),Lc=Function.prototype,Rc=Lc.apply,$c=Lc.call;Mc.exports=typeof Reflect=="object"&&Reflect.apply||(qv?$c.bind(Rc):function(){return $c.apply(Rc,arguments)})});var Mn=f((j$,Cc)=>{"use strict";var Uv=ri(),Hv=ne();Cc.exports=function(r){if(Uv(r)==="Function")return Hv(r)}});var Vc=f(Oc=>{"use strict";var Dc={}.propertyIsEnumerable,Bc=Object.getOwnPropertyDescriptor,jv=Bc&&!Dc.call({1:2},1);Oc.f=jv?function(e){var t=Bc(this,e);return!!t&&t.enumerable}:Dc});var Fc=f(Nc=>{"use strict";var Gv=Pe(),Wv=ye(),Qv=Vc(),Yv=Yi(),zv=si(),Kv=In(),Jv=Fe(),Xv=on(),_c=Object.getOwnPropertyDescriptor;Nc.f=Gv?_c:function(e,t){if(e=zv(e),t=Kv(t),Xv)try{return _c(e,t)}catch{}if(Jv(e,t))return Yv(!Wv(Qv.f,e,t),e[t])}});var Cn=f((Q$,qc)=>{"use strict";var Zv=ve(),ey=U(),ty=/#|\.prototype\./,Ki=function(r,e){var t=ry[iy(r)];return t===sy?!0:t===ay?!1:ey(e)?Zv(e):!!e},iy=Ki.normalize=function(r){return String(r).replace(ty,".").toLowerCase()},ry=Ki.data={},ay=Ki.NATIVE="N",sy=Ki.POLYFILL="P";qc.exports=Ki});var Ji=f((Y$,Hc)=>{"use strict";var Uc=Mn(),ny=rt(),oy=Fi(),uy=Uc(Uc.bind);Hc.exports=function(r,e){return ny(r),e===void 0?r:oy?uy(r,e):function(){return r.apply(e,arguments)}}});var Ae=f((z$,Gc)=>{"use strict";var Xi=j(),ly=Ln(),cy=Mn(),dy=U(),py=Fc().f,hy=Cn(),li=ka(),fy=Ji(),ci=ui(),jc=Fe();Wi();var my=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 ly(r,this,arguments)};return e.prototype=r.prototype,e};Gc.exports=function(r,e){var t=r.target,i=r.global,a=r.stat,s=r.proto,n=i?Xi:a?Xi[t]:Xi[t]&&Xi[t].prototype,o=i?li:li[t]||ci(li,t,{})[t],l=o.prototype,u,d,c,p,h,m,b,g,y;for(p in e)u=hy(i?p:t+(a?".":"#")+p,r.forced),d=!u&&n&&jc(n,p),m=o[p],d&&(r.dontCallGetSet?(y=py(n,p),b=y&&y.value):b=n[p]),h=d&&b?b:e[p],!(!u&&!s&&typeof m==typeof h)&&(r.bind&&d?g=fy(h,Xi):r.wrap&&d?g=my(h):s&&dy(h)?g=cy(h):g=h,(r.sham||h&&h.sham||m&&m.sham)&&ci(g,"sham",!0),ci(o,p,g),s&&(c=t+"Prototype",jc(li,c)||ci(li,c,{}),ci(li[c],p,h),r.real&&l&&(u||!l[p])&&ci(l,p,h)))}});var Yc=f((K$,Qc)=>{"use strict";var Dn=Pe(),by=Fe(),Wc=Function.prototype,gy=Dn&&Object.getOwnPropertyDescriptor,Bn=by(Wc,"name"),Sy=Bn&&function(){}.name==="something",vy=Bn&&(!Dn||Dn&&gy(Wc,"name").configurable);Qc.exports={EXISTS:Bn,PROPER:Sy,CONFIGURABLE:vy}});var Kc=f((J$,zc)=>{"use strict";var yy=Math.ceil,Ty=Math.floor;zc.exports=Math.trunc||function(e){var t=+e;return(t>0?Ty:yy)(t)}});var Da=f((X$,Jc)=>{"use strict";var Iy=Kc();Jc.exports=function(r){var e=+r;return e!==e||e===0?0:Iy(e)}});var Zc=f((Z$,Xc)=>{"use strict";var Ey=Da(),xy=Math.max,Py=Math.min;Xc.exports=function(r,e){var t=Ey(r);return t<0?xy(t+e,0):Py(t,e)}});var td=f((eL,ed)=>{"use strict";var Ay=Da(),ky=Math.min;ed.exports=function(r){var e=Ay(r);return e>0?ky(e,9007199254740991):0}});var Ba=f((tL,id)=>{"use strict";var wy=td();id.exports=function(r){return wy(r.length)}});var sd=f((iL,ad)=>{"use strict";var Ry=si(),$y=Zc(),Ly=Ba(),rd=function(r){return function(e,t,i){var a=Ry(e),s=Ly(a);if(s===0)return!r&&-1;var n=$y(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}};ad.exports={includes:rd(!0),indexOf:rd(!1)}});var ud=f((rL,od)=>{"use strict";var My=ne(),On=Fe(),Cy=si(),Dy=sd().indexOf,By=La(),nd=My([].push);od.exports=function(r,e){var t=Cy(r),i=0,a=[],s;for(s in t)!On(By,s)&&On(t,s)&&nd(a,s);for(;e.length>i;)On(t,s=e[i++])&&(~Dy(a,s)||nd(a,s));return a}});var Vn=f((aL,ld)=>{"use strict";ld.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var dd=f((sL,cd)=>{"use strict";var Oy=ud(),Vy=Vn();cd.exports=Object.keys||function(e){return Oy(e,Vy)}});var hd=f(pd=>{"use strict";var _y=Pe(),Ny=un(),Fy=Ct(),qy=ze(),Uy=si(),Hy=dd();pd.f=_y&&!Ny?Object.defineProperties:function(e,t){qy(e);for(var i=Uy(t),a=Hy(t),s=a.length,n=0,o;s>n;)Fy.f(e,o=a[n++],i[o]);return e}});var _n=f((oL,fd)=>{"use strict";var jy=it();fd.exports=jy("document","documentElement")});var Un=f((uL,Td)=>{"use strict";var Gy=ze(),Wy=hd(),md=Vn(),Qy=La(),Yy=_n(),zy=Pa(),Ky=$a(),bd=">",gd="<",Fn="prototype",qn="script",vd=Ky("IE_PROTO"),Nn=function(){},yd=function(r){return gd+qn+bd+r+gd+"/"+qn+bd},Sd=function(r){r.write(yd("")),r.close();var e=r.parentWindow.Object;return r=null,e},Jy=function(){var r=zy("iframe"),e="java"+qn+":",t;return r.style.display="none",Yy.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(yd("document.F=Object")),t.close(),t.F},Oa,Va=function(){try{Oa=new ActiveXObject("htmlfile")}catch{}Va=typeof document<"u"?document.domain&&Oa?Sd(Oa):Jy():Sd(Oa);for(var r=md.length;r--;)delete Va[Fn][md[r]];return Va()};Qy[vd]=!0;Td.exports=Object.create||function(e,t){var i;return e!==null?(Nn[Fn]=Gy(e),i=new Nn,Nn[Fn]=null,i[vd]=e):i=Va(),t===void 0?i:Wy.f(i,t)}});var Ed=f((lL,Id)=>{"use strict";var Xy=ve();Id.exports=!Xy(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype})});var jn=f((cL,Pd)=>{"use strict";var Zy=Fe(),eT=U(),tT=Qi(),iT=$a(),rT=Ed(),xd=iT("IE_PROTO"),Hn=Object,aT=Hn.prototype;Pd.exports=rT?Hn.getPrototypeOf:function(r){var e=tT(r);if(Zy(e,xd))return e[xd];var t=e.constructor;return eT(t)&&e instanceof t?t.prototype:e instanceof Hn?aT:null}});var di=f((dL,Ad)=>{"use strict";var sT=ui();Ad.exports=function(r,e,t,i){return i&&i.enumerable?r[e]=t:sT(r,e,t),r}});var Yn=f((pL,Rd)=>{"use strict";var nT=ve(),oT=U(),uT=xe(),lT=Un(),kd=jn(),cT=di(),dT=ie(),pT=Ne(),Qn=dT("iterator"),wd=!1,at,Gn,Wn;[].keys&&(Wn=[].keys(),"next"in Wn?(Gn=kd(kd(Wn)),Gn!==Object.prototype&&(at=Gn)):wd=!0);var hT=!uT(at)||nT(function(){var r={};return at[Qn].call(r)!==r});hT?at={}:pT&&(at=lT(at));oT(at[Qn])||cT(at,Qn,function(){return this});Rd.exports={IteratorPrototype:at,BUGGY_SAFARI_ITERATORS:wd}});var _a=f((hL,Ld)=>{"use strict";var fT=ie(),mT=fT("toStringTag"),$d={};$d[mT]="z";Ld.exports=String($d)==="[object z]"});var Zi=f((fL,Md)=>{"use strict";var bT=_a(),gT=U(),Na=ri(),ST=ie(),vT=ST("toStringTag"),yT=Object,TT=Na(function(){return arguments}())==="Arguments",IT=function(r,e){try{return r[e]}catch{}};Md.exports=bT?Na:function(r){var e,t,i;return r===void 0?"Undefined":r===null?"Null":typeof(t=IT(e=yT(r),vT))=="string"?t:TT?Na(e):(i=Na(e))==="Object"&&gT(e.callee)?"Arguments":i}});var Dd=f((mL,Cd)=>{"use strict";var ET=_a(),xT=Zi();Cd.exports=ET?{}.toString:function(){return"[object "+xT(this)+"]"}});var er=f((bL,Od)=>{"use strict";var PT=_a(),AT=Ct().f,kT=ui(),wT=Fe(),RT=Dd(),$T=ie(),Bd=$T("toStringTag");Od.exports=function(r,e,t,i){var a=t?r:r&&r.prototype;a&&(wT(a,Bd)||AT(a,Bd,{configurable:!0,value:e}),i&&!PT&&kT(a,"toString",RT))}});var _d=f((gL,Vd)=>{"use strict";var LT=Yn().IteratorPrototype,MT=Un(),CT=Yi(),DT=er(),BT=Mt(),OT=function(){return this};Vd.exports=function(r,e,t,i){var a=e+" Iterator";return r.prototype=MT(LT,{next:CT(+!i,t)}),DT(r,a,!1,!0),BT[a]=OT,r}});var Fd=f((SL,Nd)=>{"use strict";var VT=ne(),_T=rt();Nd.exports=function(r,e,t){try{return VT(_T(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}}});var Ud=f((vL,qd)=>{"use strict";var NT=xe();qd.exports=function(r){return NT(r)||r===null}});var jd=f((yL,Hd)=>{"use strict";var FT=Ud(),qT=String,UT=TypeError;Hd.exports=function(r){if(FT(r))return r;throw new UT("Can't set "+qT(r)+" as a prototype")}});var zn=f((TL,Gd)=>{"use strict";var HT=Fd(),jT=xe(),GT=qi(),WT=jd();Gd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=HT(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(a,s){return GT(a),WT(s),jT(a)&&(r?t(a,s):a.__proto__=s),a}}():void 0)});var ip=f((IL,tp)=>{"use strict";var QT=Ae(),YT=ye(),Fa=Ne(),Zd=Yc(),zT=U(),KT=_d(),Wd=jn(),Qd=zn(),JT=er(),XT=ui(),Kn=di(),ZT=ie(),Yd=Mt(),ep=Yn(),eI=Zd.PROPER,tI=Zd.CONFIGURABLE,zd=ep.IteratorPrototype,qa=ep.BUGGY_SAFARI_ITERATORS,tr=ZT("iterator"),Kd="keys",ir="values",Jd="entries",Xd=function(){return this};tp.exports=function(r,e,t,i,a,s,n){KT(t,e,i);var o=function(y){if(y===a&&p)return p;if(!qa&&y&&y in d)return d[y];switch(y){case Kd:return function(){return new t(this,y)};case ir:return function(){return new t(this,y)};case Jd:return function(){return new t(this,y)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,d=r.prototype,c=d[tr]||d["@@iterator"]||a&&d[a],p=!qa&&c||o(a),h=e==="Array"&&d.entries||c,m,b,g;if(h&&(m=Wd(h.call(new r)),m!==Object.prototype&&m.next&&(!Fa&&Wd(m)!==zd&&(Qd?Qd(m,zd):zT(m[tr])||Kn(m,tr,Xd)),JT(m,l,!0,!0),Fa&&(Yd[l]=Xd))),eI&&a===ir&&c&&c.name!==ir&&(!Fa&&tI?XT(d,"name",ir):(u=!0,p=function(){return YT(c,this)})),a)if(b={values:o(ir),keys:s?p:o(Kd),entries:o(Jd)},n)for(g in b)(qa||u||!(g in d))&&Kn(d,g,b[g]);else QT({target:e,proto:!0,forced:qa||u},b);return(!Fa||n)&&d[tr]!==p&&Kn(d,tr,p,{name:a}),Yd[e]=p,b}});var ap=f((EL,rp)=>{"use strict";rp.exports=function(r,e){return{value:r,done:e}}});var Xn=f((xL,lp)=>{"use strict";var iI=si(),Jn=rn(),sp=Mt(),op=$n(),rI=Ct().f,aI=ip(),Ua=ap(),sI=Ne(),nI=Pe(),up="Array Iterator",oI=op.set,uI=op.getterFor(up);lp.exports=aI(Array,"Array",function(r,e){oI(this,{type:up,target:iI(r),index:0,kind:e})},function(){var r=uI(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=void 0,Ua(void 0,!0);switch(r.kind){case"keys":return Ua(t,!1);case"values":return Ua(e[t],!1)}return Ua([t,e[t]],!1)},"values");var np=sp.Arguments=sp.Array;Jn("keys");Jn("values");Jn("entries");if(!sI&&nI&&np.name!=="values")try{rI(np,"name",{value:"values"})}catch{}});var dp=f((PL,cp)=>{"use strict";var lI=ie(),cI=Mt(),dI=lI("iterator"),pI=Array.prototype;cp.exports=function(r){return r!==void 0&&(cI.Array===r||pI[dI]===r)}});var Zn=f((AL,hp)=>{"use strict";var hI=Zi(),pp=Gi(),fI=ai(),mI=Mt(),bI=ie(),gI=bI("iterator");hp.exports=function(r){if(!fI(r))return pp(r,gI)||pp(r,"@@iterator")||mI[hI(r)]}});var mp=f((kL,fp)=>{"use strict";var SI=ye(),vI=rt(),yI=ze(),TI=ji(),II=Zn(),EI=TypeError;fp.exports=function(r,e){var t=arguments.length<2?II(r):e;if(vI(t))return yI(SI(t,r));throw new EI(TI(r)+" is not iterable")}});var Sp=f((wL,gp)=>{"use strict";var xI=ye(),bp=ze(),PI=Gi();gp.exports=function(r,e,t){var i,a;bp(r);try{if(i=PI(r,"return"),!i){if(e==="throw")throw t;return t}i=xI(i,r)}catch(s){a=!0,i=s}if(e==="throw")throw t;if(a)throw i;return bp(i),t}});var ja=f((RL,Ip)=>{"use strict";var AI=Ji(),kI=ye(),wI=ze(),RI=ji(),$I=dp(),LI=Ba(),vp=Hi(),MI=mp(),CI=Zn(),yp=Sp(),DI=TypeError,Ha=function(r,e){this.stopped=r,this.result=e},Tp=Ha.prototype;Ip.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),l=AI(e,i),u,d,c,p,h,m,b,g=function(A){return u&&yp(u,"normal",A),new Ha(!0,A)},y=function(A){return a?(wI(A),o?l(A[0],A[1],g):l(A[0],A[1])):o?l(A,g):l(A)};if(s)u=r.iterator;else if(n)u=r;else{if(d=CI(r),!d)throw new DI(RI(r)+" is not iterable");if($I(d)){for(c=0,p=LI(r);p>c;c++)if(h=y(r[c]),h&&vp(Tp,h))return h;return new Ha(!1)}u=MI(r,d)}for(m=s?r.next:u.next;!(b=kI(m,u)).done;){try{h=y(b.value)}catch(A){yp(u,"throw",A)}if(typeof h=="object"&&h&&vp(Tp,h))return h}return new Ha(!1)}});var xp=f(($L,Ep)=>{"use strict";var BI=Pe(),OI=Ct(),VI=Yi();Ep.exports=function(r,e,t){BI?OI.f(r,e,VI(0,t)):r[e]=t}});var Pp=f(()=>{"use strict";var _I=Ae(),NI=ja(),FI=xp();_I({target:"Object",stat:!0},{fromEntries:function(e){var t={};return NI(e,function(i,a){FI(t,i,a)},{AS_ENTRIES:!0}),t}})});var kp=f((CL,Ap)=>{"use strict";Xn();Pp();var qI=ka();Ap.exports=qI.Object.fromEntries});var Rp=f((DL,wp)=>{"use strict";wp.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 Lp=f(()=>{"use strict";Xn();var UI=Rp(),HI=j(),jI=er(),$p=Mt();for(Ga in UI)jI(HI[Ga],Ga),$p[Ga]=$p.Array;var Ga});var Cp=f((VL,Mp)=>{"use strict";var GI=kp();Lp();Mp.exports=GI});var eo=f((_L,Dp)=>{"use strict";var WI=Cp();Dp.exports=WI});var Bp=f(()=>{"use strict"});var to=f((qL,Op)=>{"use strict";var rr=j(),QI=ni(),YI=ri(),Wa=function(r){return QI.slice(0,r.length)===r};Op.exports=function(){return Wa("Bun/")?"BUN":Wa("Cloudflare-Workers")?"CLOUDFLARE":Wa("Deno/")?"DENO":Wa("Node.js/")?"NODE":rr.Bun&&typeof Bun.version=="string"?"BUN":rr.Deno&&typeof Deno.version=="object"?"DENO":YI(rr.process)==="process"?"NODE":rr.window&&rr.document?"BROWSER":"REST"}()});var Qa=f((UL,Vp)=>{"use strict";var zI=to();Vp.exports=zI==="NODE"});var Np=f((HL,_p)=>{"use strict";var KI=Ct();_p.exports=function(r,e,t){return KI.f(r,e,t)}});var Up=f((jL,qp)=>{"use strict";var JI=it(),XI=Np(),ZI=ie(),eE=Pe(),Fp=ZI("species");qp.exports=function(r){var e=JI(r);eE&&e&&!e[Fp]&&XI(e,Fp,{configurable:!0,get:function(){return this}})}});var jp=f((GL,Hp)=>{"use strict";var tE=Hi(),iE=TypeError;Hp.exports=function(r,e){if(tE(e,r))return r;throw new iE("Incorrect invocation")}});var ro=f((WL,Gp)=>{"use strict";var rE=ne(),aE=U(),io=Wi(),sE=rE(Function.toString);aE(io.inspectSource)||(io.inspectSource=function(r){return sE(r)});Gp.exports=io.inspectSource});var Jp=f((QL,Kp)=>{"use strict";var nE=ne(),oE=ve(),Wp=U(),uE=Zi(),lE=it(),cE=ro(),Qp=function(){},Yp=lE("Reflect","construct"),ao=/^\s*(?:class|function)\b/,dE=nE(ao.exec),pE=!ao.test(Qp),ar=function(e){if(!Wp(e))return!1;try{return Yp(Qp,[],e),!0}catch{return!1}},zp=function(e){if(!Wp(e))return!1;switch(uE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return pE||!!dE(ao,cE(e))}catch{return!0}};zp.sham=!0;Kp.exports=!Yp||oE(function(){var r;return ar(ar.call)||!ar(Object)||!ar(function(){r=!0})||r})?zp:ar});var Zp=f((YL,Xp)=>{"use strict";var hE=Jp(),fE=ji(),mE=TypeError;Xp.exports=function(r){if(hE(r))return r;throw new mE(fE(r)+" is not a constructor")}});var so=f((zL,th)=>{"use strict";var eh=ze(),bE=Zp(),gE=ai(),SE=ie(),vE=SE("species");th.exports=function(r,e){var t=eh(r).constructor,i;return t===void 0||gE(i=eh(t)[vE])?e:bE(i)}});var rh=f((KL,ih)=>{"use strict";var yE=ne();ih.exports=yE([].slice)});var sh=f((JL,ah)=>{"use strict";var TE=TypeError;ah.exports=function(r,e){if(r<e)throw new TE("Not enough arguments");return r}});var no=f((XL,nh)=>{"use strict";var IE=ni();nh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(IE)});var bo=f((ZL,mh)=>{"use strict";var Te=j(),EE=Ln(),xE=Ji(),oh=U(),PE=Fe(),fh=ve(),uh=_n(),AE=rh(),lh=Pa(),kE=sh(),wE=no(),RE=Qa(),ho=Te.setImmediate,fo=Te.clearImmediate,$E=Te.process,oo=Te.Dispatch,LE=Te.Function,ch=Te.MessageChannel,ME=Te.String,uo=0,sr={},dh="onreadystatechange",nr,Bt,lo,co;fh(function(){nr=Te.location});var mo=function(r){if(PE(sr,r)){var e=sr[r];delete sr[r],e()}},po=function(r){return function(){mo(r)}},ph=function(r){mo(r.data)},hh=function(r){Te.postMessage(ME(r),nr.protocol+"//"+nr.host)};(!ho||!fo)&&(ho=function(e){kE(arguments.length,1);var t=oh(e)?e:LE(e),i=AE(arguments,1);return sr[++uo]=function(){EE(t,void 0,i)},Bt(uo),uo},fo=function(e){delete sr[e]},RE?Bt=function(r){$E.nextTick(po(r))}:oo&&oo.now?Bt=function(r){oo.now(po(r))}:ch&&!wE?(lo=new ch,co=lo.port2,lo.port1.onmessage=ph,Bt=xE(co.postMessage,co)):Te.addEventListener&&oh(Te.postMessage)&&!Te.importScripts&&nr&&nr.protocol!=="file:"&&!fh(hh)?(Bt=hh,Te.addEventListener("message",ph,!1)):dh in lh("script")?Bt=function(r){uh.appendChild(lh("script"))[dh]=function(){uh.removeChild(this),mo(r)}}:Bt=function(r){setTimeout(po(r),0)});mh.exports={set:ho,clear:fo}});var Sh=f((eM,gh)=>{"use strict";var bh=j(),CE=Pe(),DE=Object.getOwnPropertyDescriptor;gh.exports=function(r){if(!CE)return bh[r];var e=DE(bh,r);return e&&e.value}});var go=f((tM,yh)=>{"use strict";var vh=function(){this.head=null,this.tail=null};vh.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}}};yh.exports=vh});var Ih=f((iM,Th)=>{"use strict";var BE=ni();Th.exports=/ipad|iphone|ipod/i.test(BE)&&typeof Pebble<"u"});var xh=f((rM,Eh)=>{"use strict";var OE=ni();Eh.exports=/web0s(?!.*chrome)/i.test(OE)});var Lh=f((aM,$h)=>{"use strict";var hi=j(),VE=Sh(),Ph=Ji(),So=bo().set,_E=go(),NE=no(),FE=Ih(),qE=xh(),vo=Qa(),Ah=hi.MutationObserver||hi.WebKitMutationObserver,kh=hi.document,wh=hi.process,Ya=hi.Promise,Io=VE("queueMicrotask"),pi,yo,To,za,Rh;Io||(or=new _E,ur=function(){var r,e;for(vo&&(r=wh.domain)&&r.exit();e=or.get();)try{e()}catch(t){throw or.head&&pi(),t}r&&r.enter()},!NE&&!vo&&!qE&&Ah&&kh?(yo=!0,To=kh.createTextNode(""),new Ah(ur).observe(To,{characterData:!0}),pi=function(){To.data=yo=!yo}):!FE&&Ya&&Ya.resolve?(za=Ya.resolve(void 0),za.constructor=Ya,Rh=Ph(za.then,za),pi=function(){Rh(ur)}):vo?pi=function(){wh.nextTick(ur)}:(So=Ph(So,hi),pi=function(){So(ur)}),Io=function(r){or.head||pi(),or.add(r)});var or,ur;$h.exports=Io});var Ch=f((sM,Mh)=>{"use strict";Mh.exports=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}}});var Ka=f((nM,Dh)=>{"use strict";Dh.exports=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}}});var Ot=f((oM,Bh)=>{"use strict";var UE=j();Bh.exports=UE.Promise});var fi=f((uM,Nh)=>{"use strict";var HE=j(),lr=Ot(),jE=U(),GE=Cn(),WE=ro(),QE=ie(),Oh=to(),YE=Ne(),Eo=pn(),Vh=lr&&lr.prototype,zE=QE("species"),xo=!1,_h=jE(HE.PromiseRejectionEvent),KE=GE("Promise",function(){var r=WE(lr),e=r!==String(lr);if(!e&&Eo===66||YE&&!(Vh.catch&&Vh.finally))return!0;if(!Eo||Eo<51||!/native code/.test(r)){var t=new lr(function(s){s(1)}),i=function(s){s(function(){},function(){})},a=t.constructor={};if(a[zE]=i,xo=t.then(function(){})instanceof i,!xo)return!0}return!e&&(Oh==="BROWSER"||Oh==="DENO")&&!_h});Nh.exports={CONSTRUCTOR:KE,REJECTION_EVENT:_h,SUBCLASSING:xo}});var mi=f((lM,qh)=>{"use strict";var Fh=rt(),JE=TypeError,XE=function(r){var e,t;this.promise=new r(function(i,a){if(e!==void 0||t!==void 0)throw new JE("Bad Promise constructor");e=i,t=a}),this.resolve=Fh(e),this.reject=Fh(t)};qh.exports.f=function(r){return new XE(r)}});var of=f(()=>{"use strict";var ZE=Ae(),ex=Ne(),es=Qa(),bt=j(),vi=ye(),Uh=di(),Hh=zn(),tx=er(),ix=Up(),rx=rt(),Za=U(),ax=xe(),sx=jp(),nx=so(),Yh=bo().set,Ro=Lh(),ox=Ch(),ux=Ka(),lx=go(),zh=$n(),ts=Ot(),$o=fi(),Kh=mi(),is="Promise",Jh=$o.CONSTRUCTOR,cx=$o.REJECTION_EVENT,dx=$o.SUBCLASSING,Po=zh.getterFor(is),px=zh.set,bi=ts&&ts.prototype,Vt=ts,Ja=bi,Xh=bt.TypeError,Ao=bt.document,Lo=bt.process,ko=Kh.f,hx=ko,fx=!!(Ao&&Ao.createEvent&&bt.dispatchEvent),Zh="unhandledrejection",mx="rejectionhandled",jh=0,ef=1,bx=2,Mo=1,tf=2,Xa,Gh,gx,Wh,rf=function(r){var e;return ax(r)&&Za(e=r.then)?e:!1},af=function(r,e){var t=e.value,i=e.state===ef,a=i?r.ok:r.fail,s=r.resolve,n=r.reject,o=r.domain,l,u,d;try{a?(i||(e.rejection===tf&&vx(e),e.rejection=Mo),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),d=!0)),l===r.promise?n(new Xh("Promise-chain cycle")):(u=rf(l))?vi(u,l,s,n):s(l)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},sf=function(r,e){r.notified||(r.notified=!0,Ro(function(){for(var t=r.reactions,i;i=t.get();)af(i,r);r.notified=!1,e&&!r.rejection&&Sx(r)}))},nf=function(r,e,t){var i,a;fx?(i=Ao.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(r,!1,!0),bt.dispatchEvent(i)):i={promise:e,reason:t},!cx&&(a=bt["on"+r])?a(i):r===Zh&&ox("Unhandled promise rejection",t)},Sx=function(r){vi(Yh,bt,function(){var e=r.facade,t=r.value,i=Qh(r),a;if(i&&(a=ux(function(){es?Lo.emit("unhandledRejection",t,e):nf(Zh,e,t)}),r.rejection=es||Qh(r)?tf:Mo,a.error))throw a.value})},Qh=function(r){return r.rejection!==Mo&&!r.parent},vx=function(r){vi(Yh,bt,function(){var e=r.facade;es?Lo.emit("rejectionHandled",e):nf(mx,e,r.value)})},gi=function(r,e,t){return function(i){r(e,i,t)}},Si=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=bx,sf(r,!0))},wo=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new Xh("Promise can't be resolved itself");var i=rf(e);i?Ro(function(){var a={done:!1};try{vi(i,e,gi(wo,a,r),gi(Si,a,r))}catch(s){Si(a,s,r)}}):(r.value=e,r.state=ef,sf(r,!1))}catch(a){Si({done:!1},a,r)}}};if(Jh&&(Vt=function(e){sx(this,Ja),rx(e),vi(Xa,this);var t=Po(this);try{e(gi(wo,t),gi(Si,t))}catch(i){Si(t,i)}},Ja=Vt.prototype,Xa=function(e){px(this,{type:is,done:!1,notified:!1,parent:!1,reactions:new lx,rejection:!1,state:jh,value:void 0})},Xa.prototype=Uh(Ja,"then",function(e,t){var i=Po(this),a=ko(nx(this,Vt));return i.parent=!0,a.ok=Za(e)?e:!0,a.fail=Za(t)&&t,a.domain=es?Lo.domain:void 0,i.state===jh?i.reactions.add(a):Ro(function(){af(a,i)}),a.promise}),Gh=function(){var r=new Xa,e=Po(r);this.promise=r,this.resolve=gi(wo,e),this.reject=gi(Si,e)},Kh.f=ko=function(r){return r===Vt||r===gx?new Gh(r):hx(r)},!ex&&Za(ts)&&bi!==Object.prototype)){Wh=bi.then,dx||Uh(bi,"then",function(e,t){var i=this;return new Vt(function(a,s){vi(Wh,i,a,s)}).then(e,t)},{unsafe:!0});try{delete bi.constructor}catch{}Hh&&Hh(bi,Ja)}ZE({global:!0,constructor:!0,wrap:!0,forced:Jh},{Promise:Vt});tx(Vt,is,!1,!0);ix(is)});var pf=f((pM,df)=>{"use strict";var yx=ie(),lf=yx("iterator"),cf=!1;try{uf=0,Co={next:function(){return{done:!!uf++}},return:function(){cf=!0}},Co[lf]=function(){return this},Array.from(Co,function(){throw 2})}catch{}var uf,Co;df.exports=function(r,e){try{if(!e&&!cf)return!1}catch{return!1}var t=!1;try{var i={};i[lf]=function(){return{next:function(){return{done:t=!0}}}},r(i)}catch{}return t}});var Do=f((hM,hf)=>{"use strict";var Tx=Ot(),Ix=pf(),Ex=fi().CONSTRUCTOR;hf.exports=Ex||!Ix(function(r){Tx.all(r).then(void 0,function(){})})});var ff=f(()=>{"use strict";var xx=Ae(),Px=ye(),Ax=rt(),kx=mi(),wx=Ka(),Rx=ja(),$x=Do();xx({target:"Promise",stat:!0,forced:$x},{all:function(e){var t=this,i=kx.f(t),a=i.resolve,s=i.reject,n=wx(function(){var o=Ax(t.resolve),l=[],u=0,d=1;Rx(e,function(c){var p=u++,h=!1;d++,Px(o,t,c).then(function(m){h||(h=!0,l[p]=m,--d||a(l))},s)}),--d||a(l)});return n.error&&s(n.value),i.promise}})});var bf=f(()=>{"use strict";var Lx=Ae(),Mx=Ne(),Cx=fi().CONSTRUCTOR,Oo=Ot(),Dx=it(),Bx=U(),Ox=di(),mf=Oo&&Oo.prototype;Lx({target:"Promise",proto:!0,forced:Cx,real:!0},{catch:function(r){return this.then(void 0,r)}});!Mx&&Bx(Oo)&&(Bo=Dx("Promise").prototype.catch,mf.catch!==Bo&&Ox(mf,"catch",Bo,{unsafe:!0}));var Bo});var gf=f(()=>{"use strict";var Vx=Ae(),_x=ye(),Nx=rt(),Fx=mi(),qx=Ka(),Ux=ja(),Hx=Do();Vx({target:"Promise",stat:!0,forced:Hx},{race:function(e){var t=this,i=Fx.f(t),a=i.reject,s=qx(function(){var n=Nx(t.resolve);Ux(e,function(o){_x(n,t,o).then(i.resolve,a)})});return s.error&&a(s.value),i.promise}})});var Sf=f(()=>{"use strict";var jx=Ae(),Gx=mi(),Wx=fi().CONSTRUCTOR;jx({target:"Promise",stat:!0,forced:Wx},{reject:function(e){var t=Gx.f(this),i=t.reject;return i(e),t.promise}})});var Vo=f((IM,vf)=>{"use strict";var Qx=ze(),Yx=xe(),zx=mi();vf.exports=function(r,e){if(Qx(r),Yx(e)&&e.constructor===r)return e;var t=zx.f(r),i=t.resolve;return i(e),t.promise}});var If=f(()=>{"use strict";var Kx=Ae(),Jx=it(),yf=Ne(),Xx=Ot(),Tf=fi().CONSTRUCTOR,Zx=Vo(),eP=Jx("Promise"),tP=yf&&!Tf;Kx({target:"Promise",stat:!0,forced:yf||Tf},{resolve:function(e){return Zx(tP&&this===eP?Xx:this,e)}})});var Ef=f(()=>{"use strict";of();ff();bf();gf();Sf();If()});var kf=f(()=>{"use strict";var iP=Ae(),rP=Ne(),rs=Ot(),aP=ve(),Pf=it(),Af=U(),sP=so(),xf=Vo(),nP=di(),No=rs&&rs.prototype,oP=!!rs&&aP(function(){No.finally.call({then:function(){}},function(){})});iP({target:"Promise",proto:!0,real:!0,forced:oP},{finally:function(r){var e=sP(this,Pf("Promise")),t=Af(r);return this.then(t?function(i){return xf(e,r()).then(function(){return i})}:r,t?function(i){return xf(e,r()).then(function(){throw i})}:r)}});!rP&&Af(rs)&&(_o=Pf("Promise").prototype.finally,No.finally!==_o&&nP(No,"finally",_o,{unsafe:!0}));var _o});var as=f((RM,wf)=>{"use strict";var uP=it();wf.exports=uP});var $f=f(($M,Rf)=>{"use strict";Bp();Ef();kf();var lP=as();Rf.exports=lP("Promise","finally")});var Mf=f((LM,Lf)=>{"use strict";var cP=$f();Lf.exports=cP});var ss=f((MM,Cf)=>{"use strict";var dP=Mf();Cf.exports=dP});var am=f(()=>{"use strict";var FP=Ae(),qP=Qi(),UP=Ba(),HP=Da(),jP=rn();FP({target:"Array",proto:!0},{at:function(e){var t=qP(this),i=UP(t),a=HP(e),s=a>=0?a:i+a;return s<0||s>=i?void 0:t[s]}});jP("at")});var nm=f((qC,sm)=>{"use strict";am();var GP=as();sm.exports=GP("Array","at")});var um=f((UC,om)=>{"use strict";var WP=nm();om.exports=WP});var hr=f((HC,lm)=>{"use strict";var QP=um();lm.exports=QP});var ab=f(()=>{"use strict"});var sb=f(()=>{"use strict"});var ob=f((jO,nb)=>{"use strict";var ek=xe(),tk=ri(),ik=ie(),rk=ik("match");nb.exports=function(r){var e;return ek(r)&&((e=r[rk])!==void 0?!!e:tk(r)==="RegExp")}});var lb=f((GO,ub)=>{"use strict";var ak=Zi(),sk=String;ub.exports=function(r){if(ak(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return sk(r)}});var db=f((WO,cb)=>{"use strict";var nk=ze();cb.exports=function(){var r=nk(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 fb=f((QO,hb)=>{"use strict";var ok=ye(),uk=Fe(),lk=Hi(),ck=db(),pb=RegExp.prototype;hb.exports=function(r){var e=r.flags;return e===void 0&&!("flags"in pb)&&!uk(r,"flags")&&lk(pb,r)?ok(ck,r):e}});var bb=f((YO,mb)=>{"use strict";var mu=ne(),dk=Qi(),pk=Math.floor,hu=mu("".charAt),hk=mu("".replace),fu=mu("".slice),fk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,mk=/\$([$&'`]|\d{1,2})/g;mb.exports=function(r,e,t,i,a,s){var n=t+r.length,o=i.length,l=mk;return a!==void 0&&(a=dk(a),l=fk),hk(s,l,function(u,d){var c;switch(hu(d,0)){case"$":return"$";case"&":return r;case"`":return fu(e,0,t);case"'":return fu(e,n);case"<":c=a[fu(d,1,-1)];break;default:var p=+d;if(p===0)return u;if(p>o){var h=pk(p/10);return h===0?u:h<=o?i[h-1]===void 0?hu(d,1):i[h-1]+hu(d,1):u}c=i[p-1]}return c===void 0?"":c})}});var vb=f(()=>{"use strict";var bk=Ae(),gk=ye(),gu=ne(),gb=qi(),Sk=U(),vk=ai(),yk=ob(),$i=lb(),Tk=Gi(),Ik=fb(),Ek=bb(),xk=ie(),Pk=Ne(),Ak=xk("replace"),kk=TypeError,bu=gu("".indexOf),wk=gu("".replace),Sb=gu("".slice),Rk=Math.max;bk({target:"String",proto:!0},{replaceAll:function(e,t){var i=gb(this),a,s,n,o,l,u,d,c,p,h,m=0,b="";if(!vk(e)){if(a=yk(e),a&&(s=$i(gb(Ik(e))),!~bu(s,"g")))throw new kk("`.replaceAll` does not allow non-global regexes");if(n=Tk(e,Ak),n)return gk(n,e,i,t);if(Pk&&a)return wk($i(i),e,t)}for(o=$i(i),l=$i(e),u=Sk(t),u||(t=$i(t)),d=l.length,c=Rk(1,d),p=bu(o,l);p!==-1;)h=u?$i(t(l,p,o)):Ek(l,o,p,[],void 0,t),b+=Sb(o,m,p)+h,m=p+d,p=p+c>o.length?-1:bu(o,l,p+c);return m<o.length&&(b+=Sb(o,m)),b}})});var Tb=f((JO,yb)=>{"use strict";ab();sb();vb();var $k=as();yb.exports=$k("String","replaceAll")});var Eb=f((XO,Ib)=>{"use strict";var Lk=Tb();Ib.exports=Lk});var Pb=f((ZO,xb)=>{"use strict";var Mk=Eb();xb.exports=Mk});var Xu="2.0.115-dev.4b123642.0";var se=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(se||{}),mt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(mt||{});var Ia=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ia||{}),Ks=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ks||{});var Js=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Js||{});import{assertNever as al,assertNonNullable as Jg,isNonNullable as Ea,ValueSubject as Xs,Subject as Xg,Subscription as Zg,merge as eS,observableFrom as tS,fromEvent as el,map as tl,tap as il,filterChanged as iS,isNullable as Zs,ErrorCategory as rl}from"@vkontakte/videoplayer-shared";var Zu=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 xa=class{constructor(e){this.connection$=new Xs(void 0);this.castState$=new Xs("NOT_AVAILABLE");this.errorEvent$=new Xg;this.realCastState$=new Xs("NOT_AVAILABLE");this.subscription=new Zg;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=Ea(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Zu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:rl.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(){Ea(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Zs(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Zs(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(el(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 al(a.sessionState)}})).add(eS(el(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(il(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),tl(a=>a.castState)),tS([i.getCastState()])).pipe(iS(),tl(rS),il(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Ea(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();Jg(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media?.contentId;(Zs(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?Ea(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:rl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},rS=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 al(r)}};var Ig=Ye(eo(),1);var Hf=Ye(ss(),1);import{assertNever as Df}from"@vkontakte/videoplayer-shared";var X=(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:Df(t)}return r},Fo=(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:Df(e)}};var E=(r,e,t=!1)=>{let i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};import{isNonNullable as pP,Subject as ns,merge as Bf}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new ns;this.transitionEnded$=new ns;this.transitionUpdated$=new ns;this.forceChanged$=new ns;this.stateChangeStarted$=Bf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Bf(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||pP(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as hP}from"@vkontakte/videoplayer-shared";var Of=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 hP(r)}};import{assertNever as yi,assertNonNullable as _t,debounce as Vf,ErrorCategory as _f,fromEvent as Nt,isNonNullable as Nf,map as Ff,merge as qf,observableFrom as fP,Subject as mP,Subscription as qo,timeout as bP,getHighestQuality as gP}from"@vkontakte/videoplayer-shared";var SP=5,vP=5,yP=500,Uf=7e3,cr=class{constructor(e){this.subscription=new qo;this.loadMediaTimeoutSubscription=new qo;this.videoState=new L("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:yi(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:yi(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:yi(e)}break}default:yi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Of(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 qo;this.subscription.add(e),this.subscription.add(qf(this.videoState.stateChangeStarted$.pipe(Ff(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Ff(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 mP;e.add(a.pipe(Vf(yP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Nt(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)>SP)&&a.next(o),s=o})),e.add(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<vP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:yi(n)}}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let i=qf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,fP(["init"])).pipe(Vf(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"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(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"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&E(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];_t(u);let d=gP(Object.keys(u));_t(d);let c=u[d];_t(c),i=c,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];_t(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];_t(u),i=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];_t(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];_t(u),i=X(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:_f.VIDEO_PIPELINE,message:u,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return yi(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:l}=this.params.meta;return Nf(o)&&(n.metadata.title=o),Nf(l)&&(n.metadata.subtitle=l),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(bP(Uf).subscribe(()=>s(`timeout(${Uf})`)))});(0,Hf.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:_f.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Gf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as TP}from"@vkontakte/videoplayer-shared";var jf=r=>{try{r.pause(),r.playbackRate=0,TP(r),r.remove()}catch(e){console.error(e)}};import{fromEvent as IP,Subscription as EP}from"@vkontakte/videoplayer-shared";var Uo=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)}},Ho=window.WeakMap?new WeakMap:new Uo,jo=window.WeakMap?new WeakMap:new Map,xP=(r,e=20)=>{let t=0;return IP(r,"ratechange").subscribe(i=>{t++,t>=e&&(r.currentTime=r.currentTime,t=0)})},oe=(r,{audioVideoSyncRate:e})=>{let t=r.querySelector("video"),i=!!t;t?Gf(t):(t=document.createElement("video"),r.appendChild(t)),Ho.set(t,i);let a=new EP;return a.add(xP(t,e)),jo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ue=r=>{jo.get(r)?.unsubscribe(),jo.delete(r);let t=Ho.get(r);Ho.delete(r),t?Gf(r):jf(r)};import{assertNonNullable as dr,isNonNullable as Je,isNullable as kP,fromEvent as Ti,merge as Wf,observableFrom as Qf,filterChanged as Yf,map as pr,Subject as zf,Subscription as wP,ValueSubject as RP,ErrorCategory as $P}from"@vkontakte/videoplayer-shared";import{isNonNullable as Go,isNullable as PP,Subscription as AP}from"@vkontakte/videoplayer-shared";var os=(r,e,t,{equal:i=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=r.getState(),o=e(),l=PP(a),u=new AP;return a&&u.add(a.subscribe(d=>{let c=r.getState();i(d,c)&&r.setState(d)},s)),i(o,n)||(t(n),l&&r.setState(n)),u.add(r.stateChangeStarted$.subscribe(d=>{t(d.to),l&&r.setState(d.to)},s)),u},Ke=(r,e,t)=>os(e,()=>r.loop,i=>{Go(i)&&(r.loop=i)},{onError:t}),le=(r,e,t,i)=>os(e,()=>({muted:r.muted,volume:r.volume}),a=>{Go(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}),ke=(r,e,t,i)=>os(e,()=>r.playbackRate,a=>{Go(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),gt=os;var LP=r=>["__",r.language,r.label].join("|"),MP=(r,e)=>{if(r.id===e)return!0;let[t,i,a]=e.split("|");return r.language===i&&r.label===a},Wo=class r{constructor(){this.available$=new zf;this.current$=new RP(void 0);this.error$=new zf;this.subscription=new wP;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:$P.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(gt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Je(s)&&this.setInternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(pr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(gt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Je(s)&&this.setExternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(pr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(gt(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(gt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){dr(this.video);let{textTracks:e}=this.video;this.subscription.add(Ti(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Wf(Ti(e,"addtrack"),Ti(e,"removetrack"),Qf(["init"])).pipe(pr(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Yf((i,a)=>i.length===a.length&&i.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Wf(Ti(e,"change"),Qf(["init"])).pipe(pr(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),pr(i=>i&&this.htmlTextTrackToITextTrack(i).id),Yf()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Ti(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(Ti(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;Je(t.align)&&(a.align=t.align),Je(t.position)&&(a.position=t.position),Je(t.size)&&(a.size=t.size),Je(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){dr(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:LP(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){dr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(kP(e)||!MP(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){dr(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){dr(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)}},we=Wo;var nt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Kf=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Qo=r=>{let e=Kf(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},Jf=r=>{let e=Kf(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};import{fromEvent as Re,map as St,merge as Zf,filterChanged as DP,isNonNullable as em,Subject as BP,filter as tm,mapTo as im,combine as OP,once as VP,ErrorCategory as _P,ValueSubject as rm,clientChecker as NP}from"@vkontakte/videoplayer-shared";var CP=3,Xf=(r,e,t=CP)=>{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 l=s-1;l>=0;l--)r.end(l)+t>=i&&(i=r.start(l));for(let l=s+1;l<r.length;l++)r.start(l)-t<=a&&(a=r.end(l))}}return{from:i,to:a}};var ce=r=>{let e=T=>Re(r,T).pipe(im(void 0)),i=Zf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Re(r,T))).pipe(St(T=>T.type==="ended"?r.readyState<2:r.readyState<3),DP()),a=Zf(Re(r,"progress"),Re(r,"timeupdate")).pipe(St(()=>Xf(r.buffered,r.currentTime))),s=NP.isSafari?OP({play:e("play").pipe(VP()),playing:e("playing")}).pipe(im(void 0)):e("playing"),n=Re(r,"volumechange").pipe(St(()=>({muted:r.muted,volume:r.volume}))),o=Re(r,"ratechange").pipe(St(()=>r.playbackRate)),l=Re(r,"error").pipe(tm(()=>!!(r.error||r.played.length)),St(()=>{let T=r.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:_P.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:r.error??void 0}})),u=Re(r,"timeupdate").pipe(St(()=>r.currentTime)),d=new BP,c=.3,p;u.subscribe(T=>{r.loop&&em(p)&&em(T)&&p>=r.duration-c&&T<=c&&d.next(p),p=T});let h=e("pause").pipe(tm(()=>!r.error&&p!==r.duration)),m=Re(r,"enterpictureinpicture"),b=Re(r,"leavepictureinpicture"),g=new rm(Jf(r));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let y=new rm(Qo(r));return Re(r,"fullscreenchange").pipe(St(()=>Qo(r))).subscribe(y),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:Re(r,"durationchange").pipe(St(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y}};import{VideoQuality as vt}from"@vkontakte/videoplayer-shared";var yt=r=>{switch(r){case"mobile":return vt.Q_144P;case"lowest":return vt.Q_240P;case"low":return vt.Q_360P;case"sd":case"medium":return vt.Q_480P;case"hd":case"high":return vt.Q_720P;case"fullhd":case"full":return vt.Q_1080P;case"quadhd":case"quad":return vt.Q_1440P;case"ultrahd":case"ultra":return vt.Q_2160P}};var Ft=Ye(hr(),1);import{isNonNullable as Y,isNullable as zo,now as gm,isHigher as Ko,isHigherOrEqual as hm,isInvariantQuality as fm,isLower as mm,isLowerOrEqual as Jo,videoSizeToQuality as YP,assertNotEmptyArray as Sm,assertNonNullable as zP}from"@vkontakte/videoplayer-shared";var Yo=!1,ot={},cm=r=>{Yo=r},dm=()=>{ot={}},pm=r=>{r(ot)},fr=(r,e)=>{Yo&&(ot.meta=ot.meta??{},ot.meta[r]=e)},re=class{constructor(e){this.name=e}next(e){if(!Yo)return;ot.series=ot.series??{};let t=ot.series[this.name]??[];t.push([Date.now(),e]),ot.series[this.name]=t}};var KP=new re("best_bitrate"),vm=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;var Xo=r=>(e,t)=>r*(Number(e.bitrate)-Number(t.bitrate)),mr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=gm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ym='Assertion "ABR Tracks is empty array" failed',us=(r,e,t,i)=>{let a=[...e].sort(Xo(1)),s=[...t].sort(Xo(1)),n=s.filter(l=>Y(l.bitrate)&&Y(r.bitrate)?r.bitrate/l.bitrate>i:!0),o=(0,Ft.default)(s,Math.round(s.length*a.indexOf(r)/(a.length+1)))??(0,Ft.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Ft.default)(n,-1):(0,Ft.default)(s,0)},bm=r=>"quality"in r,Tm=(r,e,t,i)=>{let a=Y(i?.last?.bitrate)&&Y(t?.bitrate)&&i.last.bitrate<t.bitrate?r.trackCooldownIncreaseQuality:r.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&gm()-i.history[t.id]<=a&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let o=bm(n)?"video":"audio",l=bm(n)?n.quality:n.bitrate;return e({message:`
7
- [last ${o} selected] ${l}
8
- `}),n}return i?.recordSwitch(t),t},Tt=(r,{container:e,throughput:t,tuning:i,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,visible:d,droppedVideoMaxQualityLimit:c,abrLogger:p})=>{Sm(r,ym);let h=window.devicePixelRatio??1,m=i.usePixelRatio?i.pixelRatioMultiplier*(h-1)+1:1,b=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*i.containerSizeFactor,height:e.height*m*i.containerSizeFactor},g=b&&YP(b),y=i.considerPlaybackRate&&Y(o)?o:1,A=r.filter(v=>!fm(v.quality)).sort((v,R)=>Ko(v.quality,R.quality)?-1:1),T=(0,Ft.default)(A,-1)?.quality,S=(0,Ft.default)(A,0)?.quality,I=zo(a)||Y(a.min)&&Y(a.max)&&mm(a.max,a.min)||Y(a.min)&&S&&Ko(a.min,S)||Y(a.max)&&T&&mm(a.max,T),w=y*vm(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},V=A.filter(v=>{if(!(g?Jo(v.quality,g):!0))return $[v.quality]="FitsContainer",!1;if(!(Y(t)&&isFinite(t)&&Y(v.bitrate)?t-s>=v.bitrate*w:!0))return $[v.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Y(i.minBufferToSwitchUp)&&l&&!fm(l.quality)&&(n??0)<i.minBufferToSwitchUp&&Ko(v.quality,l.quality))return $[v.quality]="Buffer",!1;if(!!c&&hm(v.quality,c))return $[v.quality]="DroppedFramesLimit",!1;let x=I||(zo(a.max)||Jo(v.quality,a.max))&&(zo(a.min)||hm(v.quality,a.min)),k=Y(d)&&!d?Jo(v.quality,i.backgroundVideoQualityLimit):!0;return!x||!k?($[v.quality]="FitsQualityLimits",!1):!0})[0];V&&V.bitrate&&KP.next(V.bitrate);let _=V??A[Math.ceil((A.length-1)/2)]??r[0];return _.quality!==u?.last?.quality&&p({message:`
6
+ var Wg=Object.create;var Ju=Object.defineProperty;var Qg=Object.getOwnPropertyDescriptor;var Yg=Object.getOwnPropertyNames;var zg=Object.getPrototypeOf,Kg=Object.prototype.hasOwnProperty;var f=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Jg=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Yg(e))!Kg.call(r,a)&&a!==t&&Ju(r,a,{get:()=>e[a],enumerable:!(i=Qg(e,a))||i.enumerable});return r};var Ye=(r,e,t)=>(t=r!=null?Wg(zg(r)):{},Jg(e||!r||!r.__esModule?Ju(t,"default",{value:r,enumerable:!0}):t,r));var ve=f((XR,sl)=>{"use strict";sl.exports=function(r){try{return!!r()}catch{return!0}}});var Fi=f((ZR,nl)=>{"use strict";var sS=ve();nl.exports=!sS(function(){var r=function(){}.bind();return typeof r!="function"||r.hasOwnProperty("prototype")})});var ne=f((e$,ll)=>{"use strict";var ol=Fi(),ul=Function.prototype,en=ul.call,nS=ol&&ul.bind.bind(en,en);ll.exports=ol?nS:function(r){return function(){return en.apply(r,arguments)}}});var ri=f((t$,dl)=>{"use strict";var cl=ne(),oS=cl({}.toString),uS=cl("".slice);dl.exports=function(r){return uS(oS(r),8,-1)}});var hl=f((i$,pl)=>{"use strict";var lS=ne(),cS=ve(),dS=ri(),tn=Object,pS=lS("".split);pl.exports=cS(function(){return!tn("z").propertyIsEnumerable(0)})?function(r){return dS(r)==="String"?pS(r,""):tn(r)}:tn});var ai=f((r$,fl)=>{"use strict";fl.exports=function(r){return r==null}});var qi=f((a$,ml)=>{"use strict";var hS=ai(),fS=TypeError;ml.exports=function(r){if(hS(r))throw new fS("Can't call method on "+r);return r}});var si=f((s$,bl)=>{"use strict";var mS=hl(),bS=qi();bl.exports=function(r){return mS(bS(r))}});var rn=f((n$,gl)=>{"use strict";gl.exports=function(){}});var Mt=f((o$,Sl)=>{"use strict";Sl.exports={}});var j=f((an,vl)=>{"use strict";var Ui=function(r){return r&&r.Math===Math&&r};vl.exports=Ui(typeof globalThis=="object"&&globalThis)||Ui(typeof window=="object"&&window)||Ui(typeof self=="object"&&self)||Ui(typeof global=="object"&&global)||Ui(typeof an=="object"&&an)||function(){return this}()||Function("return this")()});var U=f((u$,yl)=>{"use strict";var sn=typeof document=="object"&&document.all;yl.exports=typeof sn>"u"&&sn!==void 0?function(r){return typeof r=="function"||r===sn}:function(r){return typeof r=="function"}});var El=f((l$,Il)=>{"use strict";var gS=j(),SS=U(),Tl=gS.WeakMap;Il.exports=SS(Tl)&&/native code/.test(String(Tl))});var xe=f((c$,xl)=>{"use strict";var vS=U();xl.exports=function(r){return typeof r=="object"?r!==null:vS(r)}});var Pe=f((d$,Pl)=>{"use strict";var yS=ve();Pl.exports=!yS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Pa=f((p$,kl)=>{"use strict";var TS=j(),Al=xe(),nn=TS.document,IS=Al(nn)&&Al(nn.createElement);kl.exports=function(r){return IS?nn.createElement(r):{}}});var on=f((h$,wl)=>{"use strict";var ES=Pe(),xS=ve(),PS=Pa();wl.exports=!ES&&!xS(function(){return Object.defineProperty(PS("div"),"a",{get:function(){return 7}}).a!==7})});var un=f((f$,Rl)=>{"use strict";var AS=Pe(),kS=ve();Rl.exports=AS&&kS(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=f((m$,$l)=>{"use strict";var wS=xe(),RS=String,$S=TypeError;$l.exports=function(r){if(wS(r))return r;throw new $S(RS(r)+" is not an object")}});var ye=f((b$,Ll)=>{"use strict";var LS=Fi(),Aa=Function.prototype.call;Ll.exports=LS?Aa.bind(Aa):function(){return Aa.apply(Aa,arguments)}});var ka=f((g$,Ml)=>{"use strict";Ml.exports={}});var it=f((S$,Dl)=>{"use strict";var ln=ka(),cn=j(),MS=U(),Cl=function(r){return MS(r)?r:void 0};Dl.exports=function(r,e){return arguments.length<2?Cl(ln[r])||Cl(cn[r]):ln[r]&&ln[r][e]||cn[r]&&cn[r][e]}});var Hi=f((v$,Bl)=>{"use strict";var CS=ne();Bl.exports=CS({}.isPrototypeOf)});var ni=f((y$,_l)=>{"use strict";var DS=j(),Ol=DS.navigator,Vl=Ol&&Ol.userAgent;_l.exports=Vl?String(Vl):""});var pn=f((T$,jl)=>{"use strict";var Hl=j(),dn=ni(),Nl=Hl.process,Fl=Hl.Deno,ql=Nl&&Nl.versions||Fl&&Fl.version,Ul=ql&&ql.v8,_e,wa;Ul&&(_e=Ul.split("."),wa=_e[0]>0&&_e[0]<4?1:+(_e[0]+_e[1]));!wa&&dn&&(_e=dn.match(/Edge\/(\d+)/),(!_e||_e[1]>=74)&&(_e=dn.match(/Chrome\/(\d+)/),_e&&(wa=+_e[1])));jl.exports=wa});var hn=f((I$,Wl)=>{"use strict";var Gl=pn(),BS=ve(),OS=j(),VS=OS.String;Wl.exports=!!Object.getOwnPropertySymbols&&!BS(function(){var r=Symbol("symbol detection");return!VS(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&Gl&&Gl<41})});var fn=f((E$,Ql)=>{"use strict";var _S=hn();Ql.exports=_S&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mn=f((x$,Yl)=>{"use strict";var NS=it(),FS=U(),qS=Hi(),US=fn(),HS=Object;Yl.exports=US?function(r){return typeof r=="symbol"}:function(r){var e=NS("Symbol");return FS(e)&&qS(e.prototype,HS(r))}});var ji=f((P$,zl)=>{"use strict";var jS=String;zl.exports=function(r){try{return jS(r)}catch{return"Object"}}});var rt=f((A$,Kl)=>{"use strict";var GS=U(),WS=ji(),QS=TypeError;Kl.exports=function(r){if(GS(r))return r;throw new QS(WS(r)+" is not a function")}});var Gi=f((k$,Jl)=>{"use strict";var YS=rt(),zS=ai();Jl.exports=function(r,e){var t=r[e];return zS(t)?void 0:YS(t)}});var Zl=f((w$,Xl)=>{"use strict";var bn=ye(),gn=U(),Sn=xe(),KS=TypeError;Xl.exports=function(r,e){var t,i;if(e==="string"&&gn(t=r.toString)&&!Sn(i=bn(t,r))||gn(t=r.valueOf)&&!Sn(i=bn(t,r))||e!=="string"&&gn(t=r.toString)&&!Sn(i=bn(t,r)))return i;throw new KS("Can't convert object to primitive value")}});var Ne=f((R$,ec)=>{"use strict";ec.exports=!0});var rc=f(($$,ic)=>{"use strict";var tc=j(),JS=Object.defineProperty;ic.exports=function(r,e){try{JS(tc,r,{value:e,configurable:!0,writable:!0})}catch{tc[r]=e}return e}});var Wi=f((L$,nc)=>{"use strict";var XS=Ne(),ZS=j(),ev=rc(),ac="__core-js_shared__",sc=nc.exports=ZS[ac]||ev(ac,{});(sc.versions||(sc.versions=[])).push({version:"3.38.0",mode:XS?"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 vn=f((M$,uc)=>{"use strict";var oc=Wi();uc.exports=function(r,e){return oc[r]||(oc[r]=e||{})}});var Qi=f((C$,lc)=>{"use strict";var tv=qi(),iv=Object;lc.exports=function(r){return iv(tv(r))}});var Fe=f((D$,cc)=>{"use strict";var rv=ne(),av=Qi(),sv=rv({}.hasOwnProperty);cc.exports=Object.hasOwn||function(e,t){return sv(av(e),t)}});var yn=f((B$,dc)=>{"use strict";var nv=ne(),ov=0,uv=Math.random(),lv=nv(1 .toString);dc.exports=function(r){return"Symbol("+(r===void 0?"":r)+")_"+lv(++ov+uv,36)}});var ie=f((O$,hc)=>{"use strict";var cv=j(),dv=vn(),pc=Fe(),pv=yn(),hv=hn(),fv=fn(),oi=cv.Symbol,Tn=dv("wks"),mv=fv?oi.for||oi:oi&&oi.withoutSetter||pv;hc.exports=function(r){return pc(Tn,r)||(Tn[r]=hv&&pc(oi,r)?oi[r]:mv("Symbol."+r)),Tn[r]}});var gc=f((V$,bc)=>{"use strict";var bv=ye(),fc=xe(),mc=mn(),gv=Gi(),Sv=Zl(),vv=ie(),yv=TypeError,Tv=vv("toPrimitive");bc.exports=function(r,e){if(!fc(r)||mc(r))return r;var t=gv(r,Tv),i;if(t){if(e===void 0&&(e="default"),i=bv(t,r,e),!fc(i)||mc(i))return i;throw new yv("Can't convert object to primitive value")}return e===void 0&&(e="number"),Sv(r,e)}});var In=f((_$,Sc)=>{"use strict";var Iv=gc(),Ev=mn();Sc.exports=function(r){var e=Iv(r,"string");return Ev(e)?e:e+""}});var Ct=f(yc=>{"use strict";var xv=Pe(),Pv=on(),Av=un(),Ra=ze(),vc=In(),kv=TypeError,En=Object.defineProperty,wv=Object.getOwnPropertyDescriptor,xn="enumerable",Pn="configurable",An="writable";yc.f=xv?Av?function(e,t,i){if(Ra(e),t=vc(t),Ra(i),typeof e=="function"&&t==="prototype"&&"value"in i&&An in i&&!i[An]){var a=wv(e,t);a&&a[An]&&(e[t]=i.value,i={configurable:Pn in i?i[Pn]:a[Pn],enumerable:xn in i?i[xn]:a[xn],writable:!1})}return En(e,t,i)}:En:function(e,t,i){if(Ra(e),t=vc(t),Ra(i),Pv)try{return En(e,t,i)}catch{}if("get"in i||"set"in i)throw new kv("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Yi=f((F$,Tc)=>{"use strict";Tc.exports=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}}});var ui=f((q$,Ic)=>{"use strict";var Rv=Pe(),$v=Ct(),Lv=Yi();Ic.exports=Rv?function(r,e,t){return $v.f(r,e,Lv(1,t))}:function(r,e,t){return r[e]=t,r}});var $a=f((U$,xc)=>{"use strict";var Mv=vn(),Cv=yn(),Ec=Mv("keys");xc.exports=function(r){return Ec[r]||(Ec[r]=Cv(r))}});var La=f((H$,Pc)=>{"use strict";Pc.exports={}});var $n=f((j$,wc)=>{"use strict";var Dv=El(),kc=j(),Bv=xe(),Ov=ui(),kn=Fe(),wn=Wi(),Vv=$a(),_v=La(),Ac="Object already initialized",Rn=kc.TypeError,Nv=kc.WeakMap,Ma,zi,Ca,Fv=function(r){return Ca(r)?zi(r):Ma(r,{})},qv=function(r){return function(e){var t;if(!Bv(e)||(t=zi(e)).type!==r)throw new Rn("Incompatible receiver, "+r+" required");return t}};Dv||wn.state?(qe=wn.state||(wn.state=new Nv),qe.get=qe.get,qe.has=qe.has,qe.set=qe.set,Ma=function(r,e){if(qe.has(r))throw new Rn(Ac);return e.facade=r,qe.set(r,e),e},zi=function(r){return qe.get(r)||{}},Ca=function(r){return qe.has(r)}):(Dt=Vv("state"),_v[Dt]=!0,Ma=function(r,e){if(kn(r,Dt))throw new Rn(Ac);return e.facade=r,Ov(r,Dt,e),e},zi=function(r){return kn(r,Dt)?r[Dt]:{}},Ca=function(r){return kn(r,Dt)});var qe,Dt;wc.exports={set:Ma,get:zi,has:Ca,enforce:Fv,getterFor:qv}});var Ln=f((G$,Mc)=>{"use strict";var Uv=Fi(),Lc=Function.prototype,Rc=Lc.apply,$c=Lc.call;Mc.exports=typeof Reflect=="object"&&Reflect.apply||(Uv?$c.bind(Rc):function(){return $c.apply(Rc,arguments)})});var Mn=f((W$,Cc)=>{"use strict";var Hv=ri(),jv=ne();Cc.exports=function(r){if(Hv(r)==="Function")return jv(r)}});var Vc=f(Oc=>{"use strict";var Dc={}.propertyIsEnumerable,Bc=Object.getOwnPropertyDescriptor,Gv=Bc&&!Dc.call({1:2},1);Oc.f=Gv?function(e){var t=Bc(this,e);return!!t&&t.enumerable}:Dc});var Fc=f(Nc=>{"use strict";var Wv=Pe(),Qv=ye(),Yv=Vc(),zv=Yi(),Kv=si(),Jv=In(),Xv=Fe(),Zv=on(),_c=Object.getOwnPropertyDescriptor;Nc.f=Wv?_c:function(e,t){if(e=Kv(e),t=Jv(t),Zv)try{return _c(e,t)}catch{}if(Xv(e,t))return zv(!Qv(Yv.f,e,t),e[t])}});var Cn=f((z$,qc)=>{"use strict";var ey=ve(),ty=U(),iy=/#|\.prototype\./,Ki=function(r,e){var t=ay[ry(r)];return t===ny?!0:t===sy?!1:ty(e)?ey(e):!!e},ry=Ki.normalize=function(r){return String(r).replace(iy,".").toLowerCase()},ay=Ki.data={},sy=Ki.NATIVE="N",ny=Ki.POLYFILL="P";qc.exports=Ki});var Ji=f((K$,Hc)=>{"use strict";var Uc=Mn(),oy=rt(),uy=Fi(),ly=Uc(Uc.bind);Hc.exports=function(r,e){return oy(r),e===void 0?r:uy?ly(r,e):function(){return r.apply(e,arguments)}}});var Ae=f((J$,Gc)=>{"use strict";var Xi=j(),cy=Ln(),dy=Mn(),py=U(),hy=Fc().f,fy=Cn(),li=ka(),my=Ji(),ci=ui(),jc=Fe();Wi();var by=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 cy(r,this,arguments)};return e.prototype=r.prototype,e};Gc.exports=function(r,e){var t=r.target,i=r.global,a=r.stat,s=r.proto,n=i?Xi:a?Xi[t]:Xi[t]&&Xi[t].prototype,o=i?li:li[t]||ci(li,t,{})[t],u=o.prototype,l,d,c,p,h,m,b,g,y;for(p in e)l=fy(i?p:t+(a?".":"#")+p,r.forced),d=!l&&n&&jc(n,p),m=o[p],d&&(r.dontCallGetSet?(y=hy(n,p),b=y&&y.value):b=n[p]),h=d&&b?b:e[p],!(!l&&!s&&typeof m==typeof h)&&(r.bind&&d?g=my(h,Xi):r.wrap&&d?g=by(h):s&&py(h)?g=dy(h):g=h,(r.sham||h&&h.sham||m&&m.sham)&&ci(g,"sham",!0),ci(o,p,g),s&&(c=t+"Prototype",jc(li,c)||ci(li,c,{}),ci(li[c],p,h),r.real&&u&&(l||!u[p])&&ci(u,p,h)))}});var Yc=f((X$,Qc)=>{"use strict";var Dn=Pe(),gy=Fe(),Wc=Function.prototype,Sy=Dn&&Object.getOwnPropertyDescriptor,Bn=gy(Wc,"name"),vy=Bn&&function(){}.name==="something",yy=Bn&&(!Dn||Dn&&Sy(Wc,"name").configurable);Qc.exports={EXISTS:Bn,PROPER:vy,CONFIGURABLE:yy}});var Kc=f((Z$,zc)=>{"use strict";var Ty=Math.ceil,Iy=Math.floor;zc.exports=Math.trunc||function(e){var t=+e;return(t>0?Iy:Ty)(t)}});var Da=f((eL,Jc)=>{"use strict";var Ey=Kc();Jc.exports=function(r){var e=+r;return e!==e||e===0?0:Ey(e)}});var Zc=f((tL,Xc)=>{"use strict";var xy=Da(),Py=Math.max,Ay=Math.min;Xc.exports=function(r,e){var t=xy(r);return t<0?Py(t+e,0):Ay(t,e)}});var td=f((iL,ed)=>{"use strict";var ky=Da(),wy=Math.min;ed.exports=function(r){var e=ky(r);return e>0?wy(e,9007199254740991):0}});var Ba=f((rL,id)=>{"use strict";var Ry=td();id.exports=function(r){return Ry(r.length)}});var sd=f((aL,ad)=>{"use strict";var $y=si(),Ly=Zc(),My=Ba(),rd=function(r){return function(e,t,i){var a=$y(e),s=My(a);if(s===0)return!r&&-1;var n=Ly(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}};ad.exports={includes:rd(!0),indexOf:rd(!1)}});var ud=f((sL,od)=>{"use strict";var Cy=ne(),On=Fe(),Dy=si(),By=sd().indexOf,Oy=La(),nd=Cy([].push);od.exports=function(r,e){var t=Dy(r),i=0,a=[],s;for(s in t)!On(Oy,s)&&On(t,s)&&nd(a,s);for(;e.length>i;)On(t,s=e[i++])&&(~By(a,s)||nd(a,s));return a}});var Vn=f((nL,ld)=>{"use strict";ld.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var dd=f((oL,cd)=>{"use strict";var Vy=ud(),_y=Vn();cd.exports=Object.keys||function(e){return Vy(e,_y)}});var hd=f(pd=>{"use strict";var Ny=Pe(),Fy=un(),qy=Ct(),Uy=ze(),Hy=si(),jy=dd();pd.f=Ny&&!Fy?Object.defineProperties:function(e,t){Uy(e);for(var i=Hy(t),a=jy(t),s=a.length,n=0,o;s>n;)qy.f(e,o=a[n++],i[o]);return e}});var _n=f((lL,fd)=>{"use strict";var Gy=it();fd.exports=Gy("document","documentElement")});var Un=f((cL,Td)=>{"use strict";var Wy=ze(),Qy=hd(),md=Vn(),Yy=La(),zy=_n(),Ky=Pa(),Jy=$a(),bd=">",gd="<",Fn="prototype",qn="script",vd=Jy("IE_PROTO"),Nn=function(){},yd=function(r){return gd+qn+bd+r+gd+"/"+qn+bd},Sd=function(r){r.write(yd("")),r.close();var e=r.parentWindow.Object;return r=null,e},Xy=function(){var r=Ky("iframe"),e="java"+qn+":",t;return r.style.display="none",zy.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(yd("document.F=Object")),t.close(),t.F},Oa,Va=function(){try{Oa=new ActiveXObject("htmlfile")}catch{}Va=typeof document<"u"?document.domain&&Oa?Sd(Oa):Xy():Sd(Oa);for(var r=md.length;r--;)delete Va[Fn][md[r]];return Va()};Yy[vd]=!0;Td.exports=Object.create||function(e,t){var i;return e!==null?(Nn[Fn]=Wy(e),i=new Nn,Nn[Fn]=null,i[vd]=e):i=Va(),t===void 0?i:Qy.f(i,t)}});var Ed=f((dL,Id)=>{"use strict";var Zy=ve();Id.exports=!Zy(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype})});var jn=f((pL,Pd)=>{"use strict";var eT=Fe(),tT=U(),iT=Qi(),rT=$a(),aT=Ed(),xd=rT("IE_PROTO"),Hn=Object,sT=Hn.prototype;Pd.exports=aT?Hn.getPrototypeOf:function(r){var e=iT(r);if(eT(e,xd))return e[xd];var t=e.constructor;return tT(t)&&e instanceof t?t.prototype:e instanceof Hn?sT:null}});var di=f((hL,Ad)=>{"use strict";var nT=ui();Ad.exports=function(r,e,t,i){return i&&i.enumerable?r[e]=t:nT(r,e,t),r}});var Yn=f((fL,Rd)=>{"use strict";var oT=ve(),uT=U(),lT=xe(),cT=Un(),kd=jn(),dT=di(),pT=ie(),hT=Ne(),Qn=pT("iterator"),wd=!1,at,Gn,Wn;[].keys&&(Wn=[].keys(),"next"in Wn?(Gn=kd(kd(Wn)),Gn!==Object.prototype&&(at=Gn)):wd=!0);var fT=!lT(at)||oT(function(){var r={};return at[Qn].call(r)!==r});fT?at={}:hT&&(at=cT(at));uT(at[Qn])||dT(at,Qn,function(){return this});Rd.exports={IteratorPrototype:at,BUGGY_SAFARI_ITERATORS:wd}});var _a=f((mL,Ld)=>{"use strict";var mT=ie(),bT=mT("toStringTag"),$d={};$d[bT]="z";Ld.exports=String($d)==="[object z]"});var Zi=f((bL,Md)=>{"use strict";var gT=_a(),ST=U(),Na=ri(),vT=ie(),yT=vT("toStringTag"),TT=Object,IT=Na(function(){return arguments}())==="Arguments",ET=function(r,e){try{return r[e]}catch{}};Md.exports=gT?Na:function(r){var e,t,i;return r===void 0?"Undefined":r===null?"Null":typeof(t=ET(e=TT(r),yT))=="string"?t:IT?Na(e):(i=Na(e))==="Object"&&ST(e.callee)?"Arguments":i}});var Dd=f((gL,Cd)=>{"use strict";var xT=_a(),PT=Zi();Cd.exports=xT?{}.toString:function(){return"[object "+PT(this)+"]"}});var er=f((SL,Od)=>{"use strict";var AT=_a(),kT=Ct().f,wT=ui(),RT=Fe(),$T=Dd(),LT=ie(),Bd=LT("toStringTag");Od.exports=function(r,e,t,i){var a=t?r:r&&r.prototype;a&&(RT(a,Bd)||kT(a,Bd,{configurable:!0,value:e}),i&&!AT&&wT(a,"toString",$T))}});var _d=f((vL,Vd)=>{"use strict";var MT=Yn().IteratorPrototype,CT=Un(),DT=Yi(),BT=er(),OT=Mt(),VT=function(){return this};Vd.exports=function(r,e,t,i){var a=e+" Iterator";return r.prototype=CT(MT,{next:DT(+!i,t)}),BT(r,a,!1,!0),OT[a]=VT,r}});var Fd=f((yL,Nd)=>{"use strict";var _T=ne(),NT=rt();Nd.exports=function(r,e,t){try{return _T(NT(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}}});var Ud=f((TL,qd)=>{"use strict";var FT=xe();qd.exports=function(r){return FT(r)||r===null}});var jd=f((IL,Hd)=>{"use strict";var qT=Ud(),UT=String,HT=TypeError;Hd.exports=function(r){if(qT(r))return r;throw new HT("Can't set "+UT(r)+" as a prototype")}});var zn=f((EL,Gd)=>{"use strict";var jT=Fd(),GT=xe(),WT=qi(),QT=jd();Gd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=jT(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(a,s){return WT(a),QT(s),GT(a)&&(r?t(a,s):a.__proto__=s),a}}():void 0)});var ip=f((xL,tp)=>{"use strict";var YT=Ae(),zT=ye(),Fa=Ne(),Zd=Yc(),KT=U(),JT=_d(),Wd=jn(),Qd=zn(),XT=er(),ZT=ui(),Kn=di(),eI=ie(),Yd=Mt(),ep=Yn(),tI=Zd.PROPER,iI=Zd.CONFIGURABLE,zd=ep.IteratorPrototype,qa=ep.BUGGY_SAFARI_ITERATORS,tr=eI("iterator"),Kd="keys",ir="values",Jd="entries",Xd=function(){return this};tp.exports=function(r,e,t,i,a,s,n){JT(t,e,i);var o=function(y){if(y===a&&p)return p;if(!qa&&y&&y in d)return d[y];switch(y){case Kd:return function(){return new t(this,y)};case ir:return function(){return new t(this,y)};case Jd:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=r.prototype,c=d[tr]||d["@@iterator"]||a&&d[a],p=!qa&&c||o(a),h=e==="Array"&&d.entries||c,m,b,g;if(h&&(m=Wd(h.call(new r)),m!==Object.prototype&&m.next&&(!Fa&&Wd(m)!==zd&&(Qd?Qd(m,zd):KT(m[tr])||Kn(m,tr,Xd)),XT(m,u,!0,!0),Fa&&(Yd[u]=Xd))),tI&&a===ir&&c&&c.name!==ir&&(!Fa&&iI?ZT(d,"name",ir):(l=!0,p=function(){return zT(c,this)})),a)if(b={values:o(ir),keys:s?p:o(Kd),entries:o(Jd)},n)for(g in b)(qa||l||!(g in d))&&Kn(d,g,b[g]);else YT({target:e,proto:!0,forced:qa||l},b);return(!Fa||n)&&d[tr]!==p&&Kn(d,tr,p,{name:a}),Yd[e]=p,b}});var ap=f((PL,rp)=>{"use strict";rp.exports=function(r,e){return{value:r,done:e}}});var Xn=f((AL,lp)=>{"use strict";var rI=si(),Jn=rn(),sp=Mt(),op=$n(),aI=Ct().f,sI=ip(),Ua=ap(),nI=Ne(),oI=Pe(),up="Array Iterator",uI=op.set,lI=op.getterFor(up);lp.exports=sI(Array,"Array",function(r,e){uI(this,{type:up,target:rI(r),index:0,kind:e})},function(){var r=lI(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=void 0,Ua(void 0,!0);switch(r.kind){case"keys":return Ua(t,!1);case"values":return Ua(e[t],!1)}return Ua([t,e[t]],!1)},"values");var np=sp.Arguments=sp.Array;Jn("keys");Jn("values");Jn("entries");if(!nI&&oI&&np.name!=="values")try{aI(np,"name",{value:"values"})}catch{}});var dp=f((kL,cp)=>{"use strict";var cI=ie(),dI=Mt(),pI=cI("iterator"),hI=Array.prototype;cp.exports=function(r){return r!==void 0&&(dI.Array===r||hI[pI]===r)}});var Zn=f((wL,hp)=>{"use strict";var fI=Zi(),pp=Gi(),mI=ai(),bI=Mt(),gI=ie(),SI=gI("iterator");hp.exports=function(r){if(!mI(r))return pp(r,SI)||pp(r,"@@iterator")||bI[fI(r)]}});var mp=f((RL,fp)=>{"use strict";var vI=ye(),yI=rt(),TI=ze(),II=ji(),EI=Zn(),xI=TypeError;fp.exports=function(r,e){var t=arguments.length<2?EI(r):e;if(yI(t))return TI(vI(t,r));throw new xI(II(r)+" is not iterable")}});var Sp=f(($L,gp)=>{"use strict";var PI=ye(),bp=ze(),AI=Gi();gp.exports=function(r,e,t){var i,a;bp(r);try{if(i=AI(r,"return"),!i){if(e==="throw")throw t;return t}i=PI(i,r)}catch(s){a=!0,i=s}if(e==="throw")throw t;if(a)throw i;return bp(i),t}});var ja=f((LL,Ip)=>{"use strict";var kI=Ji(),wI=ye(),RI=ze(),$I=ji(),LI=dp(),MI=Ba(),vp=Hi(),CI=mp(),DI=Zn(),yp=Sp(),BI=TypeError,Ha=function(r,e){this.stopped=r,this.result=e},Tp=Ha.prototype;Ip.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),u=kI(e,i),l,d,c,p,h,m,b,g=function(A){return l&&yp(l,"normal",A),new Ha(!0,A)},y=function(A){return a?(RI(A),o?u(A[0],A[1],g):u(A[0],A[1])):o?u(A,g):u(A)};if(s)l=r.iterator;else if(n)l=r;else{if(d=DI(r),!d)throw new BI($I(r)+" is not iterable");if(LI(d)){for(c=0,p=MI(r);p>c;c++)if(h=y(r[c]),h&&vp(Tp,h))return h;return new Ha(!1)}l=CI(r,d)}for(m=s?r.next:l.next;!(b=wI(m,l)).done;){try{h=y(b.value)}catch(A){yp(l,"throw",A)}if(typeof h=="object"&&h&&vp(Tp,h))return h}return new Ha(!1)}});var xp=f((ML,Ep)=>{"use strict";var OI=Pe(),VI=Ct(),_I=Yi();Ep.exports=function(r,e,t){OI?VI.f(r,e,_I(0,t)):r[e]=t}});var Pp=f(()=>{"use strict";var NI=Ae(),FI=ja(),qI=xp();NI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return FI(e,function(i,a){qI(t,i,a)},{AS_ENTRIES:!0}),t}})});var kp=f((BL,Ap)=>{"use strict";Xn();Pp();var UI=ka();Ap.exports=UI.Object.fromEntries});var Rp=f((OL,wp)=>{"use strict";wp.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 Lp=f(()=>{"use strict";Xn();var HI=Rp(),jI=j(),GI=er(),$p=Mt();for(Ga in HI)GI(jI[Ga],Ga),$p[Ga]=$p.Array;var Ga});var Cp=f((NL,Mp)=>{"use strict";var WI=kp();Lp();Mp.exports=WI});var eo=f((FL,Dp)=>{"use strict";var QI=Cp();Dp.exports=QI});var Bp=f(()=>{"use strict"});var to=f((HL,Op)=>{"use strict";var rr=j(),YI=ni(),zI=ri(),Wa=function(r){return YI.slice(0,r.length)===r};Op.exports=function(){return Wa("Bun/")?"BUN":Wa("Cloudflare-Workers")?"CLOUDFLARE":Wa("Deno/")?"DENO":Wa("Node.js/")?"NODE":rr.Bun&&typeof Bun.version=="string"?"BUN":rr.Deno&&typeof Deno.version=="object"?"DENO":zI(rr.process)==="process"?"NODE":rr.window&&rr.document?"BROWSER":"REST"}()});var Qa=f((jL,Vp)=>{"use strict";var KI=to();Vp.exports=KI==="NODE"});var Np=f((GL,_p)=>{"use strict";var JI=Ct();_p.exports=function(r,e,t){return JI.f(r,e,t)}});var Up=f((WL,qp)=>{"use strict";var XI=it(),ZI=Np(),eE=ie(),tE=Pe(),Fp=eE("species");qp.exports=function(r){var e=XI(r);tE&&e&&!e[Fp]&&ZI(e,Fp,{configurable:!0,get:function(){return this}})}});var jp=f((QL,Hp)=>{"use strict";var iE=Hi(),rE=TypeError;Hp.exports=function(r,e){if(iE(e,r))return r;throw new rE("Incorrect invocation")}});var ro=f((YL,Gp)=>{"use strict";var aE=ne(),sE=U(),io=Wi(),nE=aE(Function.toString);sE(io.inspectSource)||(io.inspectSource=function(r){return nE(r)});Gp.exports=io.inspectSource});var Jp=f((zL,Kp)=>{"use strict";var oE=ne(),uE=ve(),Wp=U(),lE=Zi(),cE=it(),dE=ro(),Qp=function(){},Yp=cE("Reflect","construct"),ao=/^\s*(?:class|function)\b/,pE=oE(ao.exec),hE=!ao.test(Qp),ar=function(e){if(!Wp(e))return!1;try{return Yp(Qp,[],e),!0}catch{return!1}},zp=function(e){if(!Wp(e))return!1;switch(lE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return hE||!!pE(ao,dE(e))}catch{return!0}};zp.sham=!0;Kp.exports=!Yp||uE(function(){var r;return ar(ar.call)||!ar(Object)||!ar(function(){r=!0})||r})?zp:ar});var Zp=f((KL,Xp)=>{"use strict";var fE=Jp(),mE=ji(),bE=TypeError;Xp.exports=function(r){if(fE(r))return r;throw new bE(mE(r)+" is not a constructor")}});var so=f((JL,th)=>{"use strict";var eh=ze(),gE=Zp(),SE=ai(),vE=ie(),yE=vE("species");th.exports=function(r,e){var t=eh(r).constructor,i;return t===void 0||SE(i=eh(t)[yE])?e:gE(i)}});var rh=f((XL,ih)=>{"use strict";var TE=ne();ih.exports=TE([].slice)});var sh=f((ZL,ah)=>{"use strict";var IE=TypeError;ah.exports=function(r,e){if(r<e)throw new IE("Not enough arguments");return r}});var no=f((eM,nh)=>{"use strict";var EE=ni();nh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(EE)});var bo=f((tM,mh)=>{"use strict";var Te=j(),xE=Ln(),PE=Ji(),oh=U(),AE=Fe(),fh=ve(),uh=_n(),kE=rh(),lh=Pa(),wE=sh(),RE=no(),$E=Qa(),ho=Te.setImmediate,fo=Te.clearImmediate,LE=Te.process,oo=Te.Dispatch,ME=Te.Function,ch=Te.MessageChannel,CE=Te.String,uo=0,sr={},dh="onreadystatechange",nr,Bt,lo,co;fh(function(){nr=Te.location});var mo=function(r){if(AE(sr,r)){var e=sr[r];delete sr[r],e()}},po=function(r){return function(){mo(r)}},ph=function(r){mo(r.data)},hh=function(r){Te.postMessage(CE(r),nr.protocol+"//"+nr.host)};(!ho||!fo)&&(ho=function(e){wE(arguments.length,1);var t=oh(e)?e:ME(e),i=kE(arguments,1);return sr[++uo]=function(){xE(t,void 0,i)},Bt(uo),uo},fo=function(e){delete sr[e]},$E?Bt=function(r){LE.nextTick(po(r))}:oo&&oo.now?Bt=function(r){oo.now(po(r))}:ch&&!RE?(lo=new ch,co=lo.port2,lo.port1.onmessage=ph,Bt=PE(co.postMessage,co)):Te.addEventListener&&oh(Te.postMessage)&&!Te.importScripts&&nr&&nr.protocol!=="file:"&&!fh(hh)?(Bt=hh,Te.addEventListener("message",ph,!1)):dh in lh("script")?Bt=function(r){uh.appendChild(lh("script"))[dh]=function(){uh.removeChild(this),mo(r)}}:Bt=function(r){setTimeout(po(r),0)});mh.exports={set:ho,clear:fo}});var Sh=f((iM,gh)=>{"use strict";var bh=j(),DE=Pe(),BE=Object.getOwnPropertyDescriptor;gh.exports=function(r){if(!DE)return bh[r];var e=BE(bh,r);return e&&e.value}});var go=f((rM,yh)=>{"use strict";var vh=function(){this.head=null,this.tail=null};vh.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}}};yh.exports=vh});var Ih=f((aM,Th)=>{"use strict";var OE=ni();Th.exports=/ipad|iphone|ipod/i.test(OE)&&typeof Pebble<"u"});var xh=f((sM,Eh)=>{"use strict";var VE=ni();Eh.exports=/web0s(?!.*chrome)/i.test(VE)});var Lh=f((nM,$h)=>{"use strict";var hi=j(),_E=Sh(),Ph=Ji(),So=bo().set,NE=go(),FE=no(),qE=Ih(),UE=xh(),vo=Qa(),Ah=hi.MutationObserver||hi.WebKitMutationObserver,kh=hi.document,wh=hi.process,Ya=hi.Promise,Io=_E("queueMicrotask"),pi,yo,To,za,Rh;Io||(or=new NE,ur=function(){var r,e;for(vo&&(r=wh.domain)&&r.exit();e=or.get();)try{e()}catch(t){throw or.head&&pi(),t}r&&r.enter()},!FE&&!vo&&!UE&&Ah&&kh?(yo=!0,To=kh.createTextNode(""),new Ah(ur).observe(To,{characterData:!0}),pi=function(){To.data=yo=!yo}):!qE&&Ya&&Ya.resolve?(za=Ya.resolve(void 0),za.constructor=Ya,Rh=Ph(za.then,za),pi=function(){Rh(ur)}):vo?pi=function(){wh.nextTick(ur)}:(So=Ph(So,hi),pi=function(){So(ur)}),Io=function(r){or.head||pi(),or.add(r)});var or,ur;$h.exports=Io});var Ch=f((oM,Mh)=>{"use strict";Mh.exports=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}}});var Ka=f((uM,Dh)=>{"use strict";Dh.exports=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}}});var Ot=f((lM,Bh)=>{"use strict";var HE=j();Bh.exports=HE.Promise});var fi=f((cM,Nh)=>{"use strict";var jE=j(),lr=Ot(),GE=U(),WE=Cn(),QE=ro(),YE=ie(),Oh=to(),zE=Ne(),Eo=pn(),Vh=lr&&lr.prototype,KE=YE("species"),xo=!1,_h=GE(jE.PromiseRejectionEvent),JE=WE("Promise",function(){var r=QE(lr),e=r!==String(lr);if(!e&&Eo===66||zE&&!(Vh.catch&&Vh.finally))return!0;if(!Eo||Eo<51||!/native code/.test(r)){var t=new lr(function(s){s(1)}),i=function(s){s(function(){},function(){})},a=t.constructor={};if(a[KE]=i,xo=t.then(function(){})instanceof i,!xo)return!0}return!e&&(Oh==="BROWSER"||Oh==="DENO")&&!_h});Nh.exports={CONSTRUCTOR:JE,REJECTION_EVENT:_h,SUBCLASSING:xo}});var mi=f((dM,qh)=>{"use strict";var Fh=rt(),XE=TypeError,ZE=function(r){var e,t;this.promise=new r(function(i,a){if(e!==void 0||t!==void 0)throw new XE("Bad Promise constructor");e=i,t=a}),this.resolve=Fh(e),this.reject=Fh(t)};qh.exports.f=function(r){return new ZE(r)}});var of=f(()=>{"use strict";var ex=Ae(),tx=Ne(),es=Qa(),bt=j(),vi=ye(),Uh=di(),Hh=zn(),ix=er(),rx=Up(),ax=rt(),Za=U(),sx=xe(),nx=jp(),ox=so(),Yh=bo().set,Ro=Lh(),ux=Ch(),lx=Ka(),cx=go(),zh=$n(),ts=Ot(),$o=fi(),Kh=mi(),is="Promise",Jh=$o.CONSTRUCTOR,dx=$o.REJECTION_EVENT,px=$o.SUBCLASSING,Po=zh.getterFor(is),hx=zh.set,bi=ts&&ts.prototype,Vt=ts,Ja=bi,Xh=bt.TypeError,Ao=bt.document,Lo=bt.process,ko=Kh.f,fx=ko,mx=!!(Ao&&Ao.createEvent&&bt.dispatchEvent),Zh="unhandledrejection",bx="rejectionhandled",jh=0,ef=1,gx=2,Mo=1,tf=2,Xa,Gh,Sx,Wh,rf=function(r){var e;return sx(r)&&Za(e=r.then)?e:!1},af=function(r,e){var t=e.value,i=e.state===ef,a=i?r.ok:r.fail,s=r.resolve,n=r.reject,o=r.domain,u,l,d;try{a?(i||(e.rejection===tf&&yx(e),e.rejection=Mo),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),d=!0)),u===r.promise?n(new Xh("Promise-chain cycle")):(l=rf(u))?vi(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},sf=function(r,e){r.notified||(r.notified=!0,Ro(function(){for(var t=r.reactions,i;i=t.get();)af(i,r);r.notified=!1,e&&!r.rejection&&vx(r)}))},nf=function(r,e,t){var i,a;mx?(i=Ao.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(r,!1,!0),bt.dispatchEvent(i)):i={promise:e,reason:t},!dx&&(a=bt["on"+r])?a(i):r===Zh&&ux("Unhandled promise rejection",t)},vx=function(r){vi(Yh,bt,function(){var e=r.facade,t=r.value,i=Qh(r),a;if(i&&(a=lx(function(){es?Lo.emit("unhandledRejection",t,e):nf(Zh,e,t)}),r.rejection=es||Qh(r)?tf:Mo,a.error))throw a.value})},Qh=function(r){return r.rejection!==Mo&&!r.parent},yx=function(r){vi(Yh,bt,function(){var e=r.facade;es?Lo.emit("rejectionHandled",e):nf(bx,e,r.value)})},gi=function(r,e,t){return function(i){r(e,i,t)}},Si=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=gx,sf(r,!0))},wo=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new Xh("Promise can't be resolved itself");var i=rf(e);i?Ro(function(){var a={done:!1};try{vi(i,e,gi(wo,a,r),gi(Si,a,r))}catch(s){Si(a,s,r)}}):(r.value=e,r.state=ef,sf(r,!1))}catch(a){Si({done:!1},a,r)}}};if(Jh&&(Vt=function(e){nx(this,Ja),ax(e),vi(Xa,this);var t=Po(this);try{e(gi(wo,t),gi(Si,t))}catch(i){Si(t,i)}},Ja=Vt.prototype,Xa=function(e){hx(this,{type:is,done:!1,notified:!1,parent:!1,reactions:new cx,rejection:!1,state:jh,value:void 0})},Xa.prototype=Uh(Ja,"then",function(e,t){var i=Po(this),a=ko(ox(this,Vt));return i.parent=!0,a.ok=Za(e)?e:!0,a.fail=Za(t)&&t,a.domain=es?Lo.domain:void 0,i.state===jh?i.reactions.add(a):Ro(function(){af(a,i)}),a.promise}),Gh=function(){var r=new Xa,e=Po(r);this.promise=r,this.resolve=gi(wo,e),this.reject=gi(Si,e)},Kh.f=ko=function(r){return r===Vt||r===Sx?new Gh(r):fx(r)},!tx&&Za(ts)&&bi!==Object.prototype)){Wh=bi.then,px||Uh(bi,"then",function(e,t){var i=this;return new Vt(function(a,s){vi(Wh,i,a,s)}).then(e,t)},{unsafe:!0});try{delete bi.constructor}catch{}Hh&&Hh(bi,Ja)}ex({global:!0,constructor:!0,wrap:!0,forced:Jh},{Promise:Vt});ix(Vt,is,!1,!0);rx(is)});var pf=f((fM,df)=>{"use strict";var Tx=ie(),lf=Tx("iterator"),cf=!1;try{uf=0,Co={next:function(){return{done:!!uf++}},return:function(){cf=!0}},Co[lf]=function(){return this},Array.from(Co,function(){throw 2})}catch{}var uf,Co;df.exports=function(r,e){try{if(!e&&!cf)return!1}catch{return!1}var t=!1;try{var i={};i[lf]=function(){return{next:function(){return{done:t=!0}}}},r(i)}catch{}return t}});var Do=f((mM,hf)=>{"use strict";var Ix=Ot(),Ex=pf(),xx=fi().CONSTRUCTOR;hf.exports=xx||!Ex(function(r){Ix.all(r).then(void 0,function(){})})});var ff=f(()=>{"use strict";var Px=Ae(),Ax=ye(),kx=rt(),wx=mi(),Rx=Ka(),$x=ja(),Lx=Do();Px({target:"Promise",stat:!0,forced:Lx},{all:function(e){var t=this,i=wx.f(t),a=i.resolve,s=i.reject,n=Rx(function(){var o=kx(t.resolve),u=[],l=0,d=1;$x(e,function(c){var p=l++,h=!1;d++,Ax(o,t,c).then(function(m){h||(h=!0,u[p]=m,--d||a(u))},s)}),--d||a(u)});return n.error&&s(n.value),i.promise}})});var bf=f(()=>{"use strict";var Mx=Ae(),Cx=Ne(),Dx=fi().CONSTRUCTOR,Oo=Ot(),Bx=it(),Ox=U(),Vx=di(),mf=Oo&&Oo.prototype;Mx({target:"Promise",proto:!0,forced:Dx,real:!0},{catch:function(r){return this.then(void 0,r)}});!Cx&&Ox(Oo)&&(Bo=Bx("Promise").prototype.catch,mf.catch!==Bo&&Vx(mf,"catch",Bo,{unsafe:!0}));var Bo});var gf=f(()=>{"use strict";var _x=Ae(),Nx=ye(),Fx=rt(),qx=mi(),Ux=Ka(),Hx=ja(),jx=Do();_x({target:"Promise",stat:!0,forced:jx},{race:function(e){var t=this,i=qx.f(t),a=i.reject,s=Ux(function(){var n=Fx(t.resolve);Hx(e,function(o){Nx(n,t,o).then(i.resolve,a)})});return s.error&&a(s.value),i.promise}})});var Sf=f(()=>{"use strict";var Gx=Ae(),Wx=mi(),Qx=fi().CONSTRUCTOR;Gx({target:"Promise",stat:!0,forced:Qx},{reject:function(e){var t=Wx.f(this),i=t.reject;return i(e),t.promise}})});var Vo=f((xM,vf)=>{"use strict";var Yx=ze(),zx=xe(),Kx=mi();vf.exports=function(r,e){if(Yx(r),zx(e)&&e.constructor===r)return e;var t=Kx.f(r),i=t.resolve;return i(e),t.promise}});var If=f(()=>{"use strict";var Jx=Ae(),Xx=it(),yf=Ne(),Zx=Ot(),Tf=fi().CONSTRUCTOR,eP=Vo(),tP=Xx("Promise"),iP=yf&&!Tf;Jx({target:"Promise",stat:!0,forced:yf||Tf},{resolve:function(e){return eP(iP&&this===tP?Zx:this,e)}})});var Ef=f(()=>{"use strict";of();ff();bf();gf();Sf();If()});var kf=f(()=>{"use strict";var rP=Ae(),aP=Ne(),rs=Ot(),sP=ve(),Pf=it(),Af=U(),nP=so(),xf=Vo(),oP=di(),No=rs&&rs.prototype,uP=!!rs&&sP(function(){No.finally.call({then:function(){}},function(){})});rP({target:"Promise",proto:!0,real:!0,forced:uP},{finally:function(r){var e=nP(this,Pf("Promise")),t=Af(r);return this.then(t?function(i){return xf(e,r()).then(function(){return i})}:r,t?function(i){return xf(e,r()).then(function(){throw i})}:r)}});!aP&&Af(rs)&&(_o=Pf("Promise").prototype.finally,No.finally!==_o&&oP(No,"finally",_o,{unsafe:!0}));var _o});var as=f((LM,wf)=>{"use strict";var lP=it();wf.exports=lP});var $f=f((MM,Rf)=>{"use strict";Bp();Ef();kf();var cP=as();Rf.exports=cP("Promise","finally")});var Mf=f((CM,Lf)=>{"use strict";var dP=$f();Lf.exports=dP});var ss=f((DM,Cf)=>{"use strict";var pP=Mf();Cf.exports=pP});var am=f(()=>{"use strict";var qP=Ae(),UP=Qi(),HP=Ba(),jP=Da(),GP=rn();qP({target:"Array",proto:!0},{at:function(e){var t=UP(this),i=HP(t),a=jP(e),s=a>=0?a:i+a;return s<0||s>=i?void 0:t[s]}});GP("at")});var nm=f((HC,sm)=>{"use strict";am();var WP=as();sm.exports=WP("Array","at")});var um=f((jC,om)=>{"use strict";var QP=nm();om.exports=QP});var hr=f((GC,lm)=>{"use strict";var YP=um();lm.exports=YP});var ab=f(()=>{"use strict"});var sb=f(()=>{"use strict"});var ob=f((WO,nb)=>{"use strict";var tk=xe(),ik=ri(),rk=ie(),ak=rk("match");nb.exports=function(r){var e;return tk(r)&&((e=r[ak])!==void 0?!!e:ik(r)==="RegExp")}});var lb=f((QO,ub)=>{"use strict";var sk=Zi(),nk=String;ub.exports=function(r){if(sk(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return nk(r)}});var db=f((YO,cb)=>{"use strict";var ok=ze();cb.exports=function(){var r=ok(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 fb=f((zO,hb)=>{"use strict";var uk=ye(),lk=Fe(),ck=Hi(),dk=db(),pb=RegExp.prototype;hb.exports=function(r){var e=r.flags;return e===void 0&&!("flags"in pb)&&!lk(r,"flags")&&ck(pb,r)?uk(dk,r):e}});var bb=f((KO,mb)=>{"use strict";var mu=ne(),pk=Qi(),hk=Math.floor,hu=mu("".charAt),fk=mu("".replace),fu=mu("".slice),mk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,bk=/\$([$&'`]|\d{1,2})/g;mb.exports=function(r,e,t,i,a,s){var n=t+r.length,o=i.length,u=bk;return a!==void 0&&(a=pk(a),u=mk),fk(s,u,function(l,d){var c;switch(hu(d,0)){case"$":return"$";case"&":return r;case"`":return fu(e,0,t);case"'":return fu(e,n);case"<":c=a[fu(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=hk(p/10);return h===0?l:h<=o?i[h-1]===void 0?hu(d,1):i[h-1]+hu(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var vb=f(()=>{"use strict";var gk=Ae(),Sk=ye(),gu=ne(),gb=qi(),vk=U(),yk=ai(),Tk=ob(),$i=lb(),Ik=Gi(),Ek=fb(),xk=bb(),Pk=ie(),Ak=Ne(),kk=Pk("replace"),wk=TypeError,bu=gu("".indexOf),Rk=gu("".replace),Sb=gu("".slice),$k=Math.max;gk({target:"String",proto:!0},{replaceAll:function(e,t){var i=gb(this),a,s,n,o,u,l,d,c,p,h,m=0,b="";if(!yk(e)){if(a=Tk(e),a&&(s=$i(gb(Ek(e))),!~bu(s,"g")))throw new wk("`.replaceAll` does not allow non-global regexes");if(n=Ik(e,kk),n)return Sk(n,e,i,t);if(Ak&&a)return Rk($i(i),e,t)}for(o=$i(i),u=$i(e),l=vk(t),l||(t=$i(t)),d=u.length,c=$k(1,d),p=bu(o,u);p!==-1;)h=l?$i(t(u,p,o)):xk(u,o,p,[],void 0,t),b+=Sb(o,m,p)+h,m=p+d,p=p+c>o.length?-1:bu(o,u,p+c);return m<o.length&&(b+=Sb(o,m)),b}})});var Tb=f((ZO,yb)=>{"use strict";ab();sb();vb();var Lk=as();yb.exports=Lk("String","replaceAll")});var Eb=f((eV,Ib)=>{"use strict";var Mk=Tb();Ib.exports=Mk});var Pb=f((tV,xb)=>{"use strict";var Ck=Eb();xb.exports=Ck});var Xu="2.0.115-dev.c6f77ae4.0";var se=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(se||{}),mt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(mt||{});var Ia=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ia||{}),Ks=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ks||{});var Js=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Js||{});import{assertNever as al,assertNonNullable as Xg,isNonNullable as Ea,ValueSubject as Xs,Subject as Zg,Subscription as eS,merge as tS,observableFrom as iS,fromEvent as el,map as tl,tap as il,filterChanged as rS,isNullable as Zs,ErrorCategory as rl}from"@vkontakte/videoplayer-shared";var Zu=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 xa=class{constructor(e){this.connection$=new Xs(void 0);this.castState$=new Xs("NOT_AVAILABLE");this.errorEvent$=new Zg;this.realCastState$=new Xs("NOT_AVAILABLE");this.subscription=new eS;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=Ea(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Zu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:rl.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(){Ea(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Zs(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Zs(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(el(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 al(a.sessionState)}})).add(tS(el(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(il(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),tl(a=>a.castState)),iS([i.getCastState()])).pipe(rS(),tl(aS),il(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Ea(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();Xg(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Zs(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?Ea(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:rl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},aS=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 al(r)}};var Eg=Ye(eo(),1);var Hf=Ye(ss(),1);import{assertNever as Df}from"@vkontakte/videoplayer-shared";var X=(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:Df(t)}return r},Fo=(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:Df(e)}};var E=(r,e,t=!1)=>{let i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};import{isNonNullable as hP,Subject as ns,merge as Bf}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new ns;this.transitionEnded$=new ns;this.transitionUpdated$=new ns;this.forceChanged$=new ns;this.stateChangeStarted$=Bf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Bf(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||hP(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as fP}from"@vkontakte/videoplayer-shared";var Of=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 fP(r)}};import{assertNever as yi,assertNonNullable as _t,debounce as Vf,ErrorCategory as _f,fromEvent as Nt,isNonNullable as Nf,map as Ff,merge as qf,observableFrom as mP,Subject as bP,Subscription as qo,timeout as gP,getHighestQuality as SP}from"@vkontakte/videoplayer-shared";var vP=5,yP=5,TP=500,Uf=7e3,cr=class{constructor(e){this.subscription=new qo;this.loadMediaTimeoutSubscription=new qo;this.videoState=new L("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:yi(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:yi(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:yi(e)}break}default:yi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Of(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 qo;this.subscription.add(e),this.subscription.add(qf(this.videoState.stateChangeStarted$.pipe(Ff(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Ff(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 bP;e.add(a.pipe(Vf(TP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Nt(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)>vP)&&a.next(o),s=o})),e.add(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Nt(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(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<yP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:yi(n)}}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let i=qf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,mP(["init"])).pipe(Vf(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"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(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"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&E(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 l=t[e];_t(l);let d=SP(Object.keys(l));_t(d);let c=l[d];_t(c),i=c,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];_t(l),i=l.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 l=t[e];_t(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];_t(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];_t(l),i=X(l.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:_f.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return yi(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:u}=this.params.meta;return Nf(o)&&(n.metadata.title=o),Nf(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(gP(Uf).subscribe(()=>s(`timeout(${Uf})`)))});(0,Hf.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:_f.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Gf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as IP}from"@vkontakte/videoplayer-shared";var jf=r=>{try{r.pause(),r.playbackRate=0,IP(r),r.remove()}catch(e){console.error(e)}};import{fromEvent as EP,Subscription as xP}from"@vkontakte/videoplayer-shared";var Uo=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)}},Ho=window.WeakMap?new WeakMap:new Uo,jo=window.WeakMap?new WeakMap:new Map,PP=(r,e=20)=>{let t=0;return EP(r,"ratechange").subscribe(i=>{t++,t>=e&&(r.currentTime=r.currentTime,t=0)})},oe=(r,{audioVideoSyncRate:e})=>{let t=r.querySelector("video"),i=!!t;t?Gf(t):(t=document.createElement("video"),r.appendChild(t)),Ho.set(t,i);let a=new xP;return a.add(PP(t,e)),jo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ue=r=>{jo.get(r)?.unsubscribe(),jo.delete(r);let t=Ho.get(r);Ho.delete(r),t?Gf(r):jf(r)};import{assertNonNullable as dr,isNonNullable as Je,isNullable as wP,fromEvent as Ti,merge as Wf,observableFrom as Qf,filterChanged as Yf,map as pr,Subject as zf,Subscription as RP,ValueSubject as $P,ErrorCategory as LP}from"@vkontakte/videoplayer-shared";import{isNonNullable as Go,isNullable as AP,Subscription as kP}from"@vkontakte/videoplayer-shared";var os=(r,e,t,{equal:i=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=r.getState(),o=e(),u=AP(a),l=new kP;return a&&l.add(a.subscribe(d=>{let c=r.getState();i(d,c)&&r.setState(d)},s)),i(o,n)||(t(n),u&&r.setState(n)),l.add(r.stateChangeStarted$.subscribe(d=>{t(d.to),u&&r.setState(d.to)},s)),l},Ke=(r,e,t)=>os(e,()=>r.loop,i=>{Go(i)&&(r.loop=i)},{onError:t}),le=(r,e,t,i)=>os(e,()=>({muted:r.muted,volume:r.volume}),a=>{Go(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}),ke=(r,e,t,i)=>os(e,()=>r.playbackRate,a=>{Go(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),gt=os;var MP=r=>["__",r.language,r.label].join("|"),CP=(r,e)=>{if(r.id===e)return!0;let[t,i,a]=e.split("|");return r.language===i&&r.label===a},Wo=class r{constructor(){this.available$=new zf;this.current$=new $P(void 0);this.error$=new zf;this.subscription=new RP;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:LP.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(gt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Je(s)&&this.setInternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(pr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(gt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Je(s)&&this.setExternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(pr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(gt(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(gt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){dr(this.video);let{textTracks:e}=this.video;this.subscription.add(Ti(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Wf(Ti(e,"addtrack"),Ti(e,"removetrack"),Qf(["init"])).pipe(pr(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Yf((i,a)=>i.length===a.length&&i.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Wf(Ti(e,"change"),Qf(["init"])).pipe(pr(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),pr(i=>i&&this.htmlTextTrackToITextTrack(i).id),Yf()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Ti(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(Ti(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;Je(t.align)&&(a.align=t.align),Je(t.position)&&(a.position=t.position),Je(t.size)&&(a.size=t.size),Je(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){dr(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:MP(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)||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){dr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(wP(e)||!CP(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){dr(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){dr(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)}},we=Wo;var nt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Kf=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Qo=r=>{let e=Kf(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},Jf=r=>{let e=Kf(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};import{fromEvent as Re,map as St,merge as Zf,filterChanged as BP,isNonNullable as em,Subject as OP,filter as tm,mapTo as im,combine as VP,once as _P,ErrorCategory as NP,ValueSubject as rm,clientChecker as FP}from"@vkontakte/videoplayer-shared";var DP=3,Xf=(r,e,t=DP)=>{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 u=s-1;u>=0;u--)r.end(u)+t>=i&&(i=r.start(u));for(let u=s+1;u<r.length;u++)r.start(u)-t<=a&&(a=r.end(u))}}return{from:i,to:a}};var ce=r=>{let e=T=>Re(r,T).pipe(im(void 0)),i=Zf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Re(r,T))).pipe(St(T=>T.type==="ended"?r.readyState<2:r.readyState<3),BP()),a=Zf(Re(r,"progress"),Re(r,"timeupdate")).pipe(St(()=>Xf(r.buffered,r.currentTime))),s=FP.isSafari?VP({play:e("play").pipe(_P()),playing:e("playing")}).pipe(im(void 0)):e("playing"),n=Re(r,"volumechange").pipe(St(()=>({muted:r.muted,volume:r.volume}))),o=Re(r,"ratechange").pipe(St(()=>r.playbackRate)),u=Re(r,"error").pipe(tm(()=>!!(r.error||r.played.length)),St(()=>{let T=r.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:NP.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:r.error??void 0}})),l=Re(r,"timeupdate").pipe(St(()=>r.currentTime)),d=new OP,c=.3,p;l.subscribe(T=>{r.loop&&em(p)&&em(T)&&p>=r.duration-c&&T<=c&&d.next(p),p=T});let h=e("pause").pipe(tm(()=>!r.error&&p!==r.duration)),m=Re(r,"enterpictureinpicture"),b=Re(r,"leavepictureinpicture"),g=new rm(Jf(r));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let y=new rm(Qo(r));return Re(r,"fullscreenchange").pipe(St(()=>Qo(r))).subscribe(y),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Re(r,"durationchange").pipe(St(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y}};import{VideoQuality as vt}from"@vkontakte/videoplayer-shared";var yt=r=>{switch(r){case"mobile":return vt.Q_144P;case"lowest":return vt.Q_240P;case"low":return vt.Q_360P;case"sd":case"medium":return vt.Q_480P;case"hd":case"high":return vt.Q_720P;case"fullhd":case"full":return vt.Q_1080P;case"quadhd":case"quad":return vt.Q_1440P;case"ultrahd":case"ultra":return vt.Q_2160P}};var Ft=Ye(hr(),1);import{isNonNullable as Y,isNullable as zo,now as gm,isHigher as Ko,isHigherOrEqual as hm,isInvariantQuality as fm,isLower as mm,isLowerOrEqual as Jo,videoSizeToQuality as zP,assertNotEmptyArray as Sm,assertNonNullable as KP}from"@vkontakte/videoplayer-shared";var Yo=!1,ot={},cm=r=>{Yo=r},dm=()=>{ot={}},pm=r=>{r(ot)},fr=(r,e)=>{Yo&&(ot.meta=ot.meta??{},ot.meta[r]=e)},re=class{constructor(e){this.name=e}next(e){if(!Yo)return;ot.series=ot.series??{};let t=ot.series[this.name]??[];t.push([Date.now(),e]),ot.series[this.name]=t}};var JP=new re("best_bitrate"),vm=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;var Xo=r=>(e,t)=>r*(Number(e.bitrate)-Number(t.bitrate)),mr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=gm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ym='Assertion "ABR Tracks is empty array" failed',us=(r,e,t,i)=>{let a=[...e].sort(Xo(1)),s=[...t].sort(Xo(1)),n=s.filter(u=>Y(u.bitrate)&&Y(r.bitrate)?r.bitrate/u.bitrate>i:!0),o=(0,Ft.default)(s,Math.round(s.length*a.indexOf(r)/(a.length+1)))??(0,Ft.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Ft.default)(n,-1):(0,Ft.default)(s,0)},bm=r=>"quality"in r,Tm=(r,e,t,i)=>{let a=Y(i?.last?.bitrate)&&Y(t?.bitrate)&&i.last.bitrate<t.bitrate?r.trackCooldownIncreaseQuality:r.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&gm()-i.history[t.id]<=a&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let o=bm(n)?"video":"audio",u=bm(n)?n.quality:n.bitrate;return e({message:`
7
+ [last ${o} selected] ${u}
8
+ `}),n}return i?.recordSwitch(t),t},Tt=(r,{container:e,throughput:t,tuning:i,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,abrLogger:p})=>{Sm(r,ym);let h=window.devicePixelRatio??1,m=i.usePixelRatio?i.pixelRatioMultiplier*(h-1)+1:1,b=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*i.containerSizeFactor,height:e.height*m*i.containerSizeFactor},g=b&&zP(b),y=i.considerPlaybackRate&&Y(o)?o:1,A=r.filter(v=>!fm(v.quality)).sort((v,R)=>Ko(v.quality,R.quality)?-1:1),T=(0,Ft.default)(A,-1)?.quality,S=(0,Ft.default)(A,0)?.quality,I=zo(a)||Y(a.min)&&Y(a.max)&&mm(a.max,a.min)||Y(a.min)&&S&&Ko(a.min,S)||Y(a.max)&&T&&mm(a.max,T),w=y*vm(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},V=A.filter(v=>{if(!(g?Jo(v.quality,g):!0))return $[v.quality]="FitsContainer",!1;if(!(Y(t)&&isFinite(t)&&Y(v.bitrate)?t-s>=v.bitrate*w:!0))return $[v.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Y(i.minBufferToSwitchUp)&&u&&!fm(u.quality)&&(n??0)<i.minBufferToSwitchUp&&Ko(v.quality,u.quality))return $[v.quality]="Buffer",!1;if(!!c&&hm(v.quality,c))return $[v.quality]="DroppedFramesLimit",!1;let x=I||(zo(a.max)||Jo(v.quality,a.max))&&(zo(a.min)||hm(v.quality,a.min)),k=Y(d)&&!d?Jo(v.quality,i.backgroundVideoQualityLimit):!0;return!x||!k?($[v.quality]="FitsQualityLimits",!1):!0})[0];V&&V.bitrate&&JP.next(V.bitrate);let _=V??A[Math.ceil((A.length-1)/2)]??r[0];return _.quality!==l?.last?.quality&&p({message:`
9
9
  [VIDEO TRACKS ABR]
10
10
  [available video tracks]
11
11
  ${r.map(v=>`{ id: ${v.id}, quality: ${v.quality}, bitrate: ${v.bitrate} }`).join(`
@@ -35,7 +35,7 @@ var Gg=Object.create;var Ju=Object.defineProperty;var Wg=Object.getOwnPropertyDe
35
35
 
36
36
  [best video track] ${V?.quality}
37
37
  [selected video track] ${_?.quality}
38
- `}),Tm(i,p,_,u)},Im=(r,e,t,{throughput:i,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:l})=>{Sm(t,ym);let u=a.considerPlaybackRate&&Y(s)?s:1,d=[...t].sort(Xo(-1)),c=r.bitrate;zP(c);let p=u*vm(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),h,m=us(r,e,t,a.minVideoAudioRatio);return Y(i)&&isFinite(i)&&(h=d.find(b=>Y(b.bitrate)&&Y(m?.bitrate)?i-c>=b.bitrate*p&&b.bitrate>=m.bitrate:!1)),h||(h=m),h?.bitrate!==o?.last?.bitrate&&l({message:`
38
+ `}),Tm(i,p,_,l)},Im=(r,e,t,{throughput:i,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{Sm(t,ym);let l=a.considerPlaybackRate&&Y(s)?s:1,d=[...t].sort(Xo(-1)),c=r.bitrate;KP(c);let p=l*vm(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),h,m=us(r,e,t,a.minVideoAudioRatio);return Y(i)&&isFinite(i)&&(h=d.find(b=>Y(b.bitrate)&&Y(m?.bitrate)?i-c>=b.bitrate*p&&b.bitrate>=m.bitrate:!1)),h||(h=m),h?.bitrate!==o?.last?.bitrate&&u({message:`
39
39
  [AUDIO TRACKS ABR]
40
40
  [available audio tracks]
41
41
  ${t.map(b=>`{ id: ${b.id}, bitrate: ${b.bitrate} }`).join(`
@@ -49,13 +49,20 @@ var Gg=Object.create;var Ju=Object.defineProperty;var Wg=Object.getOwnPropertyDe
49
49
  throughput: ${i},
50
50
  reserve: ${c},
51
51
  playbackRate: ${s},
52
- playbackRateFactor: ${u},
52
+ playbackRateFactor: ${l},
53
53
  forwardBufferHealth: ${n},
54
54
  bitrateFactor: ${p},
55
55
  minBufferToSwitchUp: ${a.minBufferToSwitchUp},
56
56
 
57
57
  [selected audio track] ${h?.id}
58
- `}),h&&Tm(a,l,h,o)};var z=r=>new URL(r).hostname;import{assertNever as wm,assertNonNullable as Rm,combine as gA,debounce as SA,ErrorCategory as $m,filter as Lm,filterChanged as vA,isNonNullable as ru,map as hs,merge as Mm,observableFrom as yA,once as TA,Subscription as IA,ValueSubject as au,videoQualityToHeight as EA,videoSizeToQuality as xA}from"@vkontakte/videoplayer-shared";var Em=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"))},de=async(r,e)=>{let t=r.muted;try{await r.play()}catch(i){if(!Em(i))return!1;if(e&&e(),t)return console.warn(i),!1;r.muted=!0;try{await r.play()}catch(a){return Em(a)&&(r.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as cs,isNullable as ZP,assertNonNullable as Sr}from"@vkontakte/videoplayer-shared";import{isNonNullable as xm,assertNonNullable as ls,now as JP}from"@vkontakte/videoplayer-shared";function K(){return JP()}function Zo(r){return K()-r}function eu(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,l=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return l&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Pm(r,e,t){let i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Ii(r,e,t,i){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,d,c,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(l)return;ls(d);let R=Zo(d),q;if(R<b){q=b-R,setTimeout(g,q);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new a,w()},y=R=>(s=R,v),A=R=>(c=R,v),T=()=>(h="json",v),S=()=>{if(!l){if(--u>=0){g(),i&&i();return}l=!0,c&&c(),t&&t()}},I=R=>(p=R,v),w=()=>{d=K(),n=new a,n.open("get",r);let R=0,q,Me=0,ge=()=>(ls(d),Math.max(d,Math.max(q||0,Me||0)));if(s&&n.addEventListener("progress",x=>{let k=K();s.updateChunk&&x.loaded>R&&(s.updateChunk(ge(),x.loaded-R),R=x.loaded,q=k)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>S())),n.addEventListener("load",()=>{if(l)return;ls(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let k=n.response.byteLength-R;k&&s.updateChunk&&s.updateChunk(ge(),k)}n.responseType==="json"&&!Object.values(n.response).length?S():(c&&c(),e(n.response))}else S()}),n.addEventListener("error",()=>{S()}),p){let x=()=>{ls(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Me=K(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),v},v={withBitrateReporting:y,withParallel:I,withJSONResponse:T,withRetryCount:R=>(u=R,v),withRetryInterval:(R,q)=>(xm(R)&&(b=R),xm(q)&&(m=q),v),withTimeout:R=>(o=R,v),withFinally:A,send:w,abort:()=>{n&&(n.abort(),n=void 0),l=!0,c&&c()}};return v}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 l=s.bytes*n/o;a+=l,s.start=t,s.bytes-=l}}}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=K(),a=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=l=>{e._complete=1,e._responseData=l,e._downloadTime=K()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ii(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=K()}_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=K();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}};import{Subject as eA}from"@vkontakte/videoplayer-shared";var ds=1e4,tu=3;var tA=6e4,iA=10,rA=1,aA=500,vr=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.soundProhibitedEvent$=new eA,this.chunkRateEstimator=new br(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=eu(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=eu(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||cs(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=()=>{Pm(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(tu,ds,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,l=null,u=null,d=!1,c=()=>{let S=s&&(!d||d===this.rep);return S||t("Not running!"),S},p=(S,I,w)=>{l&&l.abort(),l=Ii(this.urlResolver.resolve(S,!1),I,w,()=>this._retryCallback()).withTimeout(ds).withBitrateReporting(this.bitrateSwitcher).withRetryCount(tu).withFinally(()=>{l=null}).send()},h=(S,I,w)=>{Sr(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(S,!1),I,w,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=S=>{let I=i.playbackRate;i.playbackRate!==S&&(t(`Playback rate switch: ${I}=>${S}`),i.playbackRate=S)},b=S=>{this.lowLatency=S,t(`lowLatency changed to ${S}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let S=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let w=K()-1e4,$=0;for(let V=0;V<this.bufferStates.length;V++){let _=this.bufferStates[V];S=Math.min(S,_.buf),_.ts<w&&$++}this.bufferStates.splice(0,$),t(`update playback rate; minBuffer=${S} drop=${$} jitter=${this.sourceJitter}`);let F=S-rA;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?m(1.15):F>1?m(1.1):F>.3?m(1.05):m(1)}},y=S=>{let I,w=()=>I&&I.start?I.start.length:0,$=x=>I.start[x]/1e3,F=x=>I.dur[x]/1e3,V=x=>I.fragIndex+x,_=(x,k)=>({chunkIdx:V(x),startTS:$(x),dur:F(x),discontinuity:k}),v=()=>{let x=0;if(I&&I.dur){let k=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=k;this.sourceJitter>1&&(J+=this.sourceJitter-1);let Se=I.dur.length-1;for(;Se>=0&&(J-=I.dur[Se],!(J<=0));--Se);x=Math.min(Se,I.dur.length-1-W),x=Math.max(x,0)}return _(x,!0)},R=x=>{let k=w();if(!(k<=0)){if(cs(x)){for(let W=0;W<k;W++)if($(W)>x)return _(W)}return v()}},q=x=>{let k=w(),W=x?x.chunkIdx+1:0,J=W-I.fragIndex;if(!(k<=0)){if(!x||J<0||J-k>iA)return t(`Resync: offset=${J} bChunks=${k} chunk=`+JSON.stringify(x)),v();if(!(J>=k))return _(W-I.fragIndex,!1)}},Me=(x,k,W)=>{u&&u.abort(),u=Ii(this.urlResolver.resolve(x,!0,this.lowLatency),k,W,()=>this._retryCallback()).withTimeout(ds).withRetryCount(tu).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(x,k)=>{Me(S,W=>{if(!c())return;I=W;let J=!!I.lowLatency;J!==this.lowLatency&&b(J);let Se=0;for(let Ce=0;Ce<I.dur.length;++Ce)Se+=I.dur[Ce];Se>0&&(Sr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Se/I.dur.length)),a({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,x(R(k))},()=>this._handleNetworkError())},nextChunk:q}},A=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),Sr(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:S=>{let{videoElement:I,logger:w}=this.params,$=y(e.jidxUrl),F,V,_,v,R=0,q,Me,ge,x=()=>{q&&(clearTimeout(q),q=void 0);let D=Math.max(aA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),H=R+D,ee=K(),Q=Math.min(1e4,H-ee);R=ee;let De=()=>{u||c()&&$.seek(()=>{c()&&(R=K(),k(),x())})};Q>0?q=window.setTimeout(()=>{this.paused?x():De()},Q):De()},k=()=>{let D;for(;D=$.nextChunk(v);)v=D,Xt(D);let H=$.nextChunk(_);if(H){if(_&&H.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?x():(A(),this._initPlayerWith(e));return}Ce(H)}else x()},W=(D,H)=>{if(!c()||!this.sourceBuffer)return;let ee,Q,De,pt=Ge=>{window.setTimeout(()=>{c()&&W(D,H)},Ge)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),pt(100);else{let Ge=K(),Be=I.currentTime;!this.paused&&I.buffered.length>1&&Me===Be&&Ge-ge>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),Me!==Be&&(Me=Be,ge=Ge);let wt=this._getBufferSizeSec();if(wt>30)w(`Buffered ${wt} seconds; delaying appendBuffer`),pt(2e3);else try{this.sourceBuffer.appendBuffer(D),this.videoPlayStarted?(this.bufferStates.push({ts:Ge,buf:wt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),H&&H()}catch(et){if(et.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),De=this.sourceBuffer.buffered.length,De!==0&&(ee=this.sourceBuffer.buffered.start(0),Q=Be,Q-ee>4&&this.sourceBuffer.remove(ee,Q-3)),pt(1e3);else throw et}}},J=()=>{V&&F&&(w([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(_)]),W(V,function(){V=null,k()}))},Se=D=>e.fragUrlTemplate.replace("%%id%%",D.chunkIdx),Ce=D=>{c()&&h(Se(D),(H,ee)=>{if(c()){if(ee/=1e3,V=H,_=D,n=D.startTS,ee){let Q=Math.min(10,D.dur/ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Q:Q}J()}},()=>this._handleNetworkError())},Xt=D=>{c()&&(Sr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Se(D),!1)))},kt=D=>{c()&&(e.cachedHeader=D,W(D,()=>{F=!0,J()}))};s=!0,$.seek(D=>{if(c()){if(R=K(),!D){x();return}v=D,!ZP(S)||D.startTS>S?Ce(D):(_=D,k())}},S),e.cachedHeader?kt(e.cachedHeader):p(e.headerUrl,kt,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),cs(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,Sr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return cs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,h)=>{let m=K();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,l=!0,u=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(l&&c>o&&Zo(n)<3e4)return;i(c)}l=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&u(),h},notifySwitch:c=>{let p=K();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Ii(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ds).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;de(e,()=>{this.soundProhibitedEvent$.next()}).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((l,u)=>{l.video&&a.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=u,o.push(l))}),o.sort(function(l,u){return l.video&&u.video?u.video.height-l.video.height:u.bitrate-l.bitrate}),o):(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))},tA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as sA,filter as Am,fromEvent as nA,interval as oA,isHigher as uA,isInvariantQuality as lA,isLower as cA,merge as dA,Subject as km,Subscription as pA}from"@vkontakte/videoplayer-shared";var iu=class{constructor(){this.onDroopedVideoFramesLimit$=new km;this.subscription=new pA;this.playing=!1;this.tracks=[];this.forceChecker$=new km;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&&!lA(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&&uA(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(nA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=oA(this.droppedFramesChecker.checkTime).pipe(Am(()=>this.playing),Am(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(sA(this.droppedFramesChecker.checkTime)),i=dA(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])=>cA(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}},ps=iu;import{map as hA,Observable as fA}from"@vkontakte/videoplayer-shared";import{fromEvent as mA}from"@vkontakte/videoplayer-shared";var yr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var bA=(r,e)=>new fA(t=>{if(!window.IntersectionObserver)return;let i={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||yr()))},{...i,...e});a.observe(r);let s=mA(document,"visibilitychange").pipe(hA(n=>!document.hidden||yr())).subscribe(n=>t.next(n));return()=>{a.unobserve(r),s.unsubscribe}}),$e=bA;var PA=["paused","playing","ready"],AA=["paused","playing","ready"],Tr=class{constructor(e){this.subscription=new IA;this.videoState=new L("stopped");this.representations$=new au([]);this.textTracksManager=new we;this.droppedFramesManager=new ps;this.maxSeekBackTime$=new au(1/0);this.zeroTime$=new au(void 0);this.liveOffset=new nt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:$m.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=yt(a.name)??xA(a.video),o=a.bitrate/1e3,l={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:l};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),ru(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(AA.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&PA.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(X(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 l=a?.from;l&&l==="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 l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.dash.reinit(X(this.params.source.url,l))}return;default:return wm(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:$m.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Mm(this.videoState.stateChangeStarted$.pipe(hs(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(hs(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(z(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=ce(this.video);this.subscription.add(this.representations$.pipe(hs(a=>a.map(({track:s})=>s)),Lm(a=>!!a.length),TA()).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(vA(),hs(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(gA({zeroTime:this.zeroTime$.pipe(Lm(ru)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Ke(this.video,this.params.desiredState.isLooped,t)).add(le(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ke(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add($e(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&EA(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 wm(a.to)}},t)).add(Mm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,yA(["init"])).pipe(SA(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),ue(this.video)}createLiveDashPlayer(){let e=new vr({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&&ru(t)?t:Tt(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(i),n||l||s!==o){let u=e.find(({track:d})=>d.id===s)?.representation;Rm(u,"Representations missing"),this.dash.startPlay(u,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Rm(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(X(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Cm=Tr;var Xe=(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)};import{assertNever as tw,assertNonNullable as iw,debounce as rw,ErrorCategory as Cu,filter as Yb,filterChanged as Du,fromEvent as aw,isNonNullable as sw,map as zb,merge as Ds,observableFrom as nw,observeElementSize as ow,once as Kb,Subscription as uw,ValueSubject as lw}from"@vkontakte/videoplayer-shared";var fs=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}},Ei=class extends fs{constructor(){super(),this.listeners||fs.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)}},Ir=class{constructor(){Object.defineProperty(this,"signal",{value:new Ei,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&&(Ir.prototype[Symbol.toStringTag]="AbortController",Ei.prototype[Symbol.toStringTag]="AbortSignal");function ms(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 su(r){typeof r=="function"&&(r={fetch:r});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!ms({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 c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(u,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let d=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(c),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(l,u)])}return n(l,u)},Request:s}}var Er=ms({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Dm=Er?su({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ut=Er?Dm.fetch:window.fetch,p0=Er?Dm.Request:window.Request,Ue=Er?Ir:window.AbortController,h0=Er?Ei:window.AbortSignal;var Ss=Ye(hr(),1);var lt=()=>window.ManagedMediaSource||window.MediaSource,bs=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Bm=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Om=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ts,clientChecker as vs}from"@vkontakte/videoplayer-shared";var ys=document.createElement("video"),RA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',$A='video/mp4; codecs="hev1.1.6.L93.B0"',Vm='video/webm; codecs="vp09.00.10.08"',_m='video/webm; codecs="av01.0.00M.08"',LA='audio/mp4; codecs="mp4a.40.2"',MA='audio/webm; codecs="opus"',qt={mms:bs(),mse:Bm(),hls:!!(ys.canPlayType?.("application/x-mpegurl")||ys.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},pe={mp4:!!ys.canPlayType?.("video/mp4"),webm:!!ys.canPlayType?.("video/webm"),cmaf:!0},he={h264:!!lt()?.isTypeSupported?.(RA),h265:!!lt()?.isTypeSupported?.($A),vp9:!!lt()?.isTypeSupported?.(Vm),av1:!!lt()?.isTypeSupported?.(_m),aac:!!lt()?.isTypeSupported?.(LA),opus:!!lt()?.isTypeSupported?.(MA)},xi=(he.h264||he.h265)&&he.aac,Ut,CA=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:_m}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:Vm}})]);Ut={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{CA()}catch(r){console.error(r)}var Pi=qt.hls&&pe.mp4,Nm=()=>Object.keys(he).filter(r=>he[r]),Fm=(r,e=!1,t=!1)=>{let i=qt.mse||qt.mms&&t;return r.filter(a=>{switch(a){case"DASH_SEP":return i&&pe.mp4&&xi;case"DASH_WEBM":return i&&pe.webm&&he.vp9&&he.opus;case"DASH_WEBM_AV1":return i&&pe.webm&&he.av1&&he.opus;case"DASH_STREAMS":return i&&(pe.mp4&&xi||pe.webm&&(he.vp9||he.av1)&&(he.opus||he.aac));case"DASH_LIVE":return qt.mse&&pe.mp4&&xi;case"DASH_LIVE_CMAF":return i&&pe.mp4&&xi&&pe.cmaf;case"DASH_ONDEMAND":return i&&pe.mp4&&xi;case"HLS":case"HLS_ONDEMAND":return Pi||e&&qt.mse&&pe.mp4&&xi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Pi;case"MPEG":return pe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return qt.webrtc&&qt.ws&&he.h264&&(pe.mp4||pe.webm);default:return Ts(a)}})},gs=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 Ut?Ut[t].smooth?[t,e]:Ut[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ut?Ut[t].powerEfficient?[t,e]:Ut[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ts(r)}return[e,t]},qm=({webmCodec:r,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...gs(r),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(vs.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",...gs(r),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...gs(r),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...gs(r),...a,"HLS","HLS_ONDEMAND"];default:Ts(e)}return Pi?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Um=({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,l=vs.isMac&&vs.isSafari;if(vs.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:Ts(r)}else Pi&&!l?o=n:l?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},nu=r=>r?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Hm=r=>{if(r.size===0)return;if(r.size===1){let t=r.values().next();return(0,Ss.default)(t.value.split("."),0)}for(let t of r){let i=(0,Ss.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=r.values().next();return(0,Ss.default)(e.value.split("."),0)};import{ErrorCategory as xr}from"@vkontakte/videoplayer-shared";var jm=r=>{if(!r)return{id:"EmptyResponse",category:xr.PARSER,message:"Empty response"};if(r.length<=2&&r.match(/^\d+$/))return{id:`UVError#${r}`,category:xr.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:xr.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:xr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:xr.PARSER,message:"Response is valid XML, but parser failed"}};var Ai=(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};import{abortable as Ru,assertNonNullable as Kt,clientChecker as jk,combine as Rs,ErrorCategory as dt,filter as $u,filterChanged as Ub,flattenObject as ta,fromEvent as Ci,getTraceSubscriptionMethod as Gk,interval as Lu,isNonNullable as Hb,map as Mu,merge as Di,now as Wk,Subject as jb,Subscription as Gb,tap as Qk,throttle as Yk,ValueSubject as Z}from"@vkontakte/videoplayer-shared";var Li=Ye(hr(),1);var DA=(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)},BA=r=>window.clearTimeout(r),Gm=r=>typeof r=="function"&&r?.toString().endsWith("{ [native code] }"),Wm=!Gm(window.requestIdleCallback)||!Gm(window.cancelIdleCallback),ou=Wm?DA:window.requestIdleCallback,k0=Wm?BA:window.cancelIdleCallback;var Bb=Ye(ss(),1);import{assertNever as OA,ErrorCategory as Qm,clientChecker as uu,Subject as Ym}from"@vkontakte/videoplayer-shared";var VA=16,zm=!1;try{zm=uu.isSafari&&!!uu.macVersion&&uu.macVersion<=VA}catch(r){console.error(r)}var lu=class{constructor(e){this.bufferFull$=new Ym;this.error$=new Ym;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:Qm.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;zm&&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:Qm.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:OA(t)}}},Km=lu;var cu=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};import{abortable as Wt,assertNonNullable as fe,ErrorCategory as Qt,fromEvent as xu,getExponentialDelay as Pu,isNonNullable as Qr,isNullable as me,now as xs,once as Dk,Subject as Bk,Subscription as Ok,ValueSubject as Yr}from"@vkontakte/videoplayer-shared";var O=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 ki=class extends O{};var Pr=class extends O{};var Ar=class extends O{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 kr=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wr=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Rr=class extends O{constructor(e,t){super(e,t),this.data=this.content}};var G=class extends O{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ht=class extends G{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 l=a>>>28,u=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:u})}}};var $r=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Lr=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mr=class extends G{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 Cr=class extends G{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Dr=class extends G{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Br=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Or=class extends G{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 Vr=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _r=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Nr=class extends G{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Fr=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qr=class extends G{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 Ur=class extends G{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 Hr=class extends G{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 NA={ftyp:Ar,moov:kr,moof:wr,mdat:Rr,sidx:Ht,trak:$r,mdia:Br,mfhd:Nr,tkhd:Or,traf:Fr,tfhd:qr,tfdt:Ur,trun:Hr,minf:Vr,sv3d:Lr,st3d:Mr,prhd:Cr,proj:_r,equi:Dr,uuid:Pr,unknown:ki},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=NA[e];return i?new i(t,new r):new ki(t,new r)}};var wi=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 qA=new TextDecoder("ascii"),UA=r=>qA.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",HA=r=>{let e=new Ht(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})},jA=(r,e)=>{let i=new jt().parse(r),a=new wi(i),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],l=n[n.length-1],u=o.source.byteOffset,c=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(r.buffer,u,c)},GA=(r,e)=>{let i=new jt().parse(r),s=new wi(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),l=s[s.length-1].children.find(c=>c.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((c,p)=>c+p,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},WA=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 wi(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 l=a.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},Jm={validateData:UA,parseInit:WA,getIndexRange:()=>{},parseSegments:HA,parseFeedableSegmentChunk:jA,getSegmentEndTime:GA};import{assertNonNullable as pu,isNonNullable as tb,isNullable as YA}from"@vkontakte/videoplayer-shared";import{assertNever as QA}from"@vkontakte/videoplayer-shared";var Xm={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"}},Zm=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=jr(r,t),a=i in Xm,s=a?Xm[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 l=new DataView(r.buffer,r.byteOffset+t+1,o-1),u=n&255>>o,d=jr(l),c=u*2**((o-1)*8)+d,p=t+o,h;return p+c>r.byteLength?h=new DataView(r.buffer,r.byteOffset+p):h=new DataView(r.buffer,r.byteOffset+p,c),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},jr=(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},He=(r,e)=>{switch(e){case"int":return r.getInt8(0);case"uint":return jr(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:QA(e)}},Gt=(r,e)=>{let t=0;for(;t<r.byteLength;){let i=new DataView(r.buffer,r.byteOffset+t),a=Zm(i);if(!e(a))return;a.type==="master"&&Gt(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},eb=r=>{if(r.getUint32(0)!==440786851)return!1;let e,t,i,a=Zm(r);return Gt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=He(o,n):s===17026?t=He(o,n):s===17029&&(i=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var ib=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],zA=[231,22612,22743,167,171,163,160,175],KA=r=>{let e,t,i,a,s=!1,n=!1,o=!1,l,u,d=!1,c=0;return Gt(r,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=He(m,h);u=jr(g)}else p!==21420&&(u=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=He(m,h):p===17545?a=He(m,h):p===21420&&u===475249515?l=He(m,h):p===374648427?Gt(m,({tag:g,type:y,value:A})=>g===30321?(d=He(A,y)===1,!1):!0):s&&n&&ib.includes(p)&&(o=!0),!o}),pu(e,"Failed to parse webm Segment start"),pu(t,"Failed to parse webm Segment end"),pu(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:l,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},JA=r=>{if(YA(r.cuesSeekPosition))return;let e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},XA=(r,e)=>{let t=!1,i=!1,a=o=>tb(o.time)&&tb(o.position),s=[],n;return Gt(r,({tag:o,type:l,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=He(u,l));break;case 183:break;case 241:n&&(n.position=He(u,l));break;default:t&&ib.includes(o)&&(i=!0)}return!(t&&i)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:d}=o,c=s[l+1];return{status:"none",time:{from:u,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},ZA=r=>{let e=0,t=!1;try{Gt(r,i=>i.tag===524531317?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):zA.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},rb={validateData:eb,parseInit:KA,getIndexRange:JA,parseSegments:XA,parseFeedableSegmentChunk:ZA};var Ri=r=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(r);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return rb;case"mp4":return Jm}}throw new ReferenceError(`Unsupported mime type ${r}`)};var vu=Ye(Pb(),1);var Su=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};import{isNonNullable as kb,isNullable as wb}from"@vkontakte/videoplayer-shared";var Ab=r=>{if(r.includes("/")){let e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};var Rb=r=>{if(!r.startsWith("P"))return;let e=(n,o)=>{let l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*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},ct=(r,e)=>{let t=r;t=(0,vu.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,vu.default)(t,n,(o,l)=>wb(s)?o:wb(l)?s:s.padStart(parseInt(l,10),"0"))}return t},$b=(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()??"",l=n.children,u=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),c=d?new Date(d).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Rb(h);else if(m){let S=Rb(m);kb(S)&&(p=S)}else g&&(p=parseInt(g,10));let y=0,A=s.getAttribute("profiles")?.split(",")??[];for(let S of l){let I=S.getAttribute("id")??"id"+(y++).toString(10),w=S.getAttribute("mimeType")??"",$=S.getAttribute("codecs")??"",F=S.getAttribute("contentType")??w?.split("/")[0],V=S.getAttribute("profiles")?.split(",")??[],_=S.getAttribute("lang")??void 0,v=S.querySelector("Label")?.textContent?.trim()??void 0,R=S.querySelectorAll("Representation"),q=S.querySelector("SegmentTemplate"),Me=S.querySelector("Role")?.getAttribute("value")??void 0,ge=F,x={id:I,language:_,isDefault:Me==="main",label:v,codecs:$,hdr:ge==="video"&&Su($),mime:w,representations:[]};for(let k of R){let W=k.getAttribute("lang")??void 0,J=k.getAttribute("label")??void 0,Se=k.querySelector("BaseURL")?.textContent?.trim()??"",Ce=new URL(Se||o,e).toString(),Xt=k.getAttribute("mimeType")??w,kt=k.getAttribute("codecs")??$??"",D;if(F==="text"){let H=k.getAttribute("id")||"",ee=H.includes("_auto"),Q=k.querySelector("SegmentTemplate");if(Q){let De={representationId:k.getAttribute("id")??void 0,bandwidth:k.getAttribute("bandwidth")??void 0},pt=parseInt(k.getAttribute("bandwidth")??"",10)/1e3,Ge=parseInt(Q.getAttribute("startNumber")??"",10)??1,Be=parseInt(Q.getAttribute("timescale")??"",10),wt=Q.querySelectorAll("SegmentTimeline S")??[],et=Q.getAttribute("media");if(!et)continue;let ba=[],ga=0,Sa="",Zt=0,Vi=Ge,te=0;for(let Oe of wt){let Rt=parseInt(Oe.getAttribute("d")??"",10),Ee=parseInt(Oe.getAttribute("r")??"",10)||0,ht=parseInt(Oe.getAttribute("t")??"",10);te=Number.isFinite(ht)?ht:te;let $t=Rt/Be*1e3,ei=te/Be*1e3;for(let We=0;We<Ee+1;We++){let ft=ct(et,{...De,segmentNumber:Vi.toString(10),segmentTime:(te+We*Rt).toString(10)}),ti=(ei??0)+We*$t,Ni=ti+$t;Vi++,ba.push({time:{from:ti,to:Ni},url:ft})}te+=(Ee+1)*Rt,ga+=(Ee+1)*$t}Zt=te/Be*1e3,Sa=ct(et,{...De,segmentNumber:Vi.toString(10),segmentTime:te.toString(10)});let _i={time:{from:Zt,to:1/0},url:Sa},tt={type:"template",baseUrl:Ce,segmentTemplateUrl:et,initUrl:"",totalSegmentsDurationMs:ga,segments:ba,nextSegmentBeyondManifest:_i,timescale:Be};D={id:H,kind:"text",segmentReference:tt,profiles:[],duration:p,bitrate:pt,mime:"",codecs:"",width:0,height:0,isAuto:ee}}else D={id:H,isAuto:ee,kind:"text",url:Ce}}else{let H=k.getAttribute("contentType")??Xt?.split("/")[0]??F,ee=S.getAttribute("profiles")?.split(",")??[],Q=parseInt(k.getAttribute("width")??"",10),De=parseInt(k.getAttribute("height")??"",10),pt=parseInt(k.getAttribute("bandwidth")??"",10)/1e3,Ge=k.getAttribute("frameRate")??"",Be=k.getAttribute("quality")??void 0,wt=Ge?Ab(Ge):void 0,et=k.getAttribute("id")??"id"+(y++).toString(10),ba=H==="video"?`${De}p`:H==="audio"?`${pt}Kbps`:kt,ga=`${et}@${ba}`,Sa=[...A,...V,...ee],Zt,Vi=k.querySelector("SegmentBase"),te=k.querySelector("SegmentTemplate")??q;if(Vi){let tt=k.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Oe,Rt]=tt.split("-").map(ft=>parseInt(ft,10)),Ee={from:Oe,to:Rt},ht=k.querySelector("SegmentBase")?.getAttribute("indexRange"),[$t,ei]=ht?ht.split("-").map(ft=>parseInt(ft,10)):[],We=ht?{from:$t,to:ei}:void 0;Zt={type:"byteRange",url:Ce,initRange:Ee,indexRange:We}}else if(te){let tt={representationId:k.getAttribute("id")??void 0,bandwidth:k.getAttribute("bandwidth")??void 0},Oe=parseInt(te.getAttribute("timescale")??"",10),Rt=te.getAttribute("initialization")??"",Ee=te.getAttribute("media"),ht=parseInt(te.getAttribute("startNumber")??"",10)??1,$t=ct(Rt,tt);if(!Ee)throw new ReferenceError("No media attribute in SegmentTemplate");let ei=te.querySelectorAll("SegmentTimeline S")??[],We=[],ft=0,ti="",Ni=0;if(ei.length){let va=ht,Ve=0;for(let ii of ei){let Qe=parseInt(ii.getAttribute("d")??"",10),Lt=parseInt(ii.getAttribute("r")??"",10)||0,ya=parseInt(ii.getAttribute("t")??"",10);Ve=Number.isFinite(ya)?ya:Ve;let zs=Qe/Oe*1e3,Ug=Ve/Oe*1e3;for(let Ta=0;Ta<Lt+1;Ta++){let Hg=ct(Ee,{...tt,segmentNumber:va.toString(10),segmentTime:(Ve+Ta*Qe).toString(10)}),Ku=(Ug??0)+Ta*zs,jg=Ku+zs;va++,We.push({time:{from:Ku,to:jg},url:Hg})}Ve+=(Lt+1)*Qe,ft+=(Lt+1)*zs}Ni=Ve/Oe*1e3,ti=ct(Ee,{...tt,segmentNumber:va.toString(10),segmentTime:Ve.toString(10)})}else if(kb(p)){let Ve=parseInt(te.getAttribute("duration")??"",10)/Oe*1e3,ii=Math.ceil(p/Ve),Qe=0;for(let Lt=1;Lt<ii;Lt++){let ya=ct(Ee,{...tt,segmentNumber:Lt.toString(10),segmentTime:Qe.toString(10)});We.push({time:{from:Qe,to:Qe+Ve},url:ya}),Qe+=Ve}Ni=Qe,ti=ct(Ee,{...tt,segmentNumber:ii.toString(10),segmentTime:Qe.toString(10)})}let qg={time:{from:Ni,to:1/0},url:ti};Zt={type:"template",baseUrl:Ce,segmentTemplateUrl:Ee,initUrl:$t,totalSegmentsDurationMs:ft,segments:We,nextSegmentBeyondManifest:qg,timescale:Oe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!H||!Xt)continue;let _i={video:"video",audio:"audio",text:"text"}[H];if(!_i)continue;ge||=_i,D={id:ga,kind:_i,segmentReference:Zt,profiles:Sa,duration:p,bitrate:pt,mime:Xt,codecs:kt,width:Q,height:De,fps:wt,quality:Be}}x.language||=W,x.label||=J,x.mime||=Xt,x.codecs||=kt,x.hdr||=ge==="video"&&Su(kt),x.representations.push(D)}ge&&a[ge].push(x)}return{dynamic:u,liveAvailabilityStartTime:c,duration:p,streams:a}};var Gr=Ye(hr(),1);import{videoSizeToQuality as Ck}from"@vkontakte/videoplayer-shared";var Lb=({id:r,width:e,height:t,bitrate:i,fps:a,quality:s})=>{let n=(s?yt(s):void 0)??Ck({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:a}},Mb=({id:r,bitrate:e})=>({id:r,bitrate:e}),Is=(r,e,t)=>{let i=e.indexOf(r);return(0,Gr.default)(t,Math.round(t.length*i/e.length))??(0,Gr.default)(t,-1)},Cb=({language:r,label:e},{id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),Db=({language:r,label:e,id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),Iu=({id:r,language:e,label:t,codecs:i,isDefault:a})=>({id:r,language:e,label:t,codec:(0,Gr.default)(i.split("."),0),isDefault:a}),Eu=({id:r,language:e,label:t,hdr:i,codecs:a})=>({id:r,language:e,hdr:i,label:t,codec:(0,Gr.default)(a.split("."),0)}),Es=r=>"url"in r,Le=r=>r.type==="template",Wr=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);var zr=class{constructor(e,t,i,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:l=!1,manifest:u}){this.currentSegmentLength$=new Yr(0);this.onLastSegment$=new Yr(!1);this.fullyBuffered$=new Yr(!1);this.playingRepresentation$=new Yr(void 0);this.playingRepresentationInit$=new Yr(void 0);this.error$=new Bk;this.gaps=[];this.subscription=new Ok;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ue;this.switchAbortController=new Ue;this.destroyAbortController=new Ue;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=Wt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);fe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Km(this.sourceBuffer),this.subscription.add(xu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,l=this.mediaSource.readyState;l!=="open"&&(o={id:`SegmentEjection_source_${l}`,category:Qt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Qt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(xu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Qt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let l=Math.min(this.bufferLimit,cu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=l,this.tuning.useNewPruneBufferStrategy){let u=Xe(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);fe(i,"No init buffer for starting representation"),fe(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.switchToOld=Wt(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);fe(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(me(s)||me(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),fe(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();Qr(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=Wt(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(l=>l.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let u=t.find(p=>p.id===l);u&&this.representations.set(l,u);let d=this.representations.get(l);if(!d||!Le(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(i);fe(a);let s=this.segments.get(i);fe(s,"No segments for starting representation");let n=this.initData.get(i);if(fe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=l,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.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}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ue,Wt(this.switchAbortController.signal,async function*(i,a=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);fe(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(me(o)||me(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),fe(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let l=this.getCurrentPosition();Qr(l)&&!this.isLive&&(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield this.pruneBuffer(l,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0,this.maintain(l)}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ue,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(me(e)||me(this.downloadingRepresentationId)||me(this.playingRepresentationId)||me(this.sourceBuffer)||Qr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(fe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let 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=Xe(this.sourceBuffer.buffered,e),c=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=c)}if(isFinite(this.bufferLimit)&&cu(this.sourceBuffer.buffered)>=this.bufferLimit){let u=Xe(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,Li.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&&Xe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Li.default)(i,-1);l&&l.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===l))}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;Qr(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||!Le(i.segmentReference))return;let a=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=this.segments.get(i.id)??[],n=(0,Li.default)(s,-1)?.time.to??0,o=a?.findIndex(l=>Math.floor(n)>=Math.floor(l.time.from)&&Math.floor(n)<=Math.floor(l.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=a.slice(o+1);this.segments.set(i.id,[...s,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;fe(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(!Le(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),l=ct(i.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let 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.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(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:c,time:{from:p,to:h}},m)=>{let b=p<=i&&h>=i,g=p>i||b||m===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=i+y||h<=i+y;return(c==="none"||c==="partially_ejected"&&g&&A&&this.sourceBuffer&&!(Ai(this.sourceBuffer.buffered,p)&&Ai(this.sourceBuffer.buffered,h)))&&g&&A});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=a;c<s.length&&(n<=u||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Le(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:l,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Wt(o,async function*(){let d=Pu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:l,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=xs(),!d)return;let c=new DataView(d);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,h=Ri(t.mime);a.segment.time.to=h.getSegmentEndTime(c,p)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(c,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Wr(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let l of e)l.status="downloading",this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Wt(n,async function*(){let l=Pu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),xu(window,"online").pipe(Dk()).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=xs(),this.failedDownloads=0}catch(l){this.abortActiveSegments(e),Wr(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Le(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,a={from:(0,Li.default)(e,0).byte.from,to:(0,Li.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:a,signal:s,onProgress:(o,l)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xs(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Qt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Le(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=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xs();let c=this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Qt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:a,signal:s,onProgress:l,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded: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:l}=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=Ri(n.mime).parseFeedableSegmentChunk(u,this.isLive);d?.byteLength&&(l.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom: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 l=o.segmentReference.type,u=e.byteLength;for(let d of this.activeSegments){let{segment:c}=d,p=l==="byteRange",h=p?c.byte.to-c.byte.from+1:u;if(d.representationId!==t||!(!p||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(s.aborted){n();continue}let b=p?c.byte.from-i:0,g=p?c.byte.to-i:e.byteLength,y=b<a,A=g<=a;if(c.status==="downloading"&&y&&A){c.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+b,h),S=this.getCurrentPosition();Qr(S)&&(this.bufferAccumulation.accumulatedBufferSizeMs=c.time.to-S,this.bufferAccumulation.accumulated.push({segmentView:T,segmentProgress:d}),this.activeSegments.delete(d));let I=({segmentView:w,segmentProgress:$})=>this.sourceBufferTaskQueue.append(w,s).then(F=>F&&!s.aborted?this.onSegmentFullyAppended($,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(I),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||me(S))&&(I({segmentView:T,segmentProgress:d}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&!A&&(d.loadedBytes=Math.min(h,a-b),d.loadedBytes>d.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+b+d.feedingBytes,d.loadedBytes-d.feedingBytes),S=d.loadedBytes===h?T:Ri(o.mime).parseFeedableSegmentChunk(T);S?.byteLength&&(c.status="partially_fed",d.feedingBytes+=S.byteLength,this.sourceBufferTaskQueue.append(S,s).then(I=>{if(s.aborted)n();else if(I)d.fedBytes+=S.byteLength,d.fedBytes===h&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<h)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 l of this.activeSegments){let{segment:u}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=u.byte.from-i,c=u.byte.to-i,p=c-d+1,h=d<a,m=c<=a;if(h){if(u.status==="downloading"&&m){u.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(l.loadedBytes=Math.min(p,a-d),l.loadedBytes>l.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),g=l.loadedBytes===p?b:Ri(o.mime).parseFeedableSegmentChunk(b);g?.byteLength&&(u.status="partially_fed",l.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(l.fedBytes+=g.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):n())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Es(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");fe(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=ou(()=>(0,Bb.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?Wt(this.destroyAbortController.signal,async function*(){let o=Pu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ri(e.mime),a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:d}=o,c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&Le(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Qt.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||me(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=l=>{l.sort((d,c)=>d.from-c.from);let u=[l[0]];for(let d=1;d<l.length;d++){let{from:c,to:p}=l[d],h=u[u.length-1];h.to>=c?h.to=Math.max(h.to,p):u.push(l[d])}return u},o=l=>{if(s>=t)return a;a.push({...l.time}),a=n(a);let u=Es(l)?l.size??0:l.byte.to-l.byte.from;s+=u};for(let l of this.segments.values())for(let u of l){let d=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&u.status==="fed"&&o(u)}for(let l=0;l<this.sourceBuffer.buffered.length;l++){let u=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3,c=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:u,to:d},url:"",status:"none"};o(p)}}if(a.length&&i){let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let d of u)d.time.from>=e+l&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,d)=>u||d,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||me(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,l=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let d=Es(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status==="fed"&&l(d)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status==="fed"&&l(d)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(c)){s=d,n=c;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 c of d)c.time.from>e+u&&c.status==="fed"&&l(c)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||me(e)?0:Xe(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){fe(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=ou(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Qt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(me(this.sourceBuffer)||me(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),l=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);l||(u.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Kr=r=>{let e=new URL(r);return e.searchParams.set("quic","1"),e.toString()};var Ob=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}};import{abortable as Jr,assertNever as Vb,fromEvent as _b,merge as Vk,now as Xr,Subscription as _k,ValueSubject as Au,flattenObject as Mi}from"@vkontakte/videoplayer-shared";var Ps=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:a=!1}){this.lastConnectionType$=new Au(void 0);this.lastConnectionReused$=new Au(void 0);this.lastRequestFirstBytes$=new Au(void 0);this.abortAllController=new Ue;this.subscription=new _k;this.fetchManifest=Jr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Kr(i));let a=yield ut(i,{signal:this.abortAllController.signal}).catch(Zr);return a?(t.log("success",Mi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Mi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Jr(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:l=!1}={}){let u=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(u,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),u=v.toString();break}default:Vb(t)}this.requestQuic&&(u=Kr(u));let p=this.abortAllController.signal,h;if(n){let v=new Ue;if(h=Vk(_b(this.abortAllController.signal,"abort"),_b(n,"abort")).subscribe(()=>{try{v.abort()}catch(R){Zr(R)}}),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(R){Zr(R)}p=v.signal}let m=Xr();c.log("startRequest",Mi({url:u,priority:s,rangeMethod:t,range:i,isLowLatency:l,requestStartedAt:m}));let b=yield ut(u,{priority:s,headers:d,signal:p}).catch(Zr),g=Xr();if(!b)return c.error("error",{message:"No response in request"}),c.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-m),!b.ok||!b.body){h?.unsubscribe();let v=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:v}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let v=Xr(),R={requestStartedAt:m,requestEndedAt:v,duration:v-m};return c.log("endRequest",Mi(R)),c.end(),b.arrayBuffer()}let[y,A]=b.body.tee(),T=y.getReader();o&&this.throughputEstimator?.trackStream(A,l);let S=0,I=new Uint8Array(0),w=!1,$=v=>{h?.unsubscribe(),w=!0,Zr(v)},F=Jr(p,async function*({done:v,value:R}){if(S===0&&this.lastRequestFirstBytes$.next(Xr()-m),p.aborted){h?.unsubscribe();return}if(!v&&R){let q=new Uint8Array(I.length+R.length);q.set(I),q.set(R,I.length),I=q,S+=R.byteLength,a?.(new DataView(I.buffer),S),yield T?.read().then(F,$)}}.bind(this));yield T?.read().then(F,$),h?.unsubscribe();let V=Xr(),_={failed:w,requestStartedAt:m,requestEndedAt:V,duration:V-m};return w?(c.error("endRequest",Mi(_)),c.end(),null):(c.log("endRequest",Mi(_)),c.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=Jr(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,l=!1,u,d;e.indexRange&&(u=e.indexRange.from,d=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,a),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(l)b=new DataView(c,m.from-n,m.to-m.from+1);else{let y=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=Jr(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}=Ob(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:Vb(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Zr=r=>{if(!Wr(r))throw r};var Yt=(r,e,t)=>t*e+(1-t)*r,ku=(r,e)=>r.reduce((t,i)=>t+i,0)/e,Nb=(r,e,t,i)=>{let a=0,s=t,n=ku(r,e),o=e<i?e:i;for(let l=0;l<o;l++)r[s]>n?a++:a--,s=(r.length+s-1)%r.length;return Math.abs(a)===o};import{isNullable as Nk,ValueSubject as Fb}from"@vkontakte/videoplayer-shared";var It=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 Fb(e.initial),this.debounced$=new Fb(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new re(`raw_${t}`),this.smoothedSeries$=new re(`smoothed_${t}`),this.reportedSeries$=new re(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let 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)&&(Nk(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 As=class extends It{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Yt(this.slow,e,this.params.emaAlphaSlow),this.fast=Yt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ks=class extends It{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ku(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Yt(this.emaSmoothed,e,this.params.emaAlpha);let i=Nb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ws=class extends It{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?Yt(this.smoothed,t,this.params.emaAlpha):t}};var zt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new As({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ks({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 ws({initial:e,label:"liveEdgeDelay",...t})}};var wu=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)};import{isNullable as Fk,ValueSubject as qk}from"@vkontakte/videoplayer-shared";var ea=class r{constructor(e,t){this.currentRepresentation$=new qk(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(!Fk(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 l=a.segments.find(u=>u.time.from<=e&&u.time.to>=e);!l||this.currentSegment?.time.from===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){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&&Le(t.segmentReference))}};var zk=["timeupdate","progress","play","seeked","stalled","waiting"],Kk=["timeupdate","progress","loadeddata","playing","seeked"];var $s=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Gb;this.representationSubscription=new Gb;this.state$=new L("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new jb;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.liveDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(void 0);this.bufferLength$=new Z(0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.isActiveLowLatency$=new Z(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new jb;this.gapWatchdogActive=!1;this.destroyController=new Ue;this.initManifest=Ru(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=X(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:dt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ru(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:dt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=$b(e??"",this.manifestUrlString)}catch(n){let o=jm(e)??{id:"ManifestParsing",category:dt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,l)=>!!(this.element?.canPlayType?.(o)&&lt()?.isTypeSupported?.(`${o}; codecs="${l}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let l=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p)),u=new Set(l.map(({codecs:c})=>c)),d=Hm(u);if(d&&(a[n]=l.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=a.video.some(m=>m.hdr),h=a.video.some(m=>!m.hdr);jk.isHDR&&c&&p?a.video=a.video.filter(m=>m.hdr):h&&(a.video=a.video.filter(m=>!m.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",ta(s)),s}.bind(this));this.initRepresentations=Ru(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ta({initialVideo:e,initialAudio:t,sourceHls:i})),Kt(this.manifest),Kt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=c=>{this.representationSubscription.add(Ci(c,"error").pipe($u(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?Om():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&bs())if(i){let c=document.createElement("source");a(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new zr("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Hb(t)){let c=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new zr("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(ea.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new ea(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(Lu(1e3).subscribe(c=>{if(this.element?.paused){let p=Fo(this.manifestUrlString,2);this.manifestUrlString=X(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(Di(...Kk.map(c=>Ci(this.element,c))).pipe(Mu(c=>this.element?Xe(this.element.buffered,this.element.currentTime*1e3):0),Ub(),Qk(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&(this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ub()).subscribe(p=>wu(this.element,1))),this.representationSubscription.add(Rs({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe($u(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(Rs({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:h})=>{if(!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=p-m,A=1;Math.abs(y)>b&&(A=1+Math.sign(y)*g),wu(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add(Rs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Yk(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(Kt(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,b=Fo(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,S=isFinite(p)?p:h,I=this.isActiveLowLatency$.getValue(),w=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(I&&w);let $="none";if(I?$="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&w?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),$="active_low_latency"):b!==0&&S<y?$="live_forward_buffering":S<y+T&&($="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),$==="live_forward_buffering"||$==="live_with_target_offset"){let F=c-(y+A),V=this.normolizeLiveOffset(Math.trunc(b+F/m)),_=Math.abs(V-b),v;!p||_<=this.tuning.dashCmafLive.offsetCalculationError?v=b:V>0&&_>this.tuning.dashCmafLive.offsetCalculationError?v=V:v=0,this.manifestUrlString=X(this.manifestUrlString,v,2)}$!=="none"&&$!=="active_low_latency"&&(c=0,this.updateLive())}))}let l=Di(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Mu(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),u=Di(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Mu(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue())));this.representationSubscription.add(Di(this.forceEnded$,Rs({allBuffersFull:l,someBufferEnded:u}).pipe($u(({allBuffersFull:c,someBufferEnded:p})=>c&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Di(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(c=>this.source?.addEventListener("sourceopen",c)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(c=>c.representations).flatMap(c=>{let p=[];return c.duration&&p.push(c.duration),Le(c.segmentReference)&&c.segmentReference.totalSegmentsDurationMs&&p.push(c.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&Hb(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=Lu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:dt.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 Ps({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=zt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){Kt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=X(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(){Kt(this.element),this.state$.setState("running"),this.subscription.add(Di(...zk.map(e=>Ci(this.element,e)),Ci(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ci(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ci(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ai(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=Wk(),a=100,s=this.videoBufferManager?.lastDataObtainedTimestamp??0,n=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,u=o<a&&i-s>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<a&&i-n>this.tuning.dash.crashOnStallTWithoutDataTimeout;if(this.tuning.useNewProviderReinitLogic&&(u||d)&&this.timeInWaiting>this.tuning.dash.crashOnStallTWithoutDataTimeout||this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.timeInWaiting} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),t={...t,liveLastSeekOffset:this.liveLastSeekOffset};else{let c=this.element.currentTime*1e3;this.videoBufferManager?.maintain(c),this.audioBufferManager?.maintain(c),t={...t,position:c}}this.tracer.log("stallIntervalCallback",ta(t))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Lu(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:this.tuning.useNewProviderReinitLogic?dt.NETWORK:dt.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){Kt(this.element),Kt(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),Ai(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",ta({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=Gk(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",ta(t)))}}};var Ls=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ms=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 Wb=`attribute vec2 a_vertex;
58
+ `}),h&&Tm(a,u,h,o)};var z=r=>new URL(r).hostname;import{assertNever as wm,assertNonNullable as Rm,combine as SA,debounce as vA,ErrorCategory as $m,filter as Lm,filterChanged as yA,isNonNullable as ru,map as hs,merge as Mm,observableFrom as TA,once as IA,Subscription as EA,ValueSubject as au,videoQualityToHeight as xA,videoSizeToQuality as PA}from"@vkontakte/videoplayer-shared";var Em=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"))},de=async(r,e)=>{let t=r.muted;try{await r.play()}catch(i){if(!Em(i))return!1;if(e&&e(),t)return console.warn(i),!1;r.muted=!0;try{await r.play()}catch(a){return Em(a)&&(r.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as cs,isNullable as eA,assertNonNullable as Sr}from"@vkontakte/videoplayer-shared";import{isNonNullable as xm,assertNonNullable as ls,now as XP}from"@vkontakte/videoplayer-shared";function K(){return XP()}function Zo(r){return K()-r}function eu(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,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Pm(r,e,t){let i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Ii(r,e,t,i){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;ls(d);let R=Zo(d),q;if(R<b){q=b-R,setTimeout(g,q);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new a,w()},y=R=>(s=R,v),A=R=>(c=R,v),T=()=>(h="json",v),S=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},I=R=>(p=R,v),w=()=>{d=K(),n=new a,n.open("get",r);let R=0,q,Me=0,ge=()=>(ls(d),Math.max(d,Math.max(q||0,Me||0)));if(s&&n.addEventListener("progress",x=>{let k=K();s.updateChunk&&x.loaded>R&&(s.updateChunk(ge(),x.loaded-R),R=x.loaded,q=k)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>S())),n.addEventListener("load",()=>{if(u)return;ls(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let k=n.response.byteLength-R;k&&s.updateChunk&&s.updateChunk(ge(),k)}n.responseType==="json"&&!Object.values(n.response).length?S():(c&&c(),e(n.response))}else S()}),n.addEventListener("error",()=>{S()}),p){let x=()=>{ls(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Me=K(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),v},v={withBitrateReporting:y,withParallel:I,withJSONResponse:T,withRetryCount:R=>(l=R,v),withRetryInterval:(R,q)=>(xm(R)&&(b=R),xm(q)&&(m=q),v),withTimeout:R=>(o=R,v),withFinally:A,send:w,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return v}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 u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}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=K(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=K()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ii(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=K()}_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=K();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}};import{Subject as tA}from"@vkontakte/videoplayer-shared";var ds=1e4,tu=3;var iA=6e4,rA=10,aA=1,sA=500,vr=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.soundProhibitedEvent$=new tA,this.chunkRateEstimator=new br(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=eu(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=eu(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||cs(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=()=>{Pm(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(tu,ds,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,u=null,l=null,d=!1,c=()=>{let S=s&&(!d||d===this.rep);return S||t("Not running!"),S},p=(S,I,w)=>{u&&u.abort(),u=Ii(this.urlResolver.resolve(S,!1),I,w,()=>this._retryCallback()).withTimeout(ds).withBitrateReporting(this.bitrateSwitcher).withRetryCount(tu).withFinally(()=>{u=null}).send()},h=(S,I,w)=>{Sr(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(S,!1),I,w,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=S=>{let I=i.playbackRate;i.playbackRate!==S&&(t(`Playback rate switch: ${I}=>${S}`),i.playbackRate=S)},b=S=>{this.lowLatency=S,t(`lowLatency changed to ${S}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let S=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let w=K()-1e4,$=0;for(let V=0;V<this.bufferStates.length;V++){let _=this.bufferStates[V];S=Math.min(S,_.buf),_.ts<w&&$++}this.bufferStates.splice(0,$),t(`update playback rate; minBuffer=${S} drop=${$} jitter=${this.sourceJitter}`);let F=S-aA;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?m(1.15):F>1?m(1.1):F>.3?m(1.05):m(1)}},y=S=>{let I,w=()=>I&&I.start?I.start.length:0,$=x=>I.start[x]/1e3,F=x=>I.dur[x]/1e3,V=x=>I.fragIndex+x,_=(x,k)=>({chunkIdx:V(x),startTS:$(x),dur:F(x),discontinuity:k}),v=()=>{let x=0;if(I&&I.dur){let k=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=k;this.sourceJitter>1&&(J+=this.sourceJitter-1);let Se=I.dur.length-1;for(;Se>=0&&(J-=I.dur[Se],!(J<=0));--Se);x=Math.min(Se,I.dur.length-1-W),x=Math.max(x,0)}return _(x,!0)},R=x=>{let k=w();if(!(k<=0)){if(cs(x)){for(let W=0;W<k;W++)if($(W)>x)return _(W)}return v()}},q=x=>{let k=w(),W=x?x.chunkIdx+1:0,J=W-I.fragIndex;if(!(k<=0)){if(!x||J<0||J-k>rA)return t(`Resync: offset=${J} bChunks=${k} chunk=`+JSON.stringify(x)),v();if(!(J>=k))return _(W-I.fragIndex,!1)}},Me=(x,k,W)=>{l&&l.abort(),l=Ii(this.urlResolver.resolve(x,!0,this.lowLatency),k,W,()=>this._retryCallback()).withTimeout(ds).withRetryCount(tu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,k)=>{Me(S,W=>{if(!c())return;I=W;let J=!!I.lowLatency;J!==this.lowLatency&&b(J);let Se=0;for(let Ce=0;Ce<I.dur.length;++Ce)Se+=I.dur[Ce];Se>0&&(Sr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Se/I.dur.length)),a({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,x(R(k))},()=>this._handleNetworkError())},nextChunk:q}},A=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Sr(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:S=>{let{videoElement:I,logger:w}=this.params,$=y(e.jidxUrl),F,V,_,v,R=0,q,Me,ge,x=()=>{q&&(clearTimeout(q),q=void 0);let D=Math.max(sA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),H=R+D,ee=K(),Q=Math.min(1e4,H-ee);R=ee;let De=()=>{l||c()&&$.seek(()=>{c()&&(R=K(),k(),x())})};Q>0?q=window.setTimeout(()=>{this.paused?x():De()},Q):De()},k=()=>{let D;for(;D=$.nextChunk(v);)v=D,Xt(D);let H=$.nextChunk(_);if(H){if(_&&H.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?x():(A(),this._initPlayerWith(e));return}Ce(H)}else x()},W=(D,H)=>{if(!c()||!this.sourceBuffer)return;let ee,Q,De,pt=Ge=>{window.setTimeout(()=>{c()&&W(D,H)},Ge)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),pt(100);else{let Ge=K(),Be=I.currentTime;!this.paused&&I.buffered.length>1&&Me===Be&&Ge-ge>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),Me!==Be&&(Me=Be,ge=Ge);let wt=this._getBufferSizeSec();if(wt>30)w(`Buffered ${wt} seconds; delaying appendBuffer`),pt(2e3);else try{this.sourceBuffer.appendBuffer(D),this.videoPlayStarted?(this.bufferStates.push({ts:Ge,buf:wt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),H&&H()}catch(et){if(et.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),De=this.sourceBuffer.buffered.length,De!==0&&(ee=this.sourceBuffer.buffered.start(0),Q=Be,Q-ee>4&&this.sourceBuffer.remove(ee,Q-3)),pt(1e3);else throw et}}},J=()=>{V&&F&&(w([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(_)]),W(V,function(){V=null,k()}))},Se=D=>e.fragUrlTemplate.replace("%%id%%",D.chunkIdx),Ce=D=>{c()&&h(Se(D),(H,ee)=>{if(c()){if(ee/=1e3,V=H,_=D,n=D.startTS,ee){let Q=Math.min(10,D.dur/ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Q:Q}J()}},()=>this._handleNetworkError())},Xt=D=>{c()&&(Sr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Se(D),!1)))},kt=D=>{c()&&(e.cachedHeader=D,W(D,()=>{F=!0,J()}))};s=!0,$.seek(D=>{if(c()){if(R=K(),!D){x();return}v=D,!eA(S)||D.startTS>S?Ce(D):(_=D,k())}},S),e.cachedHeader?kt(e.cachedHeader):p(e.headerUrl,kt,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),cs(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,Sr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return cs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,h)=>{let m=K();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Zo(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=K();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Ii(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ds).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;de(e,()=>{this.soundProhibitedEvent$.next()}).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((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},iA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as nA,filter as Am,fromEvent as oA,interval as uA,isHigher as lA,isInvariantQuality as cA,isLower as dA,merge as pA,Subject as km,Subscription as hA}from"@vkontakte/videoplayer-shared";var iu=class{constructor(){this.onDroopedVideoFramesLimit$=new km;this.subscription=new hA;this.playing=!1;this.tracks=[];this.forceChecker$=new km;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&&!cA(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&&lA(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(oA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=uA(this.droppedFramesChecker.checkTime).pipe(Am(()=>this.playing),Am(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(nA(this.droppedFramesChecker.checkTime)),i=pA(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])=>dA(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}},ps=iu;import{map as fA,Observable as mA}from"@vkontakte/videoplayer-shared";import{fromEvent as bA}from"@vkontakte/videoplayer-shared";var yr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var gA=(r,e)=>new mA(t=>{if(!window.IntersectionObserver)return;let i={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||yr()))},{...i,...e});a.observe(r);let s=bA(document,"visibilitychange").pipe(fA(n=>!document.hidden||yr())).subscribe(n=>t.next(n));return()=>{a.unobserve(r),s.unsubscribe}}),$e=gA;var AA=["paused","playing","ready"],kA=["paused","playing","ready"],Tr=class{constructor(e){this.subscription=new EA;this.videoState=new L("stopped");this.representations$=new au([]);this.textTracksManager=new we;this.droppedFramesManager=new ps;this.maxSeekBackTime$=new au(1/0);this.zeroTime$=new au(void 0);this.liveOffset=new nt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:$m.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=yt(a.name)??PA(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};i.push({track:l,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),ru(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(kA.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&AA.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(X(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(X(this.params.source.url,u))}return;default:return wm(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:$m.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Mm(this.videoState.stateChangeStarted$.pipe(hs(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(hs(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(z(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=ce(this.video);this.subscription.add(this.representations$.pipe(hs(a=>a.map(({track:s})=>s)),Lm(a=>!!a.length),IA()).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(yA(),hs(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(SA({zeroTime:this.zeroTime$.pipe(Lm(ru)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Ke(this.video,this.params.desiredState.isLooped,t)).add(le(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ke(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add($e(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&xA(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 wm(a.to)}},t)).add(Mm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,TA(["init"])).pipe(vA(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),ue(this.video)}createLiveDashPlayer(){let e=new vr({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&&ru(t)?t:Tt(e.map(({track:l})=>l),{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,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(i),n||u||s!==o){let l=e.find(({track:d})=>d.id===s)?.representation;Rm(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Rm(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(X(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Cm=Tr;var Xe=(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)};import{assertNever as rw,assertNonNullable as aw,debounce as sw,ErrorCategory as Cu,filter as zb,filterChanged as Du,fromEvent as nw,isNonNullable as ow,map as Kb,merge as Ds,observableFrom as uw,observeElementSize as lw,once as Jb,Subscription as cw,ValueSubject as dw}from"@vkontakte/videoplayer-shared";var fs=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}},Ei=class extends fs{constructor(){super(),this.listeners||fs.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)}},Ir=class{constructor(){Object.defineProperty(this,"signal",{value:new Ei,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&&(Ir.prototype[Symbol.toStringTag]="AbortController",Ei.prototype[Symbol.toStringTag]="AbortSignal");function ms(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 su(r){typeof r=="function"&&(r={fetch:r});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!ms({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(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Er=ms({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Dm=Er?su({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ut=Er?Dm.fetch:window.fetch,f0=Er?Dm.Request:window.Request,Ue=Er?Ir:window.AbortController,m0=Er?Ei:window.AbortSignal;var Ss=Ye(hr(),1);var lt=()=>window.ManagedMediaSource||window.MediaSource,bs=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Bm=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Om=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ts,clientChecker as vs}from"@vkontakte/videoplayer-shared";var ys=document.createElement("video"),$A='video/mp4; codecs="avc1.42000a,mp4a.40.2"',LA='video/mp4; codecs="hev1.1.6.L93.B0"',Vm='video/webm; codecs="vp09.00.10.08"',_m='video/webm; codecs="av01.0.00M.08"',MA='audio/mp4; codecs="mp4a.40.2"',CA='audio/webm; codecs="opus"',qt={mms:bs(),mse:Bm(),hls:!!(ys.canPlayType?.("application/x-mpegurl")||ys.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},pe={mp4:!!ys.canPlayType?.("video/mp4"),webm:!!ys.canPlayType?.("video/webm"),cmaf:!0},he={h264:!!lt()?.isTypeSupported?.($A),h265:!!lt()?.isTypeSupported?.(LA),vp9:!!lt()?.isTypeSupported?.(Vm),av1:!!lt()?.isTypeSupported?.(_m),aac:!!lt()?.isTypeSupported?.(MA),opus:!!lt()?.isTypeSupported?.(CA)},xi=(he.h264||he.h265)&&he.aac,Ut,DA=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:_m}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:Vm}})]);Ut={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{DA()}catch(r){console.error(r)}var Pi=qt.hls&&pe.mp4,Nm=()=>Object.keys(he).filter(r=>he[r]),Fm=(r,e=!1,t=!1)=>{let i=qt.mse||qt.mms&&t;return r.filter(a=>{switch(a){case"DASH_SEP":return i&&pe.mp4&&xi;case"DASH_WEBM":return i&&pe.webm&&he.vp9&&he.opus;case"DASH_WEBM_AV1":return i&&pe.webm&&he.av1&&he.opus;case"DASH_STREAMS":return i&&(pe.mp4&&xi||pe.webm&&(he.vp9||he.av1)&&(he.opus||he.aac));case"DASH_LIVE":return qt.mse&&pe.mp4&&xi;case"DASH_LIVE_CMAF":return i&&pe.mp4&&xi&&pe.cmaf;case"DASH_ONDEMAND":return i&&pe.mp4&&xi;case"HLS":case"HLS_ONDEMAND":return Pi||e&&qt.mse&&pe.mp4&&xi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Pi;case"MPEG":return pe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return qt.webrtc&&qt.ws&&he.h264&&(pe.mp4||pe.webm);default:return Ts(a)}})},gs=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 Ut?Ut[t].smooth?[t,e]:Ut[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ut?Ut[t].powerEfficient?[t,e]:Ut[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ts(r)}return[e,t]},qm=({webmCodec:r,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...gs(r),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(vs.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",...gs(r),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...gs(r),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...gs(r),...a,"HLS","HLS_ONDEMAND"];default:Ts(e)}return Pi?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Um=({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,u=vs.isMac&&vs.isSafari;if(vs.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:Ts(r)}else Pi&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},nu=r=>r?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Hm=r=>{if(r.size===0)return;if(r.size===1){let t=r.values().next();return(0,Ss.default)(t.value.split("."),0)}for(let t of r){let i=(0,Ss.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=r.values().next();return(0,Ss.default)(e.value.split("."),0)};import{ErrorCategory as xr}from"@vkontakte/videoplayer-shared";var jm=r=>{if(!r)return{id:"EmptyResponse",category:xr.PARSER,message:"Empty response"};if(r.length<=2&&r.match(/^\d+$/))return{id:`UVError#${r}`,category:xr.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:xr.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:xr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:xr.PARSER,message:"Response is valid XML, but parser failed"}};var Ai=(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};import{abortable as Ru,assertNonNullable as Kt,clientChecker as Wk,combine as Rs,ErrorCategory as dt,filter as $u,filterChanged as Hb,flattenObject as ta,fromEvent as Ci,getTraceSubscriptionMethod as Qk,interval as Lu,isNonNullable as jb,map as Mu,merge as Di,now as Yk,Subject as Gb,Subscription as Wb,tap as zk,throttle as Kk,ValueSubject as Z}from"@vkontakte/videoplayer-shared";var Li=Ye(hr(),1);var BA=(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)},OA=r=>window.clearTimeout(r),Gm=r=>typeof r=="function"&&r?.toString().endsWith("{ [native code] }"),Wm=!Gm(window.requestIdleCallback)||!Gm(window.cancelIdleCallback),ou=Wm?BA:window.requestIdleCallback,R0=Wm?OA:window.cancelIdleCallback;var Ob=Ye(ss(),1);import{assertNever as VA,ErrorCategory as Qm,clientChecker as uu,Subject as Ym}from"@vkontakte/videoplayer-shared";var _A=16,zm=!1;try{zm=uu.isSafari&&!!uu.macVersion&&uu.macVersion<=_A}catch(r){console.error(r)}var lu=class{constructor(e){this.bufferFull$=new Ym;this.error$=new Ym;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:Qm.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;zm&&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:Qm.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:VA(t)}}},Km=lu;var cu=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};import{abortable as Wt,assertNonNullable as fe,ErrorCategory as Qt,fromEvent as xu,getExponentialDelay as Pu,isNonNullable as Qr,isNullable as me,now as xs,once as Ok,Subject as Vk,Subscription as _k,ValueSubject as Yr}from"@vkontakte/videoplayer-shared";var O=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 ki=class extends O{};var Pr=class extends O{};var Ar=class extends O{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 kr=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wr=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Rr=class extends O{constructor(e,t){super(e,t),this.data=this.content}};var G=class extends O{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ht=class extends G{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 u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var $r=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Lr=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mr=class extends G{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 Cr=class extends G{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Dr=class extends G{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Br=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Or=class extends G{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 Vr=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _r=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Nr=class extends G{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Fr=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qr=class extends G{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 Ur=class extends G{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 Hr=class extends G{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 FA={ftyp:Ar,moov:kr,moof:wr,mdat:Rr,sidx:Ht,trak:$r,mdia:Br,mfhd:Nr,tkhd:Or,traf:Fr,tfhd:qr,tfdt:Ur,trun:Hr,minf:Vr,sv3d:Lr,st3d:Mr,prhd:Cr,proj:_r,equi:Dr,uuid:Pr,unknown:ki},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=FA[e];return i?new i(t,new r):new ki(t,new r)}};var wi=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 UA=new TextDecoder("ascii"),HA=r=>UA.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",jA=r=>{let e=new Ht(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})},GA=(r,e)=>{let i=new jt().parse(r),a=new wi(i),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(r.buffer,l,c)},WA=(r,e)=>{let i=new jt().parse(r),s=new wi(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},QA=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 wi(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 u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Jm={validateData:HA,parseInit:QA,getIndexRange:()=>{},parseSegments:jA,parseFeedableSegmentChunk:GA,getSegmentEndTime:WA};import{assertNonNullable as pu,isNonNullable as tb,isNullable as zA}from"@vkontakte/videoplayer-shared";import{assertNever as YA}from"@vkontakte/videoplayer-shared";var Xm={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"}},Zm=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=jr(r,t),a=i in Xm,s=a?Xm[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 u=new DataView(r.buffer,r.byteOffset+t+1,o-1),l=n&255>>o,d=jr(u),c=l*2**((o-1)*8)+d,p=t+o,h;return p+c>r.byteLength?h=new DataView(r.buffer,r.byteOffset+p):h=new DataView(r.buffer,r.byteOffset+p,c),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},jr=(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},He=(r,e)=>{switch(e){case"int":return r.getInt8(0);case"uint":return jr(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:YA(e)}},Gt=(r,e)=>{let t=0;for(;t<r.byteLength;){let i=new DataView(r.buffer,r.byteOffset+t),a=Zm(i);if(!e(a))return;a.type==="master"&&Gt(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},eb=r=>{if(r.getUint32(0)!==440786851)return!1;let e,t,i,a=Zm(r);return Gt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=He(o,n):s===17026?t=He(o,n):s===17029&&(i=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var ib=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],KA=[231,22612,22743,167,171,163,160,175],JA=r=>{let e,t,i,a,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return Gt(r,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=He(m,h);l=jr(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=He(m,h):p===17545?a=He(m,h):p===21420&&l===475249515?u=He(m,h):p===374648427?Gt(m,({tag:g,type:y,value:A})=>g===30321?(d=He(A,y)===1,!1):!0):s&&n&&ib.includes(p)&&(o=!0),!o}),pu(e,"Failed to parse webm Segment start"),pu(t,"Failed to parse webm Segment end"),pu(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:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},XA=r=>{if(zA(r.cuesSeekPosition))return;let e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ZA=(r,e)=>{let t=!1,i=!1,a=o=>tb(o.time)&&tb(o.position),s=[],n;return Gt(r,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=He(l,u));break;case 183:break;case 241:n&&(n.position=He(l,u));break;default:t&&ib.includes(o)&&(i=!0)}return!(t&&i)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},ek=r=>{let e=0,t=!1;try{Gt(r,i=>i.tag===524531317?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):KA.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},rb={validateData:eb,parseInit:JA,getIndexRange:XA,parseSegments:ZA,parseFeedableSegmentChunk:ek};var Ri=r=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(r);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return rb;case"mp4":return Jm}}throw new ReferenceError(`Unsupported mime type ${r}`)};var vu=Ye(Pb(),1);var Su=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};import{isNonNullable as wb,isNullable as Rb}from"@vkontakte/videoplayer-shared";var Ab=r=>{if(r.includes("/")){let e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};var kb=r=>{try{let e=Dk(),t=r.match(e),{groups:i}=t??{};if(i){let a={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function Dk(){let r="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
59
+ (?<language>${`(?:[a-z]{2,3}(?:-${r})?|[a-z]{4}|[a-z]{5,8})`})
60
+ (-(?<script>[a-z]{4}))?
61
+ (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
62
+ (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
63
+ (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
64
+ (?:-(?<privateuse>(?:${e})))?
65
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var $b=r=>{if(!r.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(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},ct=(r,e)=>{let t=r;t=(0,vu.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,vu.default)(t,n,(o,u)=>Rb(s)?o:Rb(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Lb=(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()??"",u=n.children,l=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),c=d?new Date(d).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=$b(h);else if(m){let S=$b(m);wb(S)&&(p=S)}else g&&(p=parseInt(g,10));let y=0,A=s.getAttribute("profiles")?.split(",")??[];for(let S of u){let I=S.getAttribute("id")??"id"+(y++).toString(10),w=S.getAttribute("mimeType")??"",$=S.getAttribute("codecs")??"",F=S.getAttribute("contentType")??w?.split("/")[0],V=S.getAttribute("profiles")?.split(",")??[],_=kb(S.getAttribute("lang")??"")??{},v=S.querySelector("Label")?.textContent?.trim()??S.getAttribute("label")??void 0,R=S.querySelectorAll("Representation"),q=S.querySelector("SegmentTemplate"),Me=S.querySelector("Role")?.getAttribute("value")??void 0,ge=F,x={id:I,language:_.language,isDefault:Me==="main",label:v,codecs:$,hdr:ge==="video"&&Su($),mime:w,representations:[]};for(let k of R){let W=k.getAttribute("lang")??void 0,J=k.getAttribute("label")??void 0,Se=k.querySelector("BaseURL")?.textContent?.trim()??"",Ce=new URL(Se||o,e).toString(),Xt=k.getAttribute("mimeType")??w,kt=k.getAttribute("codecs")??$??"",D;if(F==="text"){let H=k.getAttribute("id")||"",ee=_.privateuse?.includes("x-auto")||H.includes("_auto"),Q=k.querySelector("SegmentTemplate");if(Q){let De={representationId:k.getAttribute("id")??void 0,bandwidth:k.getAttribute("bandwidth")??void 0},pt=parseInt(k.getAttribute("bandwidth")??"",10)/1e3,Ge=parseInt(Q.getAttribute("startNumber")??"",10)??1,Be=parseInt(Q.getAttribute("timescale")??"",10),wt=Q.querySelectorAll("SegmentTimeline S")??[],et=Q.getAttribute("media");if(!et)continue;let ba=[],ga=0,Sa="",Zt=0,Vi=Ge,te=0;for(let Oe of wt){let Rt=parseInt(Oe.getAttribute("d")??"",10),Ee=parseInt(Oe.getAttribute("r")??"",10)||0,ht=parseInt(Oe.getAttribute("t")??"",10);te=Number.isFinite(ht)?ht:te;let $t=Rt/Be*1e3,ei=te/Be*1e3;for(let We=0;We<Ee+1;We++){let ft=ct(et,{...De,segmentNumber:Vi.toString(10),segmentTime:(te+We*Rt).toString(10)}),ti=(ei??0)+We*$t,Ni=ti+$t;Vi++,ba.push({time:{from:ti,to:Ni},url:ft})}te+=(Ee+1)*Rt,ga+=(Ee+1)*$t}Zt=te/Be*1e3,Sa=ct(et,{...De,segmentNumber:Vi.toString(10),segmentTime:te.toString(10)});let _i={time:{from:Zt,to:1/0},url:Sa},tt={type:"template",baseUrl:Ce,segmentTemplateUrl:et,initUrl:"",totalSegmentsDurationMs:ga,segments:ba,nextSegmentBeyondManifest:_i,timescale:Be};D={id:H,kind:"text",segmentReference:tt,profiles:[],duration:p,bitrate:pt,mime:"",codecs:"",width:0,height:0,isAuto:ee}}else D={id:H,isAuto:ee,kind:"text",url:Ce}}else{let H=k.getAttribute("contentType")??Xt?.split("/")[0]??F,ee=S.getAttribute("profiles")?.split(",")??[],Q=parseInt(k.getAttribute("width")??"",10),De=parseInt(k.getAttribute("height")??"",10),pt=parseInt(k.getAttribute("bandwidth")??"",10)/1e3,Ge=k.getAttribute("frameRate")??"",Be=k.getAttribute("quality")??void 0,wt=Ge?Ab(Ge):void 0,et=k.getAttribute("id")??"id"+(y++).toString(10),ba=H==="video"?`${De}p`:H==="audio"?`${pt}Kbps`:kt,ga=`${et}@${ba}`,Sa=[...A,...V,...ee],Zt,Vi=k.querySelector("SegmentBase"),te=k.querySelector("SegmentTemplate")??q;if(Vi){let tt=k.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Oe,Rt]=tt.split("-").map(ft=>parseInt(ft,10)),Ee={from:Oe,to:Rt},ht=k.querySelector("SegmentBase")?.getAttribute("indexRange"),[$t,ei]=ht?ht.split("-").map(ft=>parseInt(ft,10)):[],We=ht?{from:$t,to:ei}:void 0;Zt={type:"byteRange",url:Ce,initRange:Ee,indexRange:We}}else if(te){let tt={representationId:k.getAttribute("id")??void 0,bandwidth:k.getAttribute("bandwidth")??void 0},Oe=parseInt(te.getAttribute("timescale")??"",10),Rt=te.getAttribute("initialization")??"",Ee=te.getAttribute("media"),ht=parseInt(te.getAttribute("startNumber")??"",10)??1,$t=ct(Rt,tt);if(!Ee)throw new ReferenceError("No media attribute in SegmentTemplate");let ei=te.querySelectorAll("SegmentTimeline S")??[],We=[],ft=0,ti="",Ni=0;if(ei.length){let va=ht,Ve=0;for(let ii of ei){let Qe=parseInt(ii.getAttribute("d")??"",10),Lt=parseInt(ii.getAttribute("r")??"",10)||0,ya=parseInt(ii.getAttribute("t")??"",10);Ve=Number.isFinite(ya)?ya:Ve;let zs=Qe/Oe*1e3,Hg=Ve/Oe*1e3;for(let Ta=0;Ta<Lt+1;Ta++){let jg=ct(Ee,{...tt,segmentNumber:va.toString(10),segmentTime:(Ve+Ta*Qe).toString(10)}),Ku=(Hg??0)+Ta*zs,Gg=Ku+zs;va++,We.push({time:{from:Ku,to:Gg},url:jg})}Ve+=(Lt+1)*Qe,ft+=(Lt+1)*zs}Ni=Ve/Oe*1e3,ti=ct(Ee,{...tt,segmentNumber:va.toString(10),segmentTime:Ve.toString(10)})}else if(wb(p)){let Ve=parseInt(te.getAttribute("duration")??"",10)/Oe*1e3,ii=Math.ceil(p/Ve),Qe=0;for(let Lt=1;Lt<ii;Lt++){let ya=ct(Ee,{...tt,segmentNumber:Lt.toString(10),segmentTime:Qe.toString(10)});We.push({time:{from:Qe,to:Qe+Ve},url:ya}),Qe+=Ve}Ni=Qe,ti=ct(Ee,{...tt,segmentNumber:ii.toString(10),segmentTime:Qe.toString(10)})}let Ug={time:{from:Ni,to:1/0},url:ti};Zt={type:"template",baseUrl:Ce,segmentTemplateUrl:Ee,initUrl:$t,totalSegmentsDurationMs:ft,segments:We,nextSegmentBeyondManifest:Ug,timescale:Oe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!H||!Xt)continue;let _i={video:"video",audio:"audio",text:"text"}[H];if(!_i)continue;ge||=_i,D={id:ga,kind:_i,segmentReference:Zt,profiles:Sa,duration:p,bitrate:pt,mime:Xt,codecs:kt,width:Q,height:De,fps:wt,quality:Be}}x.language||=W,x.label||=J,x.mime||=Xt,x.codecs||=kt,x.hdr||=ge==="video"&&Su(kt),x.representations.push(D)}ge&&a[ge].push(x)}return{dynamic:l,liveAvailabilityStartTime:c,duration:p,streams:a}};var Gr=Ye(hr(),1);import{videoSizeToQuality as Bk}from"@vkontakte/videoplayer-shared";var Mb=({id:r,width:e,height:t,bitrate:i,fps:a,quality:s})=>{let n=(s?yt(s):void 0)??Bk({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:a}},Cb=({id:r,bitrate:e})=>({id:r,bitrate:e}),Is=(r,e,t)=>{let i=e.indexOf(r);return(0,Gr.default)(t,Math.round(t.length*i/e.length))??(0,Gr.default)(t,-1)},Db=({language:r,label:e},{id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),Bb=({language:r,label:e,id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),Iu=({id:r,language:e,label:t,codecs:i,isDefault:a})=>({id:r,language:e,label:t,codec:(0,Gr.default)(i.split("."),0),isDefault:a}),Eu=({id:r,language:e,label:t,hdr:i,codecs:a})=>({id:r,language:e,hdr:i,label:t,codec:(0,Gr.default)(a.split("."),0)}),Es=r=>"url"in r,Le=r=>r.type==="template",Wr=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);var zr=class{constructor(e,t,i,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new Yr(0);this.onLastSegment$=new Yr(!1);this.fullyBuffered$=new Yr(!1);this.playingRepresentation$=new Yr(void 0);this.playingRepresentationInit$=new Yr(void 0);this.error$=new Vk;this.gaps=[];this.subscription=new _k;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ue;this.switchAbortController=new Ue;this.destroyAbortController=new Ue;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=Wt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);fe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Km(this.sourceBuffer),this.subscription.add(xu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Qt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Qt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(xu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Qt.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 u=Math.min(this.bufferLimit,cu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=Xe(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,l<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);fe(i,"No init buffer for starting representation"),fe(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.switchToOld=Wt(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);fe(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(me(s)||me(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),fe(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();Qr(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=Wt(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!Le(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(i);fe(a);let s=this.segments.get(i);fe(s,"No segments for starting representation");let n=this.initData.get(i);if(fe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,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=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.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}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ue,Wt(this.switchAbortController.signal,async function*(i,a=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);fe(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(me(o)||me(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),fe(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Qr(u)&&!this.isLive&&(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0,this.maintain(u)}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ue,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(me(e)||me(this.downloadingRepresentationId)||me(this.playingRepresentationId)||me(this.sourceBuffer)||Qr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(fe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let a=i.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=Xe(this.sourceBuffer.buffered,e),c=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=c)}if(isFinite(this.bufferLimit)&&cu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=Xe(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))l="high";else{let d=(0,Li.default)(o,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&Xe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Li.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}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;Qr(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||!Le(i.segmentReference))return;let a=i.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),s=this.segments.get(i.id)??[],n=(0,Li.default)(s,-1)?.time.to??0,o=a?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,u)}else{let u=a.slice(o+1);this.segments.set(i.id,[...s,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;fe(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(!Le(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),u=ct(i.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}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.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(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:c,time:{from:p,to:h}},m)=>{let b=p<=i&&h>=i,g=p>i||b||m===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=i+y||h<=i+y;return(c==="none"||c==="partially_ejected"&&g&&A&&this.sourceBuffer&&!(Ai(this.sourceBuffer.buffered,p)&&Ai(this.sourceBuffer.buffered,h)))&&g&&A});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=a;c<s.length&&(n<=l||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){Le(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:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Wt(o,async function*(){let d=Pu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=xs(),!d)return;let c=new DataView(d);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,h=Ri(t.mime);a.segment.time.to=h.getSegmentEndTime(c,p)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Wr(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Wt(n,async function*(){let u=Pu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),xu(window,"online").pipe(Ok()).subscribe(()=>{l(),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=xs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Wr(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Le(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,a={from:(0,Li.default)(e,0).byte.from,to:(0,Li.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xs(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Qt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Le(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=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xs();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Qt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:a,signal:s,onProgress:u,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:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Ri(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.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 u=o.segmentReference.type,l=e.byteLength;for(let d of this.activeSegments){let{segment:c}=d,p=u==="byteRange",h=p?c.byte.to-c.byte.from+1:l;if(d.representationId!==t||!(!p||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(s.aborted){n();continue}let b=p?c.byte.from-i:0,g=p?c.byte.to-i:e.byteLength,y=b<a,A=g<=a;if(c.status==="downloading"&&y&&A){c.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+b,h),S=this.getCurrentPosition();Qr(S)&&(this.bufferAccumulation.accumulatedBufferSizeMs=c.time.to-S,this.bufferAccumulation.accumulated.push({segmentView:T,segmentProgress:d}),this.activeSegments.delete(d));let I=({segmentView:w,segmentProgress:$})=>this.sourceBufferTaskQueue.append(w,s).then(F=>F&&!s.aborted?this.onSegmentFullyAppended($,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(I),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||me(S))&&(I({segmentView:T,segmentProgress:d}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&!A&&(d.loadedBytes=Math.min(h,a-b),d.loadedBytes>d.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+b+d.feedingBytes,d.loadedBytes-d.feedingBytes),S=d.loadedBytes===h?T:Ri(o.mime).parseFeedableSegmentChunk(T);S?.byteLength&&(c.status="partially_fed",d.feedingBytes+=S.byteLength,this.sourceBufferTaskQueue.append(S,s).then(I=>{if(s.aborted)n();else if(I)d.fedBytes+=S.byteLength,d.fedBytes===h&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<h)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 u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<a,m=c<=a;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-d),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:Ri(o.mime).parseFeedableSegmentChunk(b);g?.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Es(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");fe(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=ou(()=>(0,Ob.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?Wt(this.destroyAbortController.signal,async function*(){let o=Pu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ri(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&Le(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Qt.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||me(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=Es(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(a.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||me(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,u=l=>{s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let d=Es(l)?l.size??0:l.byte.to-l.byte.from;a+=d};for(let l of this.segments.values())for(let d of l){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status==="fed"&&u(d)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let d of l){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status==="fed"&&u(d)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let d=this.sourceBuffer.buffered.start(l)*1e3,c=this.sourceBuffer.buffered.end(l)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(c)){s=d,n=c;break}}if(o=isFinite(s)&&isFinite(n),!o&&i){a=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let c of d)c.time.from>e+l&&c.status==="fed"&&u(c)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||me(e)?0:Xe(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){fe(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=ou(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Qt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(me(this.sourceBuffer)||me(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),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?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 Kr=r=>{let e=new URL(r);return e.searchParams.set("quic","1"),e.toString()};var Vb=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}};import{abortable as Jr,assertNever as _b,fromEvent as Nb,merge as Nk,now as Xr,Subscription as Fk,ValueSubject as Au,flattenObject as Mi}from"@vkontakte/videoplayer-shared";var Ps=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:a=!1}){this.lastConnectionType$=new Au(void 0);this.lastConnectionReused$=new Au(void 0);this.lastRequestFirstBytes$=new Au(void 0);this.abortAllController=new Ue;this.subscription=new Fk;this.fetchManifest=Jr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Kr(i));let a=yield ut(i,{signal:this.abortAllController.signal}).catch(Zr);return a?(t.log("success",Mi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Mi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Jr(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:u=!1}={}){let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(l,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),l=v.toString();break}default:_b(t)}this.requestQuic&&(l=Kr(l));let p=this.abortAllController.signal,h;if(n){let v=new Ue;if(h=Nk(Nb(this.abortAllController.signal,"abort"),Nb(n,"abort")).subscribe(()=>{try{v.abort()}catch(R){Zr(R)}}),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(R){Zr(R)}p=v.signal}let m=Xr();c.log("startRequest",Mi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield ut(l,{priority:s,headers:d,signal:p}).catch(Zr),g=Xr();if(!b)return c.error("error",{message:"No response in request"}),c.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-m),!b.ok||!b.body){h?.unsubscribe();let v=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:v}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let v=Xr(),R={requestStartedAt:m,requestEndedAt:v,duration:v-m};return c.log("endRequest",Mi(R)),c.end(),b.arrayBuffer()}let[y,A]=b.body.tee(),T=y.getReader();o&&this.throughputEstimator?.trackStream(A,u);let S=0,I=new Uint8Array(0),w=!1,$=v=>{h?.unsubscribe(),w=!0,Zr(v)},F=Jr(p,async function*({done:v,value:R}){if(S===0&&this.lastRequestFirstBytes$.next(Xr()-m),p.aborted){h?.unsubscribe();return}if(!v&&R){let q=new Uint8Array(I.length+R.length);q.set(I),q.set(R,I.length),I=q,S+=R.byteLength,a?.(new DataView(I.buffer),S),yield T?.read().then(F,$)}}.bind(this));yield T?.read().then(F,$),h?.unsubscribe();let V=Xr(),_={failed:w,requestStartedAt:m,requestEndedAt:V,duration:V-m};return w?(c.error("endRequest",Mi(_)),c.end(),null):(c.log("endRequest",Mi(_)),c.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=Jr(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,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,m.from-n,m.to-m.from+1);else{let y=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=Jr(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}=Vb(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:_b(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Zr=r=>{if(!Wr(r))throw r};var Yt=(r,e,t)=>t*e+(1-t)*r,ku=(r,e)=>r.reduce((t,i)=>t+i,0)/e,Fb=(r,e,t,i)=>{let a=0,s=t,n=ku(r,e),o=e<i?e:i;for(let u=0;u<o;u++)r[s]>n?a++:a--,s=(r.length+s-1)%r.length;return Math.abs(a)===o};import{isNullable as qk,ValueSubject as qb}from"@vkontakte/videoplayer-shared";var It=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 qb(e.initial),this.debounced$=new qb(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new re(`raw_${t}`),this.smoothedSeries$=new re(`smoothed_${t}`),this.reportedSeries$=new re(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let 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)&&(qk(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 As=class extends It{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Yt(this.slow,e,this.params.emaAlphaSlow),this.fast=Yt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ks=class extends It{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ku(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Yt(this.emaSmoothed,e,this.params.emaAlpha);let i=Fb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ws=class extends It{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?Yt(this.smoothed,t,this.params.emaAlpha):t}};var zt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new As({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ks({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 ws({initial:e,label:"liveEdgeDelay",...t})}};var wu=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)};import{isNullable as Uk,ValueSubject as Hk}from"@vkontakte/videoplayer-shared";var ea=class r{constructor(e,t){this.currentRepresentation$=new Hk(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(!Uk(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 u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,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&&Le(t.segmentReference))}};var Jk=["timeupdate","progress","play","seeked","stalled","waiting"],Xk=["timeupdate","progress","loadeddata","playing","seeked"];var $s=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Wb;this.representationSubscription=new Wb;this.state$=new L("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new Gb;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.liveDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(void 0);this.bufferLength$=new Z(0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.isActiveLowLatency$=new Z(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Gb;this.gapWatchdogActive=!1;this.destroyController=new Ue;this.initManifest=Ru(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=X(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:dt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ru(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:dt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Lb(e??"",this.manifestUrlString)}catch(n){let o=jm(e)??{id:"ManifestParsing",category:dt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&lt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||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 u=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=Hm(l);if(d&&(a[n]=u.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=a.video.some(m=>m.hdr),h=a.video.some(m=>!m.hdr);Wk.isHDR&&c&&p?a.video=a.video.filter(m=>m.hdr):h&&(a.video=a.video.filter(m=>!m.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",ta(s)),s}.bind(this));this.initRepresentations=Ru(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ta({initialVideo:e,initialAudio:t,sourceHls:i})),Kt(this.manifest),Kt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=c=>{this.representationSubscription.add(Ci(c,"error").pipe($u(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?Om():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&bs())if(i){let c=document.createElement("source");a(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new zr("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],jb(t)){let c=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new zr("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(ea.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new ea(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(Lu(1e3).subscribe(c=>{if(this.element?.paused){let p=Fo(this.manifestUrlString,2);this.manifestUrlString=X(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(Di(...Xk.map(c=>Ci(this.element,c))).pipe(Mu(c=>this.element?Xe(this.element.buffered,this.element.currentTime*1e3):0),Hb(),zk(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&(this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Hb()).subscribe(p=>wu(this.element,1))),this.representationSubscription.add(Rs({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe($u(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(Rs({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:h})=>{if(!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=p-m,A=1;Math.abs(y)>b&&(A=1+Math.sign(y)*g),wu(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add(Rs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Kk(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(Kt(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,b=Fo(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,S=isFinite(p)?p:h,I=this.isActiveLowLatency$.getValue(),w=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(I&&w);let $="none";if(I?$="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&w?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),$="active_low_latency"):b!==0&&S<y?$="live_forward_buffering":S<y+T&&($="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),$==="live_forward_buffering"||$==="live_with_target_offset"){let F=c-(y+A),V=this.normolizeLiveOffset(Math.trunc(b+F/m)),_=Math.abs(V-b),v;!p||_<=this.tuning.dashCmafLive.offsetCalculationError?v=b:V>0&&_>this.tuning.dashCmafLive.offsetCalculationError?v=V:v=0,this.manifestUrlString=X(this.manifestUrlString,v,2)}$!=="none"&&$!=="active_low_latency"&&(c=0,this.updateLive())}))}let u=Di(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Mu(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=Di(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Mu(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue())));this.representationSubscription.add(Di(this.forceEnded$,Rs({allBuffersFull:u,someBufferEnded:l}).pipe($u(({allBuffersFull:c,someBufferEnded:p})=>c&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Di(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(c=>this.source?.addEventListener("sourceopen",c)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(c=>c.representations).flatMap(c=>{let p=[];return c.duration&&p.push(c.duration),Le(c.segmentReference)&&c.segmentReference.totalSegmentsDurationMs&&p.push(c.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&jb(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=Lu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:dt.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 Ps({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=zt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){Kt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=X(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(){Kt(this.element),this.state$.setState("running"),this.subscription.add(Di(...Jk.map(e=>Ci(this.element,e)),Ci(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ci(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ci(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ai(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=Yk(),a=100,s=this.videoBufferManager?.lastDataObtainedTimestamp??0,n=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,u=this.audioBufferManager?.getForwardBufferDuration()??0,l=o<a&&i-s>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&u<a&&i-n>this.tuning.dash.crashOnStallTWithoutDataTimeout;if(this.tuning.useNewProviderReinitLogic&&(l||d)&&this.timeInWaiting>this.tuning.dash.crashOnStallTWithoutDataTimeout||this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.timeInWaiting} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),t={...t,liveLastSeekOffset:this.liveLastSeekOffset};else{let c=this.element.currentTime*1e3;this.videoBufferManager?.maintain(c),this.audioBufferManager?.maintain(c),t={...t,position:c}}this.tracer.log("stallIntervalCallback",ta(t))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Lu(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:this.tuning.useNewProviderReinitLogic?dt.NETWORK:dt.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){Kt(this.element),Kt(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),Ai(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",ta({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=Qk(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",ta(t)))}}};var Ls=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ms=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 Qb=`attribute vec2 a_vertex;
59
66
  attribute vec2 a_texel;
60
67
 
61
68
  varying vec2 v_texel;
@@ -66,7 +73,7 @@ void main(void) {
66
73
  // save texel vector to pass to fragment shader
67
74
  v_texel = a_texel;
68
75
  }
69
- `;var Qb=`#ifdef GL_ES
76
+ `;var Yb=`#ifdef GL_ES
70
77
  precision highp float;
71
78
  precision highp int;
72
79
  #else
@@ -109,5 +116,5 @@ void main(void) {
109
116
  // sample using new coordinates
110
117
  gl_FragColor = texture2D(u_texture, tc);
111
118
  }
112
- `;var Cs=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 Ls(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ms(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(Wb,this.gl.VERTEX_SHADER),i=this.createShader(Qb,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,l=t-a,u=e+i,d=t+a,c=e-i,p=t+a;return[s,n,o,l,u,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Jt=class{constructor(e){this.subscription=new uw;this.videoState=new L("stopped");this.elementSize$=new lw(void 0);this.textTracksManager=new we;this.droppedFramesManager=new ps;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"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&E(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"&&E(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"&&E(this.params.desiredState.playbackState,"paused");return;default:return tw(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Cs(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=oe(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(z(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 $s({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=ce(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Cu.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,l)=>this.subscription.add(o.subscribe(l,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Yb(u=>!!u.length),Kb()).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(Yb(sw),Kb()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(zb(u=>u.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Ke(this.video,t.isLooped,a)),this.subscription.add(le(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(ke(this.video,t.playbackRate,i.playbackRateState$,a)),s(ow(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"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(iw(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push(Iu(h));let m=[];for(let b of h.representations){let g=Mb(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of d.video){c.push(Eu(p));let h=[];for(let m of p.representations){let b=Lb(m);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}if(this.params.output.availableVideoStreams$.next(c),this.textTracksManager)for(let p of d.text)for(let h of p.representations){let m=Cb(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),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:Cu.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(Ds(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$,aw(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[p,h]=c,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),u==="manifest_ready")this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).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(Du()).subscribe(u=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:p}]=d,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Eu(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Du()).subscribe(u=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:p}]=d,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Iu(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(zb(({to:u})=>u==="ready"),Du());this.subscription.add(Ds(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(Ds(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Ds(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nw(["init"])).pipe(rw(0));this.subscription.add(l.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:w})=>w===a),o=t.currentVideoTrack$.getValue(),l=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let u=[...this.videoStreamsMap.keys()].find(({id:w})=>w===l.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let c=Xe(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:w})=>w===m?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!i)if(this.params.tuning.useSeparateAudioVideoABR){let w=us(n,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,w?.bitrate??-1/0)}else{let w=Is(n,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,w?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let w=us(o,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,w?.bitrate??-1/0)}else{let w=Is(o,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,w?.bitrate??-1/0)}}let y=Tt(d,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),A=i?y??n:n??y,T;this.params.tuning.useSeparateAudioVideoABR?T=b&&Im(A,d,this.audioStreamsMap.get(b)??[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):T=b&&Is(A,d,this.audioStreamsMap.get(b)??[]);let S=this.videoTracksMap.get(A)?.representation,I=T&&this.audioTracksMap.get(T)?.representation;if(S&&I)return[S,I];if(S&&!I&&this.audioTracksMap.size===0)return[S,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cu.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),ue(this.video),this.tracer.end()}};var ra=class extends Jt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Jb,interval as cw,map as dw}from"@vkontakte/videoplayer-shared";var aa=class extends Jt{constructor(e){super(e),this.liveOffset=new nt,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(Jb({interval:cw(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(Jb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(dw(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=Db(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 Zb=Ye(ss(),1);import{assertNever as sa,assertNonNullable as Xb,debounce as pw,ErrorCategory as Bs,filter as hw,isNonNullable as fw,isNullable as mw,map as Os,merge as bw,Observable as gw,observableFrom as Sw,Subscription as vw,videoSizeToQuality as yw}from"@vkontakte/videoplayer-shared";var je={};var Bi=(r,e)=>new gw(t=>{let i=(a,s)=>t.next(s);return r.on(e,i),()=>r.off(e,i)}),na=class{constructor(e){this.subscription=new vw;this.videoState=new L("initializing");this.textTracksManager=new we;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:sa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:sa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:sa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:sa(e)}break;default:sa(t)}};this.video=oe(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(z(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),ue(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Bs.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Zb.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(){Xb(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(){Xb(je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:Bs.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=ce(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(Ke(this.video,e.isLooped,i)),this.subscription.add(le(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ke(this.video,e.playbackRate,a.playbackRateState$,i)),s($e(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Os(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Bi(this.hls,je.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:Bs.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"),E(e.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(Bi(this.hls,je.Events.MANIFEST_PARSED).pipe(Os(({levels:u})=>u.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:h,height:m}=c,b=yt(c.attrs.QUALITY??"")??yw({width:h,height:m});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,y={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:y,level:c}),d.push(y),d},[]))),t.availableVideoTracks$),s(Bi(this.hls,je.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let d=[];for(let c of u.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Bi(this.hls,je.Events.LEVEL_LOADING).pipe(Os(({url:u})=>z(u))),t.hostname$),s(Bi(this.hls,je.Events.FRAG_CHANGED),u=>{let{video:d,audio:c}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(gt(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=Bi(this.hls,je.Events.LEVEL_SWITCHED).pipe(Os(({level:u})=>n(this.hls.levels[u])));o.pipe(hw(fw)).subscribe(t.currentVideoTrack$,i),this.subscription.add(gt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(mw(u))return;let d=this.trackLevels.get(u.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=bw(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Sw(["init"])).pipe(pw(0));this.subscription.add(l.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 de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bs.DOM,thrown:t}))||(this.videoState.setState("paused"),E(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"),E(this.params.desiredState.playbackState,"stopped",!0)}};var eg="X-Playback-Duration",Bu=async r=>{let e=await ut(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(eg)?parseInt(e.headers.get(eg),10):void 0};import{assertNever as Aw,combine as kw,debounce as ww,ErrorCategory as _s,filter as Rw,filterChanged as $w,isNonNullable as ig,isNullable as Ns,map as rg,merge as Lw,observableFrom as Mw,Subscription as Cw,ValueSubject as _u,VideoQuality as Dw}from"@vkontakte/videoplayer-shared";var Vu=Ye(eo(),1);import{videoSizeToQuality as Tw,getExponentialDelay as Iw}from"@vkontakte/videoplayer-shared";var Ew=r=>{let e=null;if(r.QUALITY&&(e=yt(r.QUALITY)),!e&&r.RESOLUTION){let[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=Tw({width:t,height:i})}return e??null},xw=(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:(.+)/),l=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!l)){if(o){let u=(0,Vu.default)(o[1].split(",").map(g=>g.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,c=Ew(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 h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[g,y]=u.RESOLUTION.split("x").map(A=>parseInt(A,10));g&&y&&(m={width:g,height:y})}let b=new URL(t[++s],e).toString();c&&i.push({id:d,quality:c,url:b,bandwidth:p,size:m,fps:h})}if(l){let u=(0,Vu.default)(l[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),d=u.URI?.replace(/playlist$/,"subtitles.vtt"),c=u.LANGUAGE,p=u.NAME;d&&c&&a.push({type:"internal",id:c,label:p,language:c,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},Pw=r=>new Promise(e=>{setTimeout(()=>{e()},r)}),Ou=0,tg=async(r,e=r,t)=>{let a=await(await ut(r)).text();Ou+=1;try{let{qualityManifests:s,textTracks:n}=xw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Ou<=t.manifestRetryMaxCount)return await Pw(Iw(Ou-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),tg(r,e,t)}return{qualityManifests:[],textTracks:[]}},Vs=tg;var oa=class{constructor(e){this.subscription=new Cw;this.videoState=new L("stopped");this.textTracksManager=new we;this.manifests$=new _u([]);this.liveOffset=new nt;this.manifestStartTime$=new _u(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"),E(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"?E(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(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"&&E(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"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Aw(t)}};this.params=e,this.video=oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Dw.INVARIANT,url:this.params.source.url},Vs(X(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:_s.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_s.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(z(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new _u(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(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:_s.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ce(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,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(le(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ke(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"),E(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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($w(),rg(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&ig(u.to)){let c=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(z(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(kw({startTime:this.manifestStartTime$.pipe(Rw(ig)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),i)),this.subscription.add(this.manifests$.pipe(rg(o=>o.map(({id:l,quality:u,size:d,bandwidth:c,fps:p})=>({id:l,quality:u,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=Lw(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Mw(["init"])).pipe(ww(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ue(this.video)}prepare(){let e=this.selectManifest();if(Ns(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:l}=t?.to??i??{};for(let[u,d]of[[o,"mq"],[l,"lq"]]){let c=String(parseFloat(u||""));d&&u&&a.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=X(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Bu(n).then(o=>{if(!Ns(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Ns(l)||!isFinite(l))try{ut(n).then(u=>u.text()).then(u=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(d){let c=new URL(d,n).toString();Bu(c).then(p=>{Ns(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_s.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()}};import{assertNever as Bw,debounce as Ow,ErrorCategory as Nu,fromEvent as Fu,isNonNullable as Vw,isNullable as _w,map as ag,merge as sg,observableFrom as ng,Subscription as Nw,ValueSubject as Fw,VideoQuality as qw,clientChecker as Uw}from"@vkontakte/videoplayer-shared";var ua=class{constructor(e){this.subscription=new Nw;this.videoState=new L("stopped");this.textTracksManager=new we;this.manifests$=new Fw([]);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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":i==="ready"?E(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Bw(t)}};this.params=e,this.video=oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:qw.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(z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Vs(X(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:Nu.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(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Nu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ce(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(ag(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,i)),this.subscription.add(le(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ke(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&Vw(u.to)){let c=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===c);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(z(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(h),b.playbackRate=h)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(ag(o=>o.map(({id:l,quality:u,size:d,bandwidth:c,fps:p})=>({id:l,quality:u,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!Uw.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(sg(Fu(o,"addtrack"),Fu(o,"removetrack"),Fu(o,"change"),ng(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},i))}let n=sg(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ng(["init"])).pipe(Ow(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ue(this.video)}prepare(){let e=this.selectManifest();if(_w(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,l]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));l&&o&&a.searchParams.set(l,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Hw,assertNonNullable as og,debounce as jw,ErrorCategory as ug,isHigher as Gw,isHigherOrEqual as Ww,isInvariantQuality as lg,isLowerOrEqual as Qw,isNonNullable as Yw,merge as zw,observableFrom as Kw,Subscription as Jw,map as Xw}from"@vkontakte/videoplayer-shared";var la=class{constructor(e){this.subscription=new Jw;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new we;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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:l}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return Hw(e)}};this.params=e,this.video=oe(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:ug.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ce(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,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(Xw(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,i)),this.subscription.add(le(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ke(this.video,t.playbackRate,a.playbackRateState$,i)),s($e(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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&&Yw(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(l!==u){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(l),d.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=zw(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Kw(["init"])).pipe(jw(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),ue(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;og(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];og(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Kr(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(z(t))}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ug.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=>!lg(o.track.quality)&&Qw(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&Ww(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!lg(u.track.quality)&&Gw(u.track.quality,e)),l=o.length;l&&(t=o[l-1].track)}t&&(i=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=Tt(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})}};import{assertNever as dg,debounce as iR,merge as pg,observableFrom as rR,Subscription as aR,map as hg,ValueSubject as sR,ErrorCategory as Uu,VideoQuality as nR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as Zw}from"@vkontakte/videoplayer-shared";var cg=["stun:videostun.mycdn.me:80"],eR=1e3,tR=3,qu=()=>null,Fs=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=qu;this.externalStopCallback=qu;this.externalErrorCallback=qu;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:cg}]};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:Zw.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),eR)}normalizeOptions(e={}){let t={stunServerList:cg,maxRetryNumber:tR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ca=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new sR(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"),E(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"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return dg(e)}};this.subscription=new aR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=oe(e.container,e.tuning),this.liveStreamClient=new Fs(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),ue(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Uu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};pg(this.videoState.stateChangeStarted$.pipe(hg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(hg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ce(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(le(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 dg(n.to)}},i)).add(pg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,rR(["init"])).pipe(iR(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(z(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:nR.INVARIANT}),this.video.srcObject=e,E(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Uu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var da=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}};import{assertNever as ha,assertNonNullable as Et,ErrorCategory as Us,filter as hR,isNonNullable as vg,isNullable as fR,map as mR,merge as bR,once as gR,Subject as be,Subscription as yg,ValueSubject as M,flattenObject as Tg}from"@vkontakte/videoplayer-shared";import{Observable as oR,map as fg,Subscription as uR,Subject as lR}from"@vkontakte/videoplayer-shared";var mg=r=>new oR(e=>{let t=new uR,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(fg(({from:u,to:d})=>`${u}-${d}`)),a=r.desiredPlaybackState$.stateChangeEnded$,s=r.providerChanged$.pipe(fg(({type:u})=>u!==void 0)),n=new lR,o=0,l="unknown";return t.add(i.subscribe(u=>{o&&window.clearTimeout(o),l=u,o=window.setTimeout(()=>n.next(u),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(l),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as bg,Subscription as cR,combine as dR,filter as gg,once as Sg}from"@vkontakte/videoplayer-shared";var pa=null,qs=null;function Hu(){return pa||(pa=new(window.AudioContext||window.webkitAudioContext)),qs||(qs=new GainNode(pa,{gain:1}),qs.connect(pa.destination)),{audioCtx:pa,gainNode:qs}}import{clientChecker as pR}from"@vkontakte/videoplayer-shared";var Oi=class r{constructor(e,t,i,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=a;this.audioContextInit=!1;this.subscriptions=new cR;this.lastAudioContextResumeId=0;this.subscriptions.add(this.provider$.pipe(gg(s=>!!s.type),Sg()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){pR.isSafari&&e!=="MPEG"||this.subscriptions.add(dR({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(gg(({playbackState:t,video:i,volume:{muted:a,volume:s}})=>t==="playing"&&!!i&&!a&&!!s),Sg()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:a}=Hu(),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),this.audioContextInit=!0}catch(n){this.volumeMultiplierError$.next({id:r.errorId,category:bg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:r.errorId,category:bg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){if(this.audioContextInit){let{gainNode:e}=Hu();e.gain.value=1}this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var SR={chunkDuration:5e3,maxParallelRequests:5},fa=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new be;this.noAvailableProvidersError$=new be;this.volumeMultiplierError$=new be;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new be,warning$:new be,willSeekEvent$:new be,soundProhibitedEvent$:new be,seekedEvent$:new be,loopedEvent$:new be,endedEvent$:new be,firstBytesEvent$:new be,loadedMetadataEvent$:new be,firstFrameEvent$:new be,canplay$:new be,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new yg;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Fm([...Um(this.params.tuning),...qm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>vg(e.sources[u])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning,s=[];i?s=[i]:a.length?s=[...t.filter(u=>!a.includes(u)),...t.filter(u=>a.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Tg(s)),this.screenFormatsIterator=new da(s);let n=[...nu(!0),...nu(!1)];this.chromecastFormatsIterator=new da(n.filter(u=>vg(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:l}}=this.params;l&&o!==1&&Oi.isSupported()&&(this.volumeMultiplierManager=new Oi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}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.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(fR(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Us.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 ha(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]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Et(o),new ra({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new aa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Et(o),Pi||!this.params.tuning.useHlsJs?new ua({...n,source:o}):new na({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new oa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Et(o),new la({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new Cm({...n,source:o,config:{...SR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new ca({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 ha(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 Et(o),new cr({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 ha(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ha(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 ha(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,Ig.default)(Object.entries(e).map(([a,s])=>[a,i(s)]))}initProviderErrorHandling(){let e=new yg,t=!1,i=0;return e.add(bR(this.providerOutput.error$,mg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(mR(a=>({id:`ProviderHangup:${a}`,category:Us.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(hR(({to:s})=>s==="playing"),gR()).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===Us.NETWORK,l=a.category===Us.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!l,c=u&&!l&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:l,haveFailoverHost:u,tryFailover:c,canReinitProvider:d},this.params.tuning.useNewProviderReinitLogic?d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN"):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",Tg(n))})),e}};import{fromEvent as Hs,once as vR,combine as yR,Subscription as Eg,ValueSubject as ju,map as TR,filter as IR,isNonNullable as js,now as Ie,safeStorage as Gu}from"@vkontakte/videoplayer-shared";var ER=5e3,xg="one_video_throughput",Pg="one_video_rtt",ma=window.navigator.connection,Ag=()=>{let r=ma?.downlink;if(js(r)&&r!==10)return r*1e3},kg=()=>{let r=ma?.rtt;if(js(r)&&r!==3e3)return r},wg=(r,e,t)=>{let i=t*8,a=i/r;return i/(a+e)},Wu=class r{constructor(e){this.subscription=new Eg;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=r.load(xg)||(e.useBrowserEstimation?Ag():void 0)||ER,i=r.load(Pg)??(e.useBrowserEstimation?kg():void 0)??0;if(this.throughput$=new ju(t),this.rtt$=new ju(i),this.rttAdjustedThroughput$=new ju(wg(t,i,e.rttPenaltyRequestSize)),this.throughput=zt.getSmoothedValue(t,-1,e),this.rtt=zt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let a=()=>{let n=Ag();n&&this.throughput.next(n);let o=kg();js(o)&&this.rtt.next(o)};ma&&"onchange"in ma&&this.subscription.add(Hs(ma,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Gu.set(xg,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Gu.set(Pg,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(yR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(TR(({throughput:a,rtt:s})=>wg(a,s,e.rttPenaltyRequestSize)),IR(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=Ie(),a=new Eg;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Hs(e,"progress").pipe(vR()).subscribe(s=>{t=s.loaded,i=Ie()}));break;case 1:case 0:a.add(Hs(e,"loadstart").subscribe(()=>{t=0,i=Ie()}));break}a.add(Hs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ie(),l=n-t,u=o-i;this.addRawSpeed(l,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=Ie(),n=0,o=Ie(),l=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(a,Ie()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=Ie();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,s=Ie()}else n+=c.byteLength;o=Ie()}else a+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ie()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ie()-o,this.concurrentDownloads.size),n=0,o=Ie());await i?.read().then(u,l)}};this.concurrentDownloads.add(e),i?.read().then(u,l)}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=Gu.get(e);if(js(t))return parseInt(t,10)??void 0}},Rg=Wu;import{fillWithDefault as xR,VideoQuality as $g}from"@vkontakte/videoplayer-shared";var Lg={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:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:1,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:$g.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:$g.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,useNewSwitchTo:!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},Mg=r=>({...xR(r,Lg),configName:[...r.configName??[],...Lg.configName]});import{assertNonNullable as Gs,combine as xt,ErrorCategory as Ws,filter as ae,filterChanged as B,fromEvent as Yu,isNonNullable as LR,isNullable as MR,Logger as CR,map as C,mapTo as Og,merge as Pt,now as Qs,once as Ze,Subject as N,Subscription as Vg,tap as _g,ValueSubject as P,isHigher as DR,isInvariantQuality as Ng,flattenObject as At,throttle as zu,getTraceSubscriptionMethod as Fg,Tracer as BR}from"@vkontakte/videoplayer-shared";import{merge as PR,map as AR,filter as Cg,isNonNullable as kR}from"@vkontakte/videoplayer-shared";var Qu=({seekState:r,position$:e})=>PR(r.stateChangeEnded$.pipe(AR(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Cg(kR)),e.pipe(Cg(()=>r.getState().state==="none")));import{assertNonNullable as wR}from"@vkontakte/videoplayer-shared";var Dg=r=>{let e=typeof r.container=="string"?document.getElementById(r.container):r.container;return wR(e,`Wrong container or containerId {${r.container}}`),e};import{filter as RR,once as $R}from"@vkontakte/videoplayer-shared";var Bg=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(RR(a=>a.length>0),$R()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};var Ys=class{constructor(e={configName:[]},t=BR.createRootTracer(!1)){this.subscription=new Vg;this.logger=new CR;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new N,ready$:new N,started$:new N,playing$:new N,paused$:new N,stopped$:new N,willStart$:new N,willResume$:new N,willPause$:new N,willStop$:new N,willDestruct$:new N,watchCoverageRecord$:new N,watchCoverageLive$:new N,managedError$:new N,fatalError$:new N,ended$:new N,looped$:new N,seeked$:new N,willSeek$:new N,autoplaySoundProhibited$:new N,firstBytes$:new N,loadedMetadata$:new N,firstFrame$:new N,canplay$:new N,log$:new N};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:pm};if(this.initLogs(),this.tuning=Mg(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new xa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Rg(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(l){let u=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),d=`Player.${String(a)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Ws.WTF,message:c,thrown:l}),l}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",At(i)),this.domContainer=Dg(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new fa({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&&!yr()?(this.tracer.log("request play from hidden tab"),Yu(document,"visibilitychange").pipe(Ze()).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){Gs(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(ae(i=>i.length>0),Ze()).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",At(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){Gs(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",At(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Bg(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(MR(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return LR(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(Pt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ae(({from:e})=>e==="stopped"),Ze()).subscribe(()=>{this.initedAt=Qs(),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",At(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ws.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ze()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",At(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),B()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,l)=>Ng(o)?1:Ng(l)?-1:DR(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let l of n)l.fps&&(o[l.quality]=l.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(B()).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(B((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(B((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(B()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(B()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(B()).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(C(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(xt({hasLiveOffsetByPaused:Pt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),B(),C(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(xt({atLiveEdge:xt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Qu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),B(),_g(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(xt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),B(),_g(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),B()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),B()).subscribe(this.info.volume$)).add(Qu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Pt(e.providerOutput.endedEvent$.pipe(Og(!0)),e.providerOutput.seekedEvent$.pipe(Og(!1))).pipe(B()).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(C(n=>({id:n?`No${n}`:"NoProviders",category:Ws.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(Ze(),C(n=>n??Qs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ze(),C(()=>Qs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ze(),C(()=>Qs()-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(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new P(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ae(({to:n})=>n==="playing"),Ze()).subscribe(()=>i.next(!1)));let a=0,s=Pt(e.providerOutput.isBuffering$,t,i).pipe(C(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),B());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(Pt(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(Pt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":l?u?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Vg;this.subscription.add(t),this.subscription.add(e.current$.pipe(B((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ae(i=>i.length>0),Ze()).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=Tt(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(Pt(this.desiredState.videoTrack.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(C(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;Gs(this.providerContainer),Gs(e),dm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>cm(t)),this.providerContainer.current$.subscribe(({type:t})=>fr("provider",t)),e.duration$.subscribe(t=>fr("duration",t)),e.availableVideoTracks$.pipe(ae(t=>!!t.length),Ze()).subscribe(t=>fr("tracks",t)),this.events.fatalError$.subscribe(new re("fatalError")),this.events.managedError$.subscribe(new re("managedError")),e.position$.subscribe(new re("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new re("quality")),this.info.currentBuffer$.subscribe(new re("buffer")),e.isBuffering$.subscribe(new re("isBuffering"))].forEach(t=>this.subscription.add(t)),fr("codecs",Nm())}initTracerSubscription(){let e=Fg(this.tracer.log.bind(this.tracer)),t=Fg(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(B()).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(xt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ae(({currentQuality:i,videoBitrate:a})=>!!i&&!!a),B((i,a)=>i.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ae(i=>i>0),B()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ae(i=>i>0),B()).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(xt({currentBuffer:this.info.currentBuffer$.pipe(ae(i=>i.end>0),B((i,a)=>i.end===a.end&&i.start===a.start)),position:this.info.position$.pipe(B())}).pipe(zu(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(B()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(B()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(B()).subscribe(e("canChangePlaybackSpeed"))).add(xt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ae(({liveTime:i,liveBufferTime:a})=>!!i&&!!a),zu(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(B(),ae(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(B(),ae(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(B()).subscribe(e("muted"))).add(this.info.volume$.pipe(B()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(B(),ae(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(xt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ae(({throughputEstimation:i,rtt:a})=>!!i&&!!a),zu(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(B(),ae(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:Ws.DOM,message:String(a)})})};this.subscription.add(Pt(Yu(document,"visibilitychange"),Yu(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",At({quality:t,availableTracks:At(e),track:At(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}};import{Subscription as Bj,Observable as Oj,Subject as Vj,ValueSubject as _j,VideoQuality as Nj}from"@vkontakte/videoplayer-shared";var Fj=`@vkontakte/videoplayer-core@${Xu}`;export{Ia as ChromecastState,Ks as HttpConnectionType,Oj as Observable,se as PlaybackState,Ys as Player,Fj as SDK_VERSION,Vj as Subject,Bj as Subscription,Js as Surface,Xu as VERSION,_j as ValueSubject,mt as VideoFormat,Nj as VideoQuality};
119
+ `;var Cs=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 Ls(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ms(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(Qb,this.gl.VERTEX_SHADER),i=this.createShader(Yb,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,u=t-a,l=e+i,d=t+a,c=e-i,p=t+a;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Jt=class{constructor(e){this.subscription=new cw;this.videoState=new L("stopped");this.elementSize$=new dw(void 0);this.textTracksManager=new we;this.droppedFramesManager=new ps;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.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"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&E(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"&&E(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"&&E(this.params.desiredState.playbackState,"paused");return;default:return rw(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Cs(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=oe(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(z(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 $s({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=ce(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Cu.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(zb(l=>!!l.length),Jb()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})})),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(zb(ow),Jb()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Kb(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Ke(this.video,t.isLooped,a)),this.subscription.add(le(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(ke(this.video,t.playbackRate,i.playbackRateState$,a)),s(lw(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"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(aw(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push(Iu(h));let m=[];for(let b of h.representations){let g=Cb(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of d.video){c.push(Eu(p));let h=[];for(let m of p.representations){let b=Mb(m);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}if(this.params.output.availableVideoStreams$.next(c),this.textTracksManager)for(let p of d.text)for(let h of p.representations){let m=Db(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=l=>e.error$.next({id:"RepresentationSwitch",category:Cu.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(Ds(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$,nw(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[p,h]=c,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Du()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:p}]=d,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Eu(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Du()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:p}]=d,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Iu(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),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(Kb(({to:l})=>l==="ready"),Du());this.subscription.add(Ds(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(Ds(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Ds(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,uw(["init"])).pipe(sw(0));this.subscription.add(u.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:w})=>w===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:w})=>w===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=Xe(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:w})=>w===m?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!i)if(this.params.tuning.useSeparateAudioVideoABR){let w=us(n,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,w?.bitrate??-1/0)}else{let w=Is(n,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,w?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let w=us(o,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,w?.bitrate??-1/0)}else{let w=Is(o,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,w?.bitrate??-1/0)}}let y=Tt(d,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),A=i?y??n:n??y,T;this.params.tuning.useSeparateAudioVideoABR?T=b&&Im(A,d,this.audioStreamsMap.get(b)??[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):T=b&&Is(A,d,this.audioStreamsMap.get(b)??[]);let S=this.videoTracksMap.get(A)?.representation,I=T&&this.audioTracksMap.get(T)?.representation;if(S&&I)return[S,I];if(S&&!I&&this.audioTracksMap.size===0)return[S,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cu.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),ue(this.video),this.tracer.end()}};var ra=class extends Jt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Xb,interval as pw,map as hw}from"@vkontakte/videoplayer-shared";var aa=class extends Jt{constructor(e){super(e),this.liveOffset=new nt,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(Xb({interval:pw(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(Xb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(hw(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=Bb(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 eg=Ye(ss(),1);import{assertNever as sa,assertNonNullable as Zb,debounce as fw,ErrorCategory as Bs,filter as mw,isNonNullable as bw,isNullable as gw,map as Os,merge as Sw,Observable as vw,observableFrom as yw,Subscription as Tw,videoSizeToQuality as Iw}from"@vkontakte/videoplayer-shared";var je={};var Bi=(r,e)=>new vw(t=>{let i=(a,s)=>t.next(s);return r.on(e,i),()=>r.off(e,i)}),na=class{constructor(e){this.subscription=new Tw;this.videoState=new L("initializing");this.textTracksManager=new we;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:sa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:sa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:sa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:sa(e)}break;default:sa(t)}};this.video=oe(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(z(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),ue(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Bs.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,eg.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(){Zb(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(){Zb(je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Bs.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=ce(this.video),s=(l,d)=>this.subscription.add(l.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(Ke(this.video,e.isLooped,i)),this.subscription.add(le(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ke(this.video,e.playbackRate,a.playbackRateState$,i)),s($e(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Os(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Bi(this.hls,je.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Bs.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(Bi(this.hls,je.Events.MANIFEST_PARSED).pipe(Os(({levels:l})=>l.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:h,height:m}=c,b=yt(c.attrs.QUALITY??"")??Iw({width:h,height:m});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,y={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:y,level:c}),d.push(y),d},[]))),t.availableVideoTracks$),s(Bi(this.hls,je.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Bi(this.hls,je.Events.LEVEL_LOADING).pipe(Os(({url:l})=>z(l))),t.hostname$),s(Bi(this.hls,je.Events.FRAG_CHANGED),l=>{let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(gt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>Array.from(this.trackLevels.values()).find(({level:d})=>d===l)?.track,o=Bi(this.hls,je.Events.LEVEL_SWITCHED).pipe(Os(({level:l})=>n(this.hls.levels[l])));o.pipe(mw(bw)).subscribe(t.currentVideoTrack$,i),this.subscription.add(gt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(gw(l))return;let d=this.trackLevels.get(l.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=Sw(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,yw(["init"])).pipe(fw(0));this.subscription.add(u.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 de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bs.DOM,thrown:t}))||(this.videoState.setState("paused"),E(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"),E(this.params.desiredState.playbackState,"stopped",!0)}};var tg="X-Playback-Duration",Bu=async r=>{let e=await ut(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(tg)?parseInt(e.headers.get(tg),10):void 0};import{assertNever as ww,combine as Rw,debounce as $w,ErrorCategory as _s,filter as Lw,filterChanged as Mw,isNonNullable as rg,isNullable as Ns,map as ag,merge as Cw,observableFrom as Dw,Subscription as Bw,ValueSubject as _u,VideoQuality as Ow}from"@vkontakte/videoplayer-shared";var Vu=Ye(eo(),1);import{videoSizeToQuality as Ew,getExponentialDelay as xw}from"@vkontakte/videoplayer-shared";var Pw=r=>{let e=null;if(r.QUALITY&&(e=yt(r.QUALITY)),!e&&r.RESOLUTION){let[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=Ew({width:t,height:i})}return e??null},Aw=(r,e)=>{let t=r.split(`
120
+ `),i=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,Vu.default)(o[1].split(",").map(g=>g.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,c=Pw(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[g,y]=l.RESOLUTION.split("x").map(A=>parseInt(A,10));g&&y&&(m={width:g,height:y})}let b=new URL(t[++s],e).toString();c&&i.push({id:d,quality:c,url:b,bandwidth:p,size:m,fps:h})}if(u){let l=(0,Vu.default)(u[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),d=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,p=l.NAME;d&&c&&a.push({type:"internal",id:c,label:p,language:c,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},kw=r=>new Promise(e=>{setTimeout(()=>{e()},r)}),Ou=0,ig=async(r,e=r,t)=>{let a=await(await ut(r)).text();Ou+=1;try{let{qualityManifests:s,textTracks:n}=Aw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Ou<=t.manifestRetryMaxCount)return await kw(xw(Ou-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ig(r,e,t)}return{qualityManifests:[],textTracks:[]}},Vs=ig;var oa=class{constructor(e){this.subscription=new Bw;this.videoState=new L("stopped");this.textTracksManager=new we;this.manifests$=new _u([]);this.liveOffset=new nt;this.manifestStartTime$=new _u(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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?E(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(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"&&E(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"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return ww(t)}};this.params=e,this.video=oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ow.INVARIANT,url:this.params.source.url},Vs(X(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:_s.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_s.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(z(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new _u(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(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:_s.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ce(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,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(le(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ke(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"),E(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(Mw(),ag(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&rg(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(z(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Rw({startTime:this.manifestStartTime$.pipe(Lw(rg)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(ag(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=Cw(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Dw(["init"])).pipe($w(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ue(this.video)}prepare(){let e=this.selectManifest();if(Ns(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:u}=t?.to??i??{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&a.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=X(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Bu(n).then(o=>{if(!Ns(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Ns(u)||!isFinite(u))try{ut(n).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,n).toString();Bu(c).then(p=>{Ns(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_s.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()}};import{assertNever as Vw,debounce as _w,ErrorCategory as Nu,fromEvent as Fu,isNonNullable as Nw,isNullable as Fw,map as sg,merge as ng,observableFrom as og,Subscription as qw,ValueSubject as Uw,VideoQuality as Hw,clientChecker as jw}from"@vkontakte/videoplayer-shared";var ua=class{constructor(e){this.subscription=new qw;this.videoState=new L("stopped");this.textTracksManager=new we;this.manifests$=new Uw([]);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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?E(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Vw(t)}};this.params=e,this.video=oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Hw.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(z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Vs(X(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:Nu.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(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Nu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ce(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));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(sg(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,i)),this.subscription.add(le(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ke(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Nw(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(z(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(h),b.playbackRate=h)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(sg(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!jw.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(ng(Fu(o,"addtrack"),Fu(o,"removetrack"),Fu(o,"change"),og(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=ng(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,og(["init"])).pipe(_w(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ue(this.video)}prepare(){let e=this.selectManifest();if(Fw(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,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Gw,assertNonNullable as ug,debounce as Ww,ErrorCategory as lg,isHigher as Qw,isHigherOrEqual as Yw,isInvariantQuality as cg,isLowerOrEqual as zw,isNonNullable as Kw,merge as Jw,observableFrom as Xw,Subscription as Zw,map as eR}from"@vkontakte/videoplayer-shared";var la=class{constructor(e){this.subscription=new Zw;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new we;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"),E(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:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*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"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return Gw(e)}};this.params=e,this.video=oe(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:lg.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ce(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,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(eR(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,i)),this.subscription.add(le(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ke(this.video,t.playbackRate,a.playbackRateState$,i)),s($e(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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&&Kw(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=Jw(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Xw(["init"])).pipe(Ww(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),ue(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;ug(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];ug(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Kr(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(z(t))}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lg.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=>!cg(o.track.quality)&&zw(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&Yw(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(l=>!cg(l.track.quality)&&Qw(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(i=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=Tt(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})}};import{assertNever as pg,debounce as aR,merge as hg,observableFrom as sR,Subscription as nR,map as fg,ValueSubject as oR,ErrorCategory as Uu,VideoQuality as uR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as tR}from"@vkontakte/videoplayer-shared";var dg=["stun:videostun.mycdn.me:80"],iR=1e3,rR=3,qu=()=>null,Fs=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=qu;this.externalStopCallback=qu;this.externalErrorCallback=qu;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:dg}]};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:tR.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),iR)}normalizeOptions(e={}){let t={stunServerList:dg,maxRetryNumber:rR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ca=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new oR(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"),E(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"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return pg(e)}};this.subscription=new nR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=oe(e.container,e.tuning),this.liveStreamClient=new Fs(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),ue(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Uu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};hg(this.videoState.stateChangeStarted$.pipe(fg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(fg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ce(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(le(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 pg(n.to)}},i)).add(hg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,sR(["init"])).pipe(aR(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(z(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:uR.INVARIANT}),this.video.srcObject=e,E(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Uu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var da=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}};import{assertNever as ha,assertNonNullable as Et,ErrorCategory as Us,filter as mR,isNonNullable as yg,isNullable as bR,map as gR,merge as SR,once as vR,Subject as be,Subscription as Tg,ValueSubject as M,flattenObject as Ig}from"@vkontakte/videoplayer-shared";import{Observable as lR,map as mg,Subscription as cR,Subject as dR}from"@vkontakte/videoplayer-shared";var bg=r=>new lR(e=>{let t=new cR,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(mg(({from:l,to:d})=>`${l}-${d}`)),a=r.desiredPlaybackState$.stateChangeEnded$,s=r.providerChanged$.pipe(mg(({type:l})=>l!==void 0)),n=new dR,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as gg,Subscription as pR,combine as hR,filter as Sg,once as vg}from"@vkontakte/videoplayer-shared";var pa=null,qs=null;function Hu(){return pa||(pa=new(window.AudioContext||window.webkitAudioContext)),qs||(qs=new GainNode(pa,{gain:1}),qs.connect(pa.destination)),{audioCtx:pa,gainNode:qs}}import{clientChecker as fR}from"@vkontakte/videoplayer-shared";var Oi=class r{constructor(e,t,i,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=a;this.audioContextInit=!1;this.subscriptions=new pR;this.lastAudioContextResumeId=0;this.subscriptions.add(this.provider$.pipe(Sg(s=>!!s.type),vg()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){fR.isSafari&&e!=="MPEG"||this.subscriptions.add(hR({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Sg(({playbackState:t,video:i,volume:{muted:a,volume:s}})=>t==="playing"&&!!i&&!a&&!!s),vg()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:a}=Hu(),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),this.audioContextInit=!0}catch(n){this.volumeMultiplierError$.next({id:r.errorId,category:gg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:r.errorId,category:gg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){if(this.audioContextInit){let{gainNode:e}=Hu();e.gain.value=1}this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var yR={chunkDuration:5e3,maxParallelRequests:5},fa=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new be;this.noAvailableProvidersError$=new be;this.volumeMultiplierError$=new be;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new be,warning$:new be,willSeekEvent$:new be,soundProhibitedEvent$:new be,seekedEvent$:new be,loopedEvent$:new be,endedEvent$:new be,firstBytesEvent$:new be,loadedMetadataEvent$:new be,firstFrameEvent$:new be,canplay$:new be,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new Tg;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Fm([...Um(this.params.tuning),...qm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>yg(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning,s=[];i?s=[i]:a.length?s=[...t.filter(l=>!a.includes(l)),...t.filter(l=>a.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Ig(s)),this.screenFormatsIterator=new da(s);let n=[...nu(!0),...nu(!1)];this.chromecastFormatsIterator=new da(n.filter(l=>yg(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Oi.isSupported()&&(this.volumeMultiplierManager=new Oi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}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.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(bR(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Us.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 ha(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]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Et(o),new ra({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new aa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Et(o),Pi||!this.params.tuning.useHlsJs?new ua({...n,source:o}):new na({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new oa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Et(o),new la({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new Cm({...n,source:o,config:{...yR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new ca({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 ha(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 Et(o),new cr({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 ha(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ha(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 ha(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,Eg.default)(Object.entries(e).map(([a,s])=>[a,i(s)]))}initProviderErrorHandling(){let e=new Tg,t=!1,i=0;return e.add(SR(this.providerOutput.error$,bg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(gR(a=>({id:`ProviderHangup:${a}`,category:Us.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(mR(({to:s})=>s==="playing"),vR()).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===Us.NETWORK,u=a.category===Us.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},this.params.tuning.useNewProviderReinitLogic?d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN"):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",Ig(n))})),e}};import{fromEvent as Hs,once as TR,combine as IR,Subscription as xg,ValueSubject as ju,map as ER,filter as xR,isNonNullable as js,now as Ie,safeStorage as Gu}from"@vkontakte/videoplayer-shared";var PR=5e3,Pg="one_video_throughput",Ag="one_video_rtt",ma=window.navigator.connection,kg=()=>{let r=ma?.downlink;if(js(r)&&r!==10)return r*1e3},wg=()=>{let r=ma?.rtt;if(js(r)&&r!==3e3)return r},Rg=(r,e,t)=>{let i=t*8,a=i/r;return i/(a+e)},Wu=class r{constructor(e){this.subscription=new xg;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=r.load(Pg)||(e.useBrowserEstimation?kg():void 0)||PR,i=r.load(Ag)??(e.useBrowserEstimation?wg():void 0)??0;if(this.throughput$=new ju(t),this.rtt$=new ju(i),this.rttAdjustedThroughput$=new ju(Rg(t,i,e.rttPenaltyRequestSize)),this.throughput=zt.getSmoothedValue(t,-1,e),this.rtt=zt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let a=()=>{let n=kg();n&&this.throughput.next(n);let o=wg();js(o)&&this.rtt.next(o)};ma&&"onchange"in ma&&this.subscription.add(Hs(ma,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Gu.set(Pg,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Gu.set(Ag,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(IR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(ER(({throughput:a,rtt:s})=>Rg(a,s,e.rttPenaltyRequestSize)),xR(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=Ie(),a=new xg;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Hs(e,"progress").pipe(TR()).subscribe(s=>{t=s.loaded,i=Ie()}));break;case 1:case 0:a.add(Hs(e,"loadstart").subscribe(()=>{t=0,i=Ie()}));break}a.add(Hs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ie(),u=n-t,l=o-i;this.addRawSpeed(u,l,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=Ie(),n=0,o=Ie(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(a,Ie()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=Ie();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,s=Ie()}else n+=c.byteLength;o=Ie()}else a+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ie()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ie()-o,this.concurrentDownloads.size),n=0,o=Ie());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}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=Gu.get(e);if(js(t))return parseInt(t,10)??void 0}},$g=Wu;import{fillWithDefault as AR,VideoQuality as Lg}from"@vkontakte/videoplayer-shared";var Mg={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:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:1,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Lg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Lg.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,useNewSwitchTo:!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},Cg=r=>({...AR(r,Mg),configName:[...r.configName??[],...Mg.configName]});import{assertNonNullable as Gs,combine as xt,ErrorCategory as Ws,filter as ae,filterChanged as B,fromEvent as Yu,isNonNullable as CR,isNullable as DR,Logger as BR,map as C,mapTo as Vg,merge as Pt,now as Qs,once as Ze,Subject as N,Subscription as _g,tap as Ng,ValueSubject as P,isHigher as OR,isInvariantQuality as Fg,flattenObject as At,throttle as zu,getTraceSubscriptionMethod as qg,Tracer as VR}from"@vkontakte/videoplayer-shared";import{merge as kR,map as wR,filter as Dg,isNonNullable as RR}from"@vkontakte/videoplayer-shared";var Qu=({seekState:r,position$:e})=>kR(r.stateChangeEnded$.pipe(wR(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Dg(RR)),e.pipe(Dg(()=>r.getState().state==="none")));import{assertNonNullable as $R}from"@vkontakte/videoplayer-shared";var Bg=r=>{let e=typeof r.container=="string"?document.getElementById(r.container):r.container;return $R(e,`Wrong container or containerId {${r.container}}`),e};import{filter as LR,once as MR}from"@vkontakte/videoplayer-shared";var Og=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(LR(a=>a.length>0),MR()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};var Ys=class{constructor(e={configName:[]},t=VR.createRootTracer(!1)){this.subscription=new _g;this.logger=new BR;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new N,ready$:new N,started$:new N,playing$:new N,paused$:new N,stopped$:new N,willStart$:new N,willResume$:new N,willPause$:new N,willStop$:new N,willDestruct$:new N,watchCoverageRecord$:new N,watchCoverageLive$:new N,managedError$:new N,fatalError$:new N,ended$:new N,looped$:new N,seeked$:new N,willSeek$:new N,autoplaySoundProhibited$:new N,firstBytes$:new N,loadedMetadata$:new N,firstFrame$:new N,canplay$:new N,log$:new N};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:pm};if(this.initLogs(),this.tuning=Cg(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new xa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new $g(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(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),d=`Player.${String(a)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Ws.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",At(i)),this.domContainer=Bg(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new fa({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&&!yr()?(this.tracer.log("request play from hidden tab"),Yu(document,"visibilitychange").pipe(Ze()).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){Gs(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(ae(i=>i.length>0),Ze()).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",At(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){Gs(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",At(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Og(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(DR(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return CR(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(Pt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ae(({from:e})=>e==="stopped"),Ze()).subscribe(()=>{this.initedAt=Qs(),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",At(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ws.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ze()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",At(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),B()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,u)=>Fg(o)?1:Fg(u)?-1:OR(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(B()).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(B((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(B((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(B()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(B()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(B()).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(C(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(xt({hasLiveOffsetByPaused:Pt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),B(),C(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(xt({atLiveEdge:xt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Qu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),B(),Ng(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(xt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),B(),Ng(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),B()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),B()).subscribe(this.info.volume$)).add(Qu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Pt(e.providerOutput.endedEvent$.pipe(Vg(!0)),e.providerOutput.seekedEvent$.pipe(Vg(!1))).pipe(B()).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(C(n=>({id:n?`No${n}`:"NoProviders",category:Ws.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(Ze(),C(n=>n??Qs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ze(),C(()=>Qs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ze(),C(()=>Qs()-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(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new P(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ae(({to:n})=>n==="playing"),Ze()).subscribe(()=>i.next(!1)));let a=0,s=Pt(e.providerOutput.isBuffering$,t,i).pipe(C(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),B());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(Pt(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(Pt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new _g;this.subscription.add(t),this.subscription.add(e.current$.pipe(B((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ae(i=>i.length>0),Ze()).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=Tt(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(Pt(this.desiredState.videoTrack.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(C(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;Gs(this.providerContainer),Gs(e),dm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>cm(t)),this.providerContainer.current$.subscribe(({type:t})=>fr("provider",t)),e.duration$.subscribe(t=>fr("duration",t)),e.availableVideoTracks$.pipe(ae(t=>!!t.length),Ze()).subscribe(t=>fr("tracks",t)),this.events.fatalError$.subscribe(new re("fatalError")),this.events.managedError$.subscribe(new re("managedError")),e.position$.subscribe(new re("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new re("quality")),this.info.currentBuffer$.subscribe(new re("buffer")),e.isBuffering$.subscribe(new re("isBuffering"))].forEach(t=>this.subscription.add(t)),fr("codecs",Nm())}initTracerSubscription(){let e=qg(this.tracer.log.bind(this.tracer)),t=qg(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(B()).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(xt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ae(({currentQuality:i,videoBitrate:a})=>!!i&&!!a),B((i,a)=>i.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ae(i=>i>0),B()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ae(i=>i>0),B()).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(xt({currentBuffer:this.info.currentBuffer$.pipe(ae(i=>i.end>0),B((i,a)=>i.end===a.end&&i.start===a.start)),position:this.info.position$.pipe(B())}).pipe(zu(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(B()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(B()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(B()).subscribe(e("canChangePlaybackSpeed"))).add(xt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ae(({liveTime:i,liveBufferTime:a})=>!!i&&!!a),zu(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(B(),ae(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(B(),ae(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(B()).subscribe(e("muted"))).add(this.info.volume$.pipe(B()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(B(),ae(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(xt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ae(({throughputEstimation:i,rtt:a})=>!!i&&!!a),zu(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(B(),ae(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:Ws.DOM,message:String(a)})})};this.subscription.add(Pt(Yu(document,"visibilitychange"),Yu(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",At({quality:t,availableTracks:At(e),track:At(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}};import{Subscription as Nj,Observable as Fj,Subject as qj,ValueSubject as Uj,VideoQuality as Hj}from"@vkontakte/videoplayer-shared";var jj=`@vkontakte/videoplayer-core@${Xu}`;export{Ia as ChromecastState,Ks as HttpConnectionType,Fj as Observable,se as PlaybackState,Ys as Player,jj as SDK_VERSION,qj as Subject,Nj as Subscription,Js as Surface,Xu as VERSION,Uj as ValueSubject,mt as VideoFormat,Hj as VideoQuality};