@vkontakte/videoplayer-core 2.0.108-dev.43b53ca1.0 → 2.0.108-dev.69cab4e9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.cjs.js CHANGED
@@ -1,18 +1,15 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.108-dev.43b53ca1.0
3
- * Thu, 29 Aug 2024 16:46:43 GMT
2
+ * @vkontakte/videoplayer-core v2.0.108-dev.69cab4e9.0
3
+ * Fri, 30 Aug 2024 10:19:03 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
5
5
  */
6
- "use strict";var eg=Object.create;var Wr=Object.defineProperty,tg=Object.defineProperties,rg=Object.getOwnPropertyDescriptor,ig=Object.getOwnPropertyDescriptors,ag=Object.getOwnPropertyNames,Yu=Object.getOwnPropertySymbols,sg=Object.getPrototypeOf,Qu=Object.prototype.hasOwnProperty,ng=Object.prototype.propertyIsEnumerable;var og=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,Wu=(a,e,t)=>e in a?Wr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,_=(a,e)=>{for(var t in e||(e={}))Qu.call(e,t)&&Wu(a,t,e[t]);if(Yu)for(var t of Yu(e))ng.call(e,t)&&Wu(a,t,e[t]);return a},X=(a,e)=>tg(a,ig(e));var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),ug=(a,e)=>{for(var t in e)Wr(a,t,{get:e[t],enumerable:!0})},zu=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ag(e))!Qu.call(a,i)&&i!==t&&Wr(a,i,{get:()=>e[i],enumerable:!(r=rg(e,i))||r.enumerable});return a};var Ke=(a,e,t)=>(t=a!=null?eg(sg(a)):{},zu(e||!a||!a.__esModule?Wr(t,"default",{value:a,enumerable:!0}):t,a)),lg=a=>zu(Wr({},"__esModule",{value:!0}),a);var D=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),cg=function(a,e){this[0]=a,this[1]=e},ge=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof cg,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[og("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var De=b((TA,Ju)=>{"use strict";Ju.exports=function(a){try{return!!a()}catch(e){return!0}}});var zr=b((IA,Xu)=>{"use strict";var pg=De();Xu.exports=!pg(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Ae=b((EA,tl)=>{"use strict";var Zu=zr(),el=Function.prototype,Js=el.call,hg=Zu&&el.bind.bind(Js,Js);tl.exports=Zu?hg:function(a){return function(){return Js.apply(a,arguments)}}});var pr=b((xA,il)=>{"use strict";var rl=Ae(),fg=rl({}.toString),mg=rl("".slice);il.exports=function(a){return mg(fg(a),8,-1)}});var sl=b((PA,al)=>{"use strict";var bg=Ae(),gg=De(),Sg=pr(),Xs=Object,vg=bg("".split);al.exports=gg(function(){return!Xs("z").propertyIsEnumerable(0)})?function(a){return Sg(a)==="String"?vg(a,""):Xs(a)}:Xs});var hr=b((AA,nl)=>{"use strict";nl.exports=function(a){return a==null}});var Kr=b((wA,ol)=>{"use strict";var yg=hr(),Tg=TypeError;ol.exports=function(a){if(yg(a))throw new Tg("Can't call method on "+a);return a}});var fr=b((kA,ul)=>{"use strict";var Ig=sl(),Eg=Kr();ul.exports=function(a){return Ig(Eg(a))}});var Zs=b((RA,ll)=>{"use strict";ll.exports=function(){}});var jt=b((LA,cl)=>{"use strict";cl.exports={}});var ce=b((en,dl)=>{"use strict";var Jr=function(a){return a&&a.Math===Math&&a};dl.exports=Jr(typeof globalThis=="object"&&globalThis)||Jr(typeof window=="object"&&window)||Jr(typeof self=="object"&&self)||Jr(typeof global=="object"&&global)||Jr(typeof en=="object"&&en)||function(){return this}()||Function("return this")()});var le=b(($A,pl)=>{"use strict";var tn=typeof document=="object"&&document.all;pl.exports=typeof tn=="undefined"&&tn!==void 0?function(a){return typeof a=="function"||a===tn}:function(a){return typeof a=="function"}});var ml=b((MA,fl)=>{"use strict";var xg=ce(),Pg=le(),hl=xg.WeakMap;fl.exports=Pg(hl)&&/native code/.test(String(hl))});var Fe=b((CA,bl)=>{"use strict";var Ag=le();bl.exports=function(a){return typeof a=="object"?a!==null:Ag(a)}});var qe=b((DA,gl)=>{"use strict";var wg=De();gl.exports=!wg(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Pa=b((OA,vl)=>{"use strict";var kg=ce(),Sl=Fe(),rn=kg.document,Rg=Sl(rn)&&Sl(rn.createElement);vl.exports=function(a){return Rg?rn.createElement(a):{}}});var an=b((BA,yl)=>{"use strict";var Lg=qe(),$g=De(),Mg=Pa();yl.exports=!Lg&&!$g(function(){return Object.defineProperty(Mg("div"),"a",{get:function(){return 7}}).a!==7})});var sn=b((VA,Tl)=>{"use strict";var Cg=qe(),Dg=De();Tl.exports=Cg&&Dg(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var st=b((_A,Il)=>{"use strict";var Og=Fe(),Bg=String,Vg=TypeError;Il.exports=function(a){if(Og(a))return a;throw new Vg(Bg(a)+" is not an object")}});var Oe=b((NA,El)=>{"use strict";var _g=zr(),Aa=Function.prototype.call;El.exports=_g?Aa.bind(Aa):function(){return Aa.apply(Aa,arguments)}});var wa=b((FA,xl)=>{"use strict";xl.exports={}});var ht=b((qA,Al)=>{"use strict";var nn=wa(),on=ce(),Ng=le(),Pl=function(a){return Ng(a)?a:void 0};Al.exports=function(a,e){return arguments.length<2?Pl(nn[a])||Pl(on[a]):nn[a]&&nn[a][e]||on[a]&&on[a][e]}});var Xr=b((UA,wl)=>{"use strict";var Fg=Ae();wl.exports=Fg({}.isPrototypeOf)});var mr=b((HA,Ll)=>{"use strict";var qg=ce(),kl=qg.navigator,Rl=kl&&kl.userAgent;Ll.exports=Rl?String(Rl):""});var ln=b((jA,Bl)=>{"use strict";var Ol=ce(),un=mr(),$l=Ol.process,Ml=Ol.Deno,Cl=$l&&$l.versions||Ml&&Ml.version,Dl=Cl&&Cl.v8,Je,ka;Dl&&(Je=Dl.split("."),ka=Je[0]>0&&Je[0]<4?1:+(Je[0]+Je[1]));!ka&&un&&(Je=un.match(/Edge\/(\d+)/),(!Je||Je[1]>=74)&&(Je=un.match(/Chrome\/(\d+)/),Je&&(ka=+Je[1])));Bl.exports=ka});var cn=b((GA,_l)=>{"use strict";var Vl=ln(),Ug=De(),Hg=ce(),jg=Hg.String;_l.exports=!!Object.getOwnPropertySymbols&&!Ug(function(){var a=Symbol("symbol detection");return!jg(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Vl&&Vl<41})});var dn=b((YA,Nl)=>{"use strict";var Gg=cn();Nl.exports=Gg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var pn=b((WA,Fl)=>{"use strict";var Yg=ht(),Wg=le(),Qg=Xr(),zg=dn(),Kg=Object;Fl.exports=zg?function(a){return typeof a=="symbol"}:function(a){var e=Yg("Symbol");return Wg(e)&&Qg(e.prototype,Kg(a))}});var Zr=b((QA,ql)=>{"use strict";var Jg=String;ql.exports=function(a){try{return Jg(a)}catch(e){return"Object"}}});var ft=b((zA,Ul)=>{"use strict";var Xg=le(),Zg=Zr(),eS=TypeError;Ul.exports=function(a){if(Xg(a))return a;throw new eS(Zg(a)+" is not a function")}});var ei=b((KA,Hl)=>{"use strict";var tS=ft(),rS=hr();Hl.exports=function(a,e){var t=a[e];return rS(t)?void 0:tS(t)}});var Gl=b((JA,jl)=>{"use strict";var hn=Oe(),fn=le(),mn=Fe(),iS=TypeError;jl.exports=function(a,e){var t,r;if(e==="string"&&fn(t=a.toString)&&!mn(r=hn(t,a))||fn(t=a.valueOf)&&!mn(r=hn(t,a))||e!=="string"&&fn(t=a.toString)&&!mn(r=hn(t,a)))return r;throw new iS("Can't convert object to primitive value")}});var Xe=b((XA,Yl)=>{"use strict";Yl.exports=!0});var zl=b((ZA,Ql)=>{"use strict";var Wl=ce(),aS=Object.defineProperty;Ql.exports=function(a,e){try{aS(Wl,a,{value:e,configurable:!0,writable:!0})}catch(t){Wl[a]=e}return e}});var ti=b((ew,Xl)=>{"use strict";var sS=Xe(),nS=ce(),oS=zl(),Kl="__core-js_shared__",Jl=Xl.exports=nS[Kl]||oS(Kl,{});(Jl.versions||(Jl.versions=[])).push({version:"3.38.0",mode:sS?"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 bn=b((tw,ec)=>{"use strict";var Zl=ti();ec.exports=function(a,e){return Zl[a]||(Zl[a]=e||{})}});var ri=b((rw,tc)=>{"use strict";var uS=Kr(),lS=Object;tc.exports=function(a){return lS(uS(a))}});var Ze=b((iw,rc)=>{"use strict";var cS=Ae(),dS=ri(),pS=cS({}.hasOwnProperty);rc.exports=Object.hasOwn||function(e,t){return pS(dS(e),t)}});var gn=b((aw,ic)=>{"use strict";var hS=Ae(),fS=0,mS=Math.random(),bS=hS(1 .toString);ic.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+bS(++fS+mS,36)}});var Ie=b((sw,sc)=>{"use strict";var gS=ce(),SS=bn(),ac=Ze(),vS=gn(),yS=cn(),TS=dn(),br=gS.Symbol,Sn=SS("wks"),IS=TS?br.for||br:br&&br.withoutSetter||vS;sc.exports=function(a){return ac(Sn,a)||(Sn[a]=yS&&ac(br,a)?br[a]:IS("Symbol."+a)),Sn[a]}});var lc=b((nw,uc)=>{"use strict";var ES=Oe(),nc=Fe(),oc=pn(),xS=ei(),PS=Gl(),AS=Ie(),wS=TypeError,kS=AS("toPrimitive");uc.exports=function(a,e){if(!nc(a)||oc(a))return a;var t=xS(a,kS),r;if(t){if(e===void 0&&(e="default"),r=ES(t,a,e),!nc(r)||oc(r))return r;throw new wS("Can't convert object to primitive value")}return e===void 0&&(e="number"),PS(a,e)}});var vn=b((ow,cc)=>{"use strict";var RS=lc(),LS=pn();cc.exports=function(a){var e=RS(a,"string");return LS(e)?e:e+""}});var Gt=b(pc=>{"use strict";var $S=qe(),MS=an(),CS=sn(),Ra=st(),dc=vn(),DS=TypeError,yn=Object.defineProperty,OS=Object.getOwnPropertyDescriptor,Tn="enumerable",In="configurable",En="writable";pc.f=$S?CS?function(e,t,r){if(Ra(e),t=dc(t),Ra(r),typeof e=="function"&&t==="prototype"&&"value"in r&&En in r&&!r[En]){var i=OS(e,t);i&&i[En]&&(e[t]=r.value,r={configurable:In in r?r[In]:i[In],enumerable:Tn in r?r[Tn]:i[Tn],writable:!1})}return yn(e,t,r)}:yn:function(e,t,r){if(Ra(e),t=dc(t),Ra(r),MS)try{return yn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new DS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var ii=b((lw,hc)=>{"use strict";hc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var gr=b((cw,fc)=>{"use strict";var BS=qe(),VS=Gt(),_S=ii();fc.exports=BS?function(a,e,t){return VS.f(a,e,_S(1,t))}:function(a,e,t){return a[e]=t,a}});var La=b((dw,bc)=>{"use strict";var NS=bn(),FS=gn(),mc=NS("keys");bc.exports=function(a){return mc[a]||(mc[a]=FS(a))}});var $a=b((pw,gc)=>{"use strict";gc.exports={}});var wn=b((hw,yc)=>{"use strict";var qS=ml(),vc=ce(),US=Fe(),HS=gr(),xn=Ze(),Pn=ti(),jS=La(),GS=$a(),Sc="Object already initialized",An=vc.TypeError,YS=vc.WeakMap,Ma,ai,Ca,WS=function(a){return Ca(a)?ai(a):Ma(a,{})},QS=function(a){return function(e){var t;if(!US(e)||(t=ai(e)).type!==a)throw new An("Incompatible receiver, "+a+" required");return t}};qS||Pn.state?(et=Pn.state||(Pn.state=new YS),et.get=et.get,et.has=et.has,et.set=et.set,Ma=function(a,e){if(et.has(a))throw new An(Sc);return e.facade=a,et.set(a,e),e},ai=function(a){return et.get(a)||{}},Ca=function(a){return et.has(a)}):(Yt=jS("state"),GS[Yt]=!0,Ma=function(a,e){if(xn(a,Yt))throw new An(Sc);return e.facade=a,HS(a,Yt,e),e},ai=function(a){return xn(a,Yt)?a[Yt]:{}},Ca=function(a){return xn(a,Yt)});var et,Yt;yc.exports={set:Ma,get:ai,has:Ca,enforce:WS,getterFor:QS}});var kn=b((fw,xc)=>{"use strict";var zS=zr(),Ec=Function.prototype,Tc=Ec.apply,Ic=Ec.call;xc.exports=typeof Reflect=="object"&&Reflect.apply||(zS?Ic.bind(Tc):function(){return Ic.apply(Tc,arguments)})});var Rn=b((mw,Pc)=>{"use strict";var KS=pr(),JS=Ae();Pc.exports=function(a){if(KS(a)==="Function")return JS(a)}});var Rc=b(kc=>{"use strict";var Ac={}.propertyIsEnumerable,wc=Object.getOwnPropertyDescriptor,XS=wc&&!Ac.call({1:2},1);kc.f=XS?function(e){var t=wc(this,e);return!!t&&t.enumerable}:Ac});var Mc=b($c=>{"use strict";var ZS=qe(),ev=Oe(),tv=Rc(),rv=ii(),iv=fr(),av=vn(),sv=Ze(),nv=an(),Lc=Object.getOwnPropertyDescriptor;$c.f=ZS?Lc:function(e,t){if(e=iv(e),t=av(t),nv)try{return Lc(e,t)}catch(r){}if(sv(e,t))return rv(!ev(tv.f,e,t),e[t])}});var Ln=b((Sw,Cc)=>{"use strict";var ov=De(),uv=le(),lv=/#|\.prototype\./,si=function(a,e){var t=dv[cv(a)];return t===hv?!0:t===pv?!1:uv(e)?ov(e):!!e},cv=si.normalize=function(a){return String(a).replace(lv,".").toLowerCase()},dv=si.data={},pv=si.NATIVE="N",hv=si.POLYFILL="P";Cc.exports=si});var ni=b((vw,Oc)=>{"use strict";var Dc=Rn(),fv=ft(),mv=zr(),bv=Dc(Dc.bind);Oc.exports=function(a,e){return fv(a),e===void 0?a:mv?bv(a,e):function(){return a.apply(e,arguments)}}});var Ue=b((yw,Vc)=>{"use strict";var oi=ce(),gv=kn(),Sv=Rn(),vv=le(),yv=Mc().f,Tv=Ln(),Sr=wa(),Iv=ni(),vr=gr(),Bc=Ze();ti();var Ev=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return gv(a,this,arguments)};return e.prototype=a.prototype,e};Vc.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?oi:i?oi[t]:oi[t]&&oi[t].prototype,o=r?Sr:Sr[t]||vr(Sr,t,{})[t],u=o.prototype,l,c,d,p,h,m,g,S,T;for(p in e)l=Tv(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Bc(n,p),m=o[p],c&&(a.dontCallGetSet?(T=yv(n,p),g=T&&T.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?S=Iv(h,oi):a.wrap&&c?S=Ev(h):s&&vv(h)?S=Sv(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&vr(S,"sham",!0),vr(o,p,S),s&&(d=t+"Prototype",Bc(Sr,d)||vr(Sr,d,{}),vr(Sr[d],p,h),a.real&&u&&(l||!u[p])&&vr(u,p,h)))}});var Fc=b((Tw,Nc)=>{"use strict";var $n=qe(),xv=Ze(),_c=Function.prototype,Pv=$n&&Object.getOwnPropertyDescriptor,Mn=xv(_c,"name"),Av=Mn&&function(){}.name==="something",wv=Mn&&(!$n||$n&&Pv(_c,"name").configurable);Nc.exports={EXISTS:Mn,PROPER:Av,CONFIGURABLE:wv}});var Uc=b((Iw,qc)=>{"use strict";var kv=Math.ceil,Rv=Math.floor;qc.exports=Math.trunc||function(e){var t=+e;return(t>0?Rv:kv)(t)}});var Da=b((Ew,Hc)=>{"use strict";var Lv=Uc();Hc.exports=function(a){var e=+a;return e!==e||e===0?0:Lv(e)}});var Gc=b((xw,jc)=>{"use strict";var $v=Da(),Mv=Math.max,Cv=Math.min;jc.exports=function(a,e){var t=$v(a);return t<0?Mv(t+e,0):Cv(t,e)}});var Wc=b((Pw,Yc)=>{"use strict";var Dv=Da(),Ov=Math.min;Yc.exports=function(a){var e=Dv(a);return e>0?Ov(e,9007199254740991):0}});var Oa=b((Aw,Qc)=>{"use strict";var Bv=Wc();Qc.exports=function(a){return Bv(a.length)}});var Jc=b((ww,Kc)=>{"use strict";var Vv=fr(),_v=Gc(),Nv=Oa(),zc=function(a){return function(e,t,r){var i=Vv(e),s=Nv(i);if(s===0)return!a&&-1;var n=_v(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Kc.exports={includes:zc(!0),indexOf:zc(!1)}});var ed=b((kw,Zc)=>{"use strict";var Fv=Ae(),Cn=Ze(),qv=fr(),Uv=Jc().indexOf,Hv=$a(),Xc=Fv([].push);Zc.exports=function(a,e){var t=qv(a),r=0,i=[],s;for(s in t)!Cn(Hv,s)&&Cn(t,s)&&Xc(i,s);for(;e.length>r;)Cn(t,s=e[r++])&&(~Uv(i,s)||Xc(i,s));return i}});var Dn=b((Rw,td)=>{"use strict";td.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var id=b((Lw,rd)=>{"use strict";var jv=ed(),Gv=Dn();rd.exports=Object.keys||function(e){return jv(e,Gv)}});var sd=b(ad=>{"use strict";var Yv=qe(),Wv=sn(),Qv=Gt(),zv=st(),Kv=fr(),Jv=id();ad.f=Yv&&!Wv?Object.defineProperties:function(e,t){zv(e);for(var r=Kv(t),i=Jv(t),s=i.length,n=0,o;s>n;)Qv.f(e,o=i[n++],r[o]);return e}});var On=b((Mw,nd)=>{"use strict";var Xv=ht();nd.exports=Xv("document","documentElement")});var Nn=b((Cw,hd)=>{"use strict";var Zv=st(),ey=sd(),od=Dn(),ty=$a(),ry=On(),iy=Pa(),ay=La(),ud=">",ld="<",Vn="prototype",_n="script",dd=ay("IE_PROTO"),Bn=function(){},pd=function(a){return ld+_n+ud+a+ld+"/"+_n+ud},cd=function(a){a.write(pd("")),a.close();var e=a.parentWindow.Object;return a=null,e},sy=function(){var a=iy("iframe"),e="java"+_n+":",t;return a.style.display="none",ry.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(pd("document.F=Object")),t.close(),t.F},Ba,Va=function(){try{Ba=new ActiveXObject("htmlfile")}catch(e){}Va=typeof document!="undefined"?document.domain&&Ba?cd(Ba):sy():cd(Ba);for(var a=od.length;a--;)delete Va[Vn][od[a]];return Va()};ty[dd]=!0;hd.exports=Object.create||function(e,t){var r;return e!==null?(Bn[Vn]=Zv(e),r=new Bn,Bn[Vn]=null,r[dd]=e):r=Va(),t===void 0?r:ey.f(r,t)}});var md=b((Dw,fd)=>{"use strict";var ny=De();fd.exports=!ny(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var qn=b((Ow,gd)=>{"use strict";var oy=Ze(),uy=le(),ly=ri(),cy=La(),dy=md(),bd=cy("IE_PROTO"),Fn=Object,py=Fn.prototype;gd.exports=dy?Fn.getPrototypeOf:function(a){var e=ly(a);if(oy(e,bd))return e[bd];var t=e.constructor;return uy(t)&&e instanceof t?t.prototype:e instanceof Fn?py:null}});var yr=b((Bw,Sd)=>{"use strict";var hy=gr();Sd.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:hy(a,e,t),a}});var Gn=b((Vw,Td)=>{"use strict";var fy=De(),my=le(),by=Fe(),gy=Nn(),vd=qn(),Sy=yr(),vy=Ie(),yy=Xe(),jn=vy("iterator"),yd=!1,mt,Un,Hn;[].keys&&(Hn=[].keys(),"next"in Hn?(Un=vd(vd(Hn)),Un!==Object.prototype&&(mt=Un)):yd=!0);var Ty=!by(mt)||fy(function(){var a={};return mt[jn].call(a)!==a});Ty?mt={}:yy&&(mt=gy(mt));my(mt[jn])||Sy(mt,jn,function(){return this});Td.exports={IteratorPrototype:mt,BUGGY_SAFARI_ITERATORS:yd}});var _a=b((_w,Ed)=>{"use strict";var Iy=Ie(),Ey=Iy("toStringTag"),Id={};Id[Ey]="z";Ed.exports=String(Id)==="[object z]"});var ui=b((Nw,xd)=>{"use strict";var xy=_a(),Py=le(),Na=pr(),Ay=Ie(),wy=Ay("toStringTag"),ky=Object,Ry=Na(function(){return arguments}())==="Arguments",Ly=function(a,e){try{return a[e]}catch(t){}};xd.exports=xy?Na:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=Ly(e=ky(a),wy))=="string"?t:Ry?Na(e):(r=Na(e))==="Object"&&Py(e.callee)?"Arguments":r}});var Ad=b((Fw,Pd)=>{"use strict";var $y=_a(),My=ui();Pd.exports=$y?{}.toString:function(){return"[object "+My(this)+"]"}});var li=b((qw,kd)=>{"use strict";var Cy=_a(),Dy=Gt().f,Oy=gr(),By=Ze(),Vy=Ad(),_y=Ie(),wd=_y("toStringTag");kd.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(By(i,wd)||Dy(i,wd,{configurable:!0,value:e}),r&&!Cy&&Oy(i,"toString",Vy))}});var Ld=b((Uw,Rd)=>{"use strict";var Ny=Gn().IteratorPrototype,Fy=Nn(),qy=ii(),Uy=li(),Hy=jt(),jy=function(){return this};Rd.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=Fy(Ny,{next:qy(+!r,t)}),Uy(a,i,!1,!0),Hy[i]=jy,a}});var Md=b((Hw,$d)=>{"use strict";var Gy=Ae(),Yy=ft();$d.exports=function(a,e,t){try{return Gy(Yy(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Dd=b((jw,Cd)=>{"use strict";var Wy=Fe();Cd.exports=function(a){return Wy(a)||a===null}});var Bd=b((Gw,Od)=>{"use strict";var Qy=Dd(),zy=String,Ky=TypeError;Od.exports=function(a){if(Qy(a))return a;throw new Ky("Can't set "+zy(a)+" as a prototype")}});var Yn=b((Yw,Vd)=>{"use strict";var Jy=Md(),Xy=Fe(),Zy=Kr(),eT=Bd();Vd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Jy(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return Zy(i),eT(s),Xy(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Qd=b((Ww,Wd)=>{"use strict";var tT=Ue(),rT=Oe(),Fa=Xe(),Gd=Fc(),iT=le(),aT=Ld(),_d=qn(),Nd=Yn(),sT=li(),nT=gr(),Wn=yr(),oT=Ie(),Fd=jt(),Yd=Gn(),uT=Gd.PROPER,lT=Gd.CONFIGURABLE,qd=Yd.IteratorPrototype,qa=Yd.BUGGY_SAFARI_ITERATORS,ci=oT("iterator"),Ud="keys",di="values",Hd="entries",jd=function(){return this};Wd.exports=function(a,e,t,r,i,s,n){aT(t,e,r);var o=function(T){if(T===i&&p)return p;if(!qa&&T&&T in c)return c[T];switch(T){case Ud:return function(){return new t(this,T)};case di:return function(){return new t(this,T)};case Hd:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[ci]||c["@@iterator"]||i&&c[i],p=!qa&&d||o(i),h=e==="Array"&&c.entries||d,m,g,S;if(h&&(m=_d(h.call(new a)),m!==Object.prototype&&m.next&&(!Fa&&_d(m)!==qd&&(Nd?Nd(m,qd):iT(m[ci])||Wn(m,ci,jd)),sT(m,u,!0,!0),Fa&&(Fd[u]=jd))),uT&&i===di&&d&&d.name!==di&&(!Fa&&lT?nT(c,"name",di):(l=!0,p=function(){return rT(d,this)})),i)if(g={values:o(di),keys:s?p:o(Ud),entries:o(Hd)},n)for(S in g)(qa||l||!(S in c))&&Wn(c,S,g[S]);else tT({target:e,proto:!0,forced:qa||l},g);return(!Fa||n)&&c[ci]!==p&&Wn(c,ci,p,{name:i}),Fd[e]=p,g}});var Kd=b((Qw,zd)=>{"use strict";zd.exports=function(a,e){return{value:a,done:e}}});var zn=b((zw,tp)=>{"use strict";var cT=fr(),Qn=Zs(),Jd=jt(),Zd=wn(),dT=Gt().f,pT=Qd(),Ua=Kd(),hT=Xe(),fT=qe(),ep="Array Iterator",mT=Zd.set,bT=Zd.getterFor(ep);tp.exports=pT(Array,"Array",function(a,e){mT(this,{type:ep,target:cT(a),index:0,kind:e})},function(){var a=bT(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ua(void 0,!0);switch(a.kind){case"keys":return Ua(t,!1);case"values":return Ua(e[t],!1)}return Ua([t,e[t]],!1)},"values");var Xd=Jd.Arguments=Jd.Array;Qn("keys");Qn("values");Qn("entries");if(!hT&&fT&&Xd.name!=="values")try{dT(Xd,"name",{value:"values"})}catch(a){}});var ip=b((Kw,rp)=>{"use strict";var gT=Ie(),ST=jt(),vT=gT("iterator"),yT=Array.prototype;rp.exports=function(a){return a!==void 0&&(ST.Array===a||yT[vT]===a)}});var Kn=b((Jw,sp)=>{"use strict";var TT=ui(),ap=ei(),IT=hr(),ET=jt(),xT=Ie(),PT=xT("iterator");sp.exports=function(a){if(!IT(a))return ap(a,PT)||ap(a,"@@iterator")||ET[TT(a)]}});var op=b((Xw,np)=>{"use strict";var AT=Oe(),wT=ft(),kT=st(),RT=Zr(),LT=Kn(),$T=TypeError;np.exports=function(a,e){var t=arguments.length<2?LT(a):e;if(wT(t))return kT(AT(t,a));throw new $T(RT(a)+" is not iterable")}});var cp=b((Zw,lp)=>{"use strict";var MT=Oe(),up=st(),CT=ei();lp.exports=function(a,e,t){var r,i;up(a);try{if(r=CT(a,"return"),!r){if(e==="throw")throw t;return t}r=MT(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return up(r),t}});var ja=b((ek,fp)=>{"use strict";var DT=ni(),OT=Oe(),BT=st(),VT=Zr(),_T=ip(),NT=Oa(),dp=Xr(),FT=op(),qT=Kn(),pp=cp(),UT=TypeError,Ha=function(a,e){this.stopped=a,this.result=e},hp=Ha.prototype;fp.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=DT(e,r),l,c,d,p,h,m,g,S=function(A){return l&&pp(l,"normal",A),new Ha(!0,A)},T=function(A){return i?(BT(A),o?u(A[0],A[1],S):u(A[0],A[1])):o?u(A,S):u(A)};if(s)l=a.iterator;else if(n)l=a;else{if(c=qT(a),!c)throw new UT(VT(a)+" is not iterable");if(_T(c)){for(d=0,p=NT(a);p>d;d++)if(h=T(a[d]),h&&dp(hp,h))return h;return new Ha(!1)}l=FT(a,c)}for(m=s?a.next:l.next;!(g=OT(m,l)).done;){try{h=T(g.value)}catch(A){pp(l,"throw",A)}if(typeof h=="object"&&h&&dp(hp,h))return h}return new Ha(!1)}});var bp=b((tk,mp)=>{"use strict";var HT=qe(),jT=Gt(),GT=ii();mp.exports=function(a,e,t){HT?jT.f(a,e,GT(0,t)):a[e]=t}});var gp=b(()=>{"use strict";var YT=Ue(),WT=ja(),QT=bp();YT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return WT(e,function(r,i){QT(t,r,i)},{AS_ENTRIES:!0}),t}})});var vp=b((ak,Sp)=>{"use strict";zn();gp();var zT=wa();Sp.exports=zT.Object.fromEntries});var Tp=b((sk,yp)=>{"use strict";yp.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 Ep=b(()=>{"use strict";zn();var KT=Tp(),JT=ce(),XT=li(),Ip=jt();for(Ga in KT)XT(JT[Ga],Ga),Ip[Ga]=Ip.Array;var Ga});var Pp=b((uk,xp)=>{"use strict";var ZT=vp();Ep();xp.exports=ZT});var Jn=b((lk,Ap)=>{"use strict";var eI=Pp();Ap.exports=eI});var wp=b(()=>{"use strict"});var Xn=b((pk,kp)=>{"use strict";var pi=ce(),tI=mr(),rI=pr(),Ya=function(a){return tI.slice(0,a.length)===a};kp.exports=function(){return Ya("Bun/")?"BUN":Ya("Cloudflare-Workers")?"CLOUDFLARE":Ya("Deno/")?"DENO":Ya("Node.js/")?"NODE":pi.Bun&&typeof Bun.version=="string"?"BUN":pi.Deno&&typeof Deno.version=="object"?"DENO":rI(pi.process)==="process"?"NODE":pi.window&&pi.document?"BROWSER":"REST"}()});var Wa=b((hk,Rp)=>{"use strict";var iI=Xn();Rp.exports=iI==="NODE"});var $p=b((fk,Lp)=>{"use strict";var aI=Gt();Lp.exports=function(a,e,t){return aI.f(a,e,t)}});var Dp=b((mk,Cp)=>{"use strict";var sI=ht(),nI=$p(),oI=Ie(),uI=qe(),Mp=oI("species");Cp.exports=function(a){var e=sI(a);uI&&e&&!e[Mp]&&nI(e,Mp,{configurable:!0,get:function(){return this}})}});var Bp=b((bk,Op)=>{"use strict";var lI=Xr(),cI=TypeError;Op.exports=function(a,e){if(lI(e,a))return a;throw new cI("Incorrect invocation")}});var eo=b((gk,Vp)=>{"use strict";var dI=Ae(),pI=le(),Zn=ti(),hI=dI(Function.toString);pI(Zn.inspectSource)||(Zn.inspectSource=function(a){return hI(a)});Vp.exports=Zn.inspectSource});var Hp=b((Sk,Up)=>{"use strict";var fI=Ae(),mI=De(),_p=le(),bI=ui(),gI=ht(),SI=eo(),Np=function(){},Fp=gI("Reflect","construct"),to=/^\s*(?:class|function)\b/,vI=fI(to.exec),yI=!to.test(Np),hi=function(e){if(!_p(e))return!1;try{return Fp(Np,[],e),!0}catch(t){return!1}},qp=function(e){if(!_p(e))return!1;switch(bI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return yI||!!vI(to,SI(e))}catch(t){return!0}};qp.sham=!0;Up.exports=!Fp||mI(function(){var a;return hi(hi.call)||!hi(Object)||!hi(function(){a=!0})||a})?qp:hi});var Gp=b((vk,jp)=>{"use strict";var TI=Hp(),II=Zr(),EI=TypeError;jp.exports=function(a){if(TI(a))return a;throw new EI(II(a)+" is not a constructor")}});var ro=b((yk,Wp)=>{"use strict";var Yp=st(),xI=Gp(),PI=hr(),AI=Ie(),wI=AI("species");Wp.exports=function(a,e){var t=Yp(a).constructor,r;return t===void 0||PI(r=Yp(t)[wI])?e:xI(r)}});var zp=b((Tk,Qp)=>{"use strict";var kI=Ae();Qp.exports=kI([].slice)});var Jp=b((Ik,Kp)=>{"use strict";var RI=TypeError;Kp.exports=function(a,e){if(a<e)throw new RI("Not enough arguments");return a}});var io=b((Ek,Xp)=>{"use strict";var LI=mr();Xp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(LI)});var ho=b((xk,oh)=>{"use strict";var Be=ce(),$I=kn(),MI=ni(),Zp=le(),CI=Ze(),nh=De(),eh=On(),DI=zp(),th=Pa(),OI=Jp(),BI=io(),VI=Wa(),lo=Be.setImmediate,co=Be.clearImmediate,_I=Be.process,ao=Be.Dispatch,NI=Be.Function,rh=Be.MessageChannel,FI=Be.String,so=0,fi={},ih="onreadystatechange",mi,Wt,no,oo;nh(function(){mi=Be.location});var po=function(a){if(CI(fi,a)){var e=fi[a];delete fi[a],e()}},uo=function(a){return function(){po(a)}},ah=function(a){po(a.data)},sh=function(a){Be.postMessage(FI(a),mi.protocol+"//"+mi.host)};(!lo||!co)&&(lo=function(e){OI(arguments.length,1);var t=Zp(e)?e:NI(e),r=DI(arguments,1);return fi[++so]=function(){$I(t,void 0,r)},Wt(so),so},co=function(e){delete fi[e]},VI?Wt=function(a){_I.nextTick(uo(a))}:ao&&ao.now?Wt=function(a){ao.now(uo(a))}:rh&&!BI?(no=new rh,oo=no.port2,no.port1.onmessage=ah,Wt=MI(oo.postMessage,oo)):Be.addEventListener&&Zp(Be.postMessage)&&!Be.importScripts&&mi&&mi.protocol!=="file:"&&!nh(sh)?(Wt=sh,Be.addEventListener("message",ah,!1)):ih in th("script")?Wt=function(a){eh.appendChild(th("script"))[ih]=function(){eh.removeChild(this),po(a)}}:Wt=function(a){setTimeout(uo(a),0)});oh.exports={set:lo,clear:co}});var ch=b((Pk,lh)=>{"use strict";var uh=ce(),qI=qe(),UI=Object.getOwnPropertyDescriptor;lh.exports=function(a){if(!qI)return uh[a];var e=UI(uh,a);return e&&e.value}});var fo=b((Ak,ph)=>{"use strict";var dh=function(){this.head=null,this.tail=null};dh.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};ph.exports=dh});var fh=b((wk,hh)=>{"use strict";var HI=mr();hh.exports=/ipad|iphone|ipod/i.test(HI)&&typeof Pebble!="undefined"});var bh=b((kk,mh)=>{"use strict";var jI=mr();mh.exports=/web0s(?!.*chrome)/i.test(jI)});var Eh=b((Rk,Ih)=>{"use strict";var Ir=ce(),GI=ch(),gh=ni(),mo=ho().set,YI=fo(),WI=io(),QI=fh(),zI=bh(),bo=Wa(),Sh=Ir.MutationObserver||Ir.WebKitMutationObserver,vh=Ir.document,yh=Ir.process,Qa=Ir.Promise,vo=GI("queueMicrotask"),Tr,go,So,za,Th;vo||(bi=new YI,gi=function(){var a,e;for(bo&&(a=yh.domain)&&a.exit();e=bi.get();)try{e()}catch(t){throw bi.head&&Tr(),t}a&&a.enter()},!WI&&!bo&&!zI&&Sh&&vh?(go=!0,So=vh.createTextNode(""),new Sh(gi).observe(So,{characterData:!0}),Tr=function(){So.data=go=!go}):!QI&&Qa&&Qa.resolve?(za=Qa.resolve(void 0),za.constructor=Qa,Th=gh(za.then,za),Tr=function(){Th(gi)}):bo?Tr=function(){yh.nextTick(gi)}:(mo=gh(mo,Ir),Tr=function(){mo(gi)}),vo=function(a){bi.head||Tr(),bi.add(a)});var bi,gi;Ih.exports=vo});var Ph=b((Lk,xh)=>{"use strict";xh.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ka=b(($k,Ah)=>{"use strict";Ah.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Qt=b((Mk,wh)=>{"use strict";var KI=ce();wh.exports=KI.Promise});var Er=b((Ck,$h)=>{"use strict";var JI=ce(),Si=Qt(),XI=le(),ZI=Ln(),eE=eo(),tE=Ie(),kh=Xn(),rE=Xe(),yo=ln(),Rh=Si&&Si.prototype,iE=tE("species"),To=!1,Lh=XI(JI.PromiseRejectionEvent),aE=ZI("Promise",function(){var a=eE(Si),e=a!==String(Si);if(!e&&yo===66||rE&&!(Rh.catch&&Rh.finally))return!0;if(!yo||yo<51||!/native code/.test(a)){var t=new Si(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[iE]=r,To=t.then(function(){})instanceof r,!To)return!0}return!e&&(kh==="BROWSER"||kh==="DENO")&&!Lh});$h.exports={CONSTRUCTOR:aE,REJECTION_EVENT:Lh,SUBCLASSING:To}});var xr=b((Dk,Ch)=>{"use strict";var Mh=ft(),sE=TypeError,nE=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new sE("Bad Promise constructor");e=r,t=i}),this.resolve=Mh(e),this.reject=Mh(t)};Ch.exports.f=function(a){return new nE(a)}});var Xh=b(()=>{"use strict";var oE=Ue(),uE=Xe(),es=Wa(),$t=ce(),kr=Oe(),Dh=yr(),Oh=Yn(),lE=li(),cE=Dp(),dE=ft(),Za=le(),pE=Fe(),hE=Bp(),fE=ro(),Fh=ho().set,Ao=Eh(),mE=Ph(),bE=Ka(),gE=fo(),qh=wn(),ts=Qt(),wo=Er(),Uh=xr(),rs="Promise",Hh=wo.CONSTRUCTOR,SE=wo.REJECTION_EVENT,vE=wo.SUBCLASSING,Io=qh.getterFor(rs),yE=qh.set,Pr=ts&&ts.prototype,zt=ts,Ja=Pr,jh=$t.TypeError,Eo=$t.document,ko=$t.process,xo=Uh.f,TE=xo,IE=!!(Eo&&Eo.createEvent&&$t.dispatchEvent),Gh="unhandledrejection",EE="rejectionhandled",Bh=0,Yh=1,xE=2,Ro=1,Wh=2,Xa,Vh,PE,_h,Qh=function(a){var e;return pE(a)&&Za(e=a.then)?e:!1},zh=function(a,e){var t=e.value,r=e.state===Yh,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Wh&&wE(e),e.rejection=Ro),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new jh("Promise-chain cycle")):(l=Qh(u))?kr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Kh=function(a,e){a.notified||(a.notified=!0,Ao(function(){for(var t=a.reactions,r;r=t.get();)zh(r,a);a.notified=!1,e&&!a.rejection&&AE(a)}))},Jh=function(a,e,t){var r,i;IE?(r=Eo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),$t.dispatchEvent(r)):r={promise:e,reason:t},!SE&&(i=$t["on"+a])?i(r):a===Gh&&mE("Unhandled promise rejection",t)},AE=function(a){kr(Fh,$t,function(){var e=a.facade,t=a.value,r=Nh(a),i;if(r&&(i=bE(function(){es?ko.emit("unhandledRejection",t,e):Jh(Gh,e,t)}),a.rejection=es||Nh(a)?Wh:Ro,i.error))throw i.value})},Nh=function(a){return a.rejection!==Ro&&!a.parent},wE=function(a){kr(Fh,$t,function(){var e=a.facade;es?ko.emit("rejectionHandled",e):Jh(EE,e,a.value)})},Ar=function(a,e,t){return function(r){a(e,r,t)}},wr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=xE,Kh(a,!0))},Po=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new jh("Promise can't be resolved itself");var r=Qh(e);r?Ao(function(){var i={done:!1};try{kr(r,e,Ar(Po,i,a),Ar(wr,i,a))}catch(s){wr(i,s,a)}}):(a.value=e,a.state=Yh,Kh(a,!1))}catch(i){wr({done:!1},i,a)}}};if(Hh&&(zt=function(e){hE(this,Ja),dE(e),kr(Xa,this);var t=Io(this);try{e(Ar(Po,t),Ar(wr,t))}catch(r){wr(t,r)}},Ja=zt.prototype,Xa=function(e){yE(this,{type:rs,done:!1,notified:!1,parent:!1,reactions:new gE,rejection:!1,state:Bh,value:void 0})},Xa.prototype=Dh(Ja,"then",function(e,t){var r=Io(this),i=xo(fE(this,zt));return r.parent=!0,i.ok=Za(e)?e:!0,i.fail=Za(t)&&t,i.domain=es?ko.domain:void 0,r.state===Bh?r.reactions.add(i):Ao(function(){zh(i,r)}),i.promise}),Vh=function(){var a=new Xa,e=Io(a);this.promise=a,this.resolve=Ar(Po,e),this.reject=Ar(wr,e)},Uh.f=xo=function(a){return a===zt||a===PE?new Vh(a):TE(a)},!uE&&Za(ts)&&Pr!==Object.prototype)){_h=Pr.then,vE||Dh(Pr,"then",function(e,t){var r=this;return new zt(function(i,s){kr(_h,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Pr.constructor}catch(a){}Oh&&Oh(Pr,Ja)}oE({global:!0,constructor:!0,wrap:!0,forced:Hh},{Promise:zt});lE(zt,rs,!1,!0);cE(rs)});var af=b((Vk,rf)=>{"use strict";var kE=Ie(),ef=kE("iterator"),tf=!1;try{Zh=0,Lo={next:function(){return{done:!!Zh++}},return:function(){tf=!0}},Lo[ef]=function(){return this},Array.from(Lo,function(){throw 2})}catch(a){}var Zh,Lo;rf.exports=function(a,e){try{if(!e&&!tf)return!1}catch(i){return!1}var t=!1;try{var r={};r[ef]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var $o=b((_k,sf)=>{"use strict";var RE=Qt(),LE=af(),$E=Er().CONSTRUCTOR;sf.exports=$E||!LE(function(a){RE.all(a).then(void 0,function(){})})});var nf=b(()=>{"use strict";var ME=Ue(),CE=Oe(),DE=ft(),OE=xr(),BE=Ka(),VE=ja(),_E=$o();ME({target:"Promise",stat:!0,forced:_E},{all:function(e){var t=this,r=OE.f(t),i=r.resolve,s=r.reject,n=BE(function(){var o=DE(t.resolve),u=[],l=0,c=1;VE(e,function(d){var p=l++,h=!1;c++,CE(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var uf=b(()=>{"use strict";var NE=Ue(),FE=Xe(),qE=Er().CONSTRUCTOR,Co=Qt(),UE=ht(),HE=le(),jE=yr(),of=Co&&Co.prototype;NE({target:"Promise",proto:!0,forced:qE,real:!0},{catch:function(a){return this.then(void 0,a)}});!FE&&HE(Co)&&(Mo=UE("Promise").prototype.catch,of.catch!==Mo&&jE(of,"catch",Mo,{unsafe:!0}));var Mo});var lf=b(()=>{"use strict";var GE=Ue(),YE=Oe(),WE=ft(),QE=xr(),zE=Ka(),KE=ja(),JE=$o();GE({target:"Promise",stat:!0,forced:JE},{race:function(e){var t=this,r=QE.f(t),i=r.reject,s=zE(function(){var n=WE(t.resolve);KE(e,function(o){YE(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var cf=b(()=>{"use strict";var XE=Ue(),ZE=xr(),ex=Er().CONSTRUCTOR;XE({target:"Promise",stat:!0,forced:ex},{reject:function(e){var t=ZE.f(this),r=t.reject;return r(e),t.promise}})});var Do=b((Wk,df)=>{"use strict";var tx=st(),rx=Fe(),ix=xr();df.exports=function(a,e){if(tx(a),rx(e)&&e.constructor===a)return e;var t=ix.f(a),r=t.resolve;return r(e),t.promise}});var ff=b(()=>{"use strict";var ax=Ue(),sx=ht(),pf=Xe(),nx=Qt(),hf=Er().CONSTRUCTOR,ox=Do(),ux=sx("Promise"),lx=pf&&!hf;ax({target:"Promise",stat:!0,forced:pf||hf},{resolve:function(e){return ox(lx&&this===ux?nx:this,e)}})});var mf=b(()=>{"use strict";Xh();nf();uf();lf();cf();ff()});var vf=b(()=>{"use strict";var cx=Ue(),dx=Xe(),is=Qt(),px=De(),gf=ht(),Sf=le(),hx=ro(),bf=Do(),fx=yr(),Bo=is&&is.prototype,mx=!!is&&px(function(){Bo.finally.call({then:function(){}},function(){})});cx({target:"Promise",proto:!0,real:!0,forced:mx},{finally:function(a){var e=hx(this,gf("Promise")),t=Sf(a);return this.then(t?function(r){return bf(e,a()).then(function(){return r})}:a,t?function(r){return bf(e,a()).then(function(){throw r})}:a)}});!dx&&Sf(is)&&(Oo=gf("Promise").prototype.finally,Bo.finally!==Oo&&fx(Bo,"finally",Oo,{unsafe:!0}));var Oo});var as=b((eR,yf)=>{"use strict";var bx=ht();yf.exports=bx});var If=b((tR,Tf)=>{"use strict";wp();mf();vf();var gx=as();Tf.exports=gx("Promise","finally")});var xf=b((rR,Ef)=>{"use strict";var Sx=If();Ef.exports=Sx});var ss=b((iR,Pf)=>{"use strict";var vx=xf();Pf.exports=vx});var Of=b(()=>{"use strict";var wx=Ue(),kx=ri(),Rx=Oa(),Lx=Da(),$x=Zs();wx({target:"Array",proto:!0},{at:function(e){var t=kx(this),r=Rx(t),i=Lx(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});$x("at")});var Vf=b((tL,Bf)=>{"use strict";Of();var Mx=as();Bf.exports=Mx("Array","at")});var Nf=b((rL,_f)=>{"use strict";var Cx=Vf();_f.exports=Cx});var yi=b((iL,Ff)=>{"use strict";var Dx=Nf();Ff.exports=Dx});var $m=b(()=>{"use strict"});var Mm=b(()=>{"use strict"});var Dm=b((XC,Cm)=>{"use strict";var fP=Fe(),mP=pr(),bP=Ie(),gP=bP("match");Cm.exports=function(a){var e;return fP(a)&&((e=a[gP])!==void 0?!!e:mP(a)==="RegExp")}});var Bm=b((ZC,Om)=>{"use strict";var SP=ui(),vP=String;Om.exports=function(a){if(SP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return vP(a)}});var _m=b((eD,Vm)=>{"use strict";var yP=st();Vm.exports=function(){var a=yP(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var qm=b((tD,Fm)=>{"use strict";var TP=Oe(),IP=Ze(),EP=Xr(),xP=_m(),Nm=RegExp.prototype;Fm.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Nm)&&!IP(a,"flags")&&EP(Nm,a)?TP(xP,a):e}});var Hm=b((rD,Um)=>{"use strict";var su=Ae(),PP=ri(),AP=Math.floor,iu=su("".charAt),wP=su("".replace),au=su("".slice),kP=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,RP=/\$([$&'`]|\d{1,2})/g;Um.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=RP;return i!==void 0&&(i=PP(i),u=kP),wP(s,u,function(l,c){var d;switch(iu(c,0)){case"$":return"$";case"&":return a;case"`":return au(e,0,t);case"'":return au(e,n);case"<":d=i[au(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=AP(p/10);return h===0?l:h<=o?r[h-1]===void 0?iu(c,1):r[h-1]+iu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var Ym=b(()=>{"use strict";var LP=Ue(),$P=Oe(),ou=Ae(),jm=Kr(),MP=le(),CP=hr(),DP=Dm(),Vr=Bm(),OP=ei(),BP=qm(),VP=Hm(),_P=Ie(),NP=Xe(),FP=_P("replace"),qP=TypeError,nu=ou("".indexOf),UP=ou("".replace),Gm=ou("".slice),HP=Math.max;LP({target:"String",proto:!0},{replaceAll:function(e,t){var r=jm(this),i,s,n,o,u,l,c,d,p,h,m=0,g="";if(!CP(e)){if(i=DP(e),i&&(s=Vr(jm(BP(e))),!~nu(s,"g")))throw new qP("`.replaceAll` does not allow non-global regexes");if(n=OP(e,FP),n)return $P(n,e,r,t);if(NP&&i)return UP(Vr(r),e,t)}for(o=Vr(r),u=Vr(e),l=MP(t),l||(t=Vr(t)),c=u.length,d=HP(1,c),p=nu(o,u);p!==-1;)h=l?Vr(t(u,p,o)):VP(u,o,p,[],void 0,t),g+=Gm(o,m,p)+h,m=p+c,p=p+d>o.length?-1:nu(o,u,p+d);return m<o.length&&(g+=Gm(o,m)),g}})});var Qm=b((sD,Wm)=>{"use strict";$m();Mm();Ym();var jP=as();Wm.exports=jP("String","replaceAll")});var Km=b((nD,zm)=>{"use strict";var GP=Qm();zm.exports=GP});var Xm=b((oD,Jm)=>{"use strict";var YP=Km();Jm.exports=YP});var oA={};ug(oA,{ChromecastState:()=>Qr,HttpConnectionType:()=>Ia,Observable:()=>ct.Observable,PlaybackState:()=>Te,Player:()=>ba,SDK_VERSION:()=>nA,Subject:()=>ct.Subject,Subscription:()=>ct.Subscription,Surface:()=>Ea,VERSION:()=>Ks,ValueSubject:()=>ct.ValueSubject,VideoFormat:()=>pt,VideoQuality:()=>ct.VideoQuality});module.exports=lg(oA);var Ks="2.0.108-dev.43b53ca1.0";var Te=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Te||{}),pt=(I=>(I.MPEG="MPEG",I.DASH="DASH",I.DASH_SEP="DASH_SEP",I.DASH_SEP_VK="DASH_SEP",I.DASH_WEBM="DASH_WEBM",I.DASH_WEBM_AV1="DASH_WEBM_AV1",I.DASH_STREAMS="DASH_STREAMS",I.DASH_WEBM_VK="DASH_WEBM",I.DASH_ONDEMAND="DASH_ONDEMAND",I.DASH_ONDEMAND_VK="DASH_ONDEMAND",I.DASH_LIVE="DASH_LIVE",I.DASH_LIVE_CMAF="DASH_LIVE_CMAF",I.DASH_LIVE_WEBM="DASH_LIVE_WEBM",I.HLS="HLS",I.HLS_ONDEMAND="HLS_ONDEMAND",I.HLS_JS="HLS",I.HLS_LIVE="HLS_LIVE",I.HLS_LIVE_CMAF="HLS_LIVE_CMAF",I.WEB_RTC_LIVE="WEB_RTC_LIVE",I))(pt||{});var Qr=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Qr||{}),Ia=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ia||{});var Ea=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ea||{});var U=require("@vkontakte/videoplayer-shared");var Ku=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var xa=class{constructor(e){this.connection$=new U.ValueSubject(void 0);this.castState$=new U.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new U.Subject;this.realCastState$=new U.ValueSubject("NOT_AVAILABLE");this.subscription=new U.Subscription;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,U.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Ku("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:U.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,U.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,U.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,U.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,U.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,U.assertNever)(i.sessionState)}})).add((0,U.merge)((0,U.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,U.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,U.map)(i=>i.castState)),(0,U.observableFrom)([r.getCastState()])).pipe((0,U.filterChanged)(),(0,U.map)(dg),(0,U.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o;let s=i==="CONNECTED",n=(0,U.isNonNullable)(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();(0,U.assertNonNullable)(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;((0,U.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,U.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:U.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},dg=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,U.assertNever)(a)}};var Tb=Ke(Jn(),1);var Rf=Ke(ss(),1);var Vo=require("@vkontakte/videoplayer-shared");var ye=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,Vo.assertNever)(t)}return a},_o=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,Vo.assertNever)(e)}};var w=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var nt=require("@vkontakte/videoplayer-shared"),j=class{constructor(e){this.transitionStarted$=new nt.Subject;this.transitionEnded$=new nt.Subject;this.transitionUpdated$=new nt.Subject;this.forceChanged$=new nt.Subject;this.stateChangeStarted$=(0,nt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,nt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,nt.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Af=require("@vkontakte/videoplayer-shared"),wf=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Af.assertNever)(a)}};var k=require("@vkontakte/videoplayer-shared");var yx=5,Tx=5,Ix=500,kf=7e3,vi=class{constructor(e){this.subscription=new k.Subscription;this.loadMediaTimeoutSubscription=new k.Subscription;this.videoState=new j("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,k.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,k.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,k.assertNever)(e)}break}default:(0,k.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(wf(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 k.Subscription;this.subscription.add(e),this.subscription.add((0,k.merge)(this.videoState.stateChangeStarted$.pipe((0,k.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,k.map)(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new k.Subject;e.add(i.pipe((0,k.debounce)(Ix)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>yx)&&i.next(o),s=o})),e.add((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.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<Tx&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,k.assertNever)(n)}}),t((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,k.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,k.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,k.observableFrom)(["init"])).pipe((0,k.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&w(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];(0,k.assertNonNullable)(c);let d=(0,k.getHighestQuality)(Object.keys(c));(0,k.assertNonNullable)(d);let p=c[d];(0,k.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,k.assertNonNullable)(c),r=c.url,i="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 c=t[e];(0,k.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,k.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,k.assertNonNullable)(c),r=ye(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:k.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,k.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,k.isNonNullable)(o)&&(n.metadata.title=o),(0,k.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add((0,k.timeout)(kf).subscribe(()=>s(`timeout(${kf})`)))});(0,Rf.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:k.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Uo=require("@vkontakte/videoplayer-shared");var Lf=require("@vkontakte/videoplayer-shared"),$f=a=>{try{a.pause(),a.playbackRate=0,(0,Lf.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var ns=require("@vkontakte/videoplayer-shared"),No=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)}},Fo=window.WeakMap?new WeakMap:new No,qo=window.WeakMap?new WeakMap:new Map,Ex=(a,e=20)=>{let t=0;return(0,ns.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},we=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,Uo.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),Fo.set(t,r);let i=new ns.Subscription;return i.add(Ex(t,e)),qo.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ke=a=>{let e=qo.get(a);e==null||e.unsubscribe(),qo.delete(a);let t=Fo.get(a);Fo.delete(a),t?(0,Uo.clearVideoElement)(a):$f(a)};var R=require("@vkontakte/videoplayer-shared");var Mt=require("@vkontakte/videoplayer-shared"),os=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Mt.isNullable)(i),l=new Mt.Subscription;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>os(e,()=>a.loop,r=>{(0,Mt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Re=(a,e,t,r)=>os(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Mt.isNonNullable)(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),He=(a,e,t,r)=>os(e,()=>a.playbackRate,i=>{(0,Mt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ct=os;var xx=a=>["__",a.language,a.label].join("|"),Px=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Ho=class a{constructor(){this.available$=new R.Subject;this.current$=new R.ValueSubject(void 0);this.error$=new R.Subject;this.subscription=new R.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:R.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ct(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,R.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,R.isNonNullable)(s)&&(0,R.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,R.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ct(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,R.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,R.isNonNullable)(s)&&(0,R.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,R.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ct(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:i})),this.subscription.add(Ct(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,R.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,R.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,R.merge)((0,R.fromEvent)(e,"addtrack"),(0,R.fromEvent)(e,"removetrack"),(0,R.observableFrom)(["init"])).pipe((0,R.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,R.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,R.merge)((0,R.fromEvent)(e,"change"),(0,R.observableFrom)(["init"])).pipe((0,R.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,R.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,R.filterChanged)()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add((0,R.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,R.fromEvent)(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;(0,R.isNonNullable)(t.align)&&(i.align=t.align),(0,R.isNonNullable)(t.position)&&(i.position=t.position),(0,R.isNonNullable)(t.size)&&(i.size=t.size),(0,R.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,R.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:xx(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,R.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,R.isNullable)(e)||!Px(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,R.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,R.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},je=Ho;var gt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Mf=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},jo=a=>{let e=Mf(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Cf=a=>{let e=Mf(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var $=require("@vkontakte/videoplayer-shared");var Ax=3,Df=(a,e,t=Ax)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Le=a=>{let e=I=>(0,$.fromEvent)(a,I).pipe((0,$.mapTo)(void 0)),r=(0,$.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>(0,$.fromEvent)(a,I))).pipe((0,$.map)(I=>I.type==="ended"?a.readyState<2:a.readyState<3),(0,$.filterChanged)()),i=(0,$.merge)((0,$.fromEvent)(a,"progress"),(0,$.fromEvent)(a,"timeupdate")).pipe((0,$.map)(()=>Df(a.buffered,a.currentTime))),s=$.clientChecker.isSafari?(0,$.combine)({play:e("play").pipe((0,$.once)()),playing:e("playing")}).pipe((0,$.mapTo)(void 0)):e("playing"),n=(0,$.fromEvent)(a,"volumechange").pipe((0,$.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,$.fromEvent)(a,"ratechange").pipe((0,$.map)(()=>a.playbackRate)),u=(0,$.fromEvent)(a,"error").pipe((0,$.filter)(()=>!!(a.error||a.played.length)),(0,$.map)(()=>{var E;let I=a.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:$.ErrorCategory.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(()=>a.currentTime)),c=new $.Subject,d=.3,p;l.subscribe(I=>{a.loop&&(0,$.isNonNullable)(p)&&(0,$.isNonNullable)(I)&&p>=a.duration-d&&I<=d&&c.next(p),p=I});let h=e("pause").pipe((0,$.filter)(()=>!a.error&&p!==a.duration)),m=(0,$.fromEvent)(a,"enterpictureinpicture"),g=(0,$.fromEvent)(a,"leavepictureinpicture"),S=new $.ValueSubject(Cf(a));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let T=new $.ValueSubject(jo(a));return(0,$.fromEvent)(a,"fullscreenchange").pipe((0,$.map)(()=>jo(a))).subscribe(T),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,$.fromEvent)(a,"durationchange").pipe((0,$.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:T}};var St=require("@vkontakte/videoplayer-shared"),Dt=a=>{switch(a){case"mobile":return St.VideoQuality.Q_144P;case"lowest":return St.VideoQuality.Q_240P;case"low":return St.VideoQuality.Q_360P;case"sd":case"medium":return St.VideoQuality.Q_480P;case"hd":case"high":return St.VideoQuality.Q_720P;case"fullhd":case"full":return St.VideoQuality.Q_1080P;case"quadhd":case"quad":return St.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return St.VideoQuality.Q_2160P}};var Kt=Ke(yi(),1),O=require("@vkontakte/videoplayer-shared");var Go=!1,vt={},qf=a=>{Go=a},Uf=()=>{vt={}},Hf=a=>{a(vt)},Ti=(a,e)=>{var t;Go&&(vt.meta=(t=vt.meta)!=null?t:{},vt.meta[a]=e)},Ee=class{constructor(e){this.name=e}next(e){var r,i;if(!Go)return;vt.series=(r=vt.series)!=null?r:{};let t=(i=vt.series[this.name])!=null?i:[];t.push([Date.now(),e]),vt.series[this.name]=t}};var Ox=new Ee("best_bitrate"),Gf=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Yo=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ii=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,O.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Yf='Assertion "ABR Tracks is empty array" failed',us=(a,e,t,r)=>{var u;let i=[...e].sort(Yo(1)),s=[...t].sort(Yo(1)),n=s.filter(l=>(0,O.isNonNullable)(l.bitrate)&&(0,O.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Kt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Kt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Kt.default)(n,-1):(0,Kt.default)(s,0)},jf=a=>"quality"in a,Wf=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&(0,O.now)()-r.history[t.id]<=a.trackCooldown&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!i&&r.recordSelection(t),i&&(r!=null&&r.last)){let s=r.last;r==null||r.recordSwitch(s);let n=jf(s)?"video":"audio",o=jf(s)?s.quality:s.bitrate;return e({message:`
7
- [last ${n} selected] ${o}
8
- `}),s}return r==null||r.recordSwitch(t),t},Ot=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var W,Z,q,M,ee;(0,O.assertNotEmptyArray)(a,Yf);let p=r.usePixelRatio&&(W=window.devicePixelRatio)!=null?W:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},m=h&&(0,O.videoSizeToQuality)(h),g=r.considerPlaybackRate&&(0,O.isNonNullable)(o)?o:1,S=a.filter(V=>!(0,O.isInvariantQuality)(V.quality)).sort((V,pe)=>(0,O.isHigher)(V.quality,pe.quality)?-1:1),T=(Z=(0,Kt.default)(S,-1))==null?void 0:Z.quality,A=(q=(0,Kt.default)(S,0))==null?void 0:q.quality,I=(0,O.isNullable)(i)||(0,O.isNonNullable)(i.min)&&(0,O.isNonNullable)(i.max)&&(0,O.isLower)(i.max,i.min)||(0,O.isNonNullable)(i.min)&&A&&(0,O.isHigher)(i.min,A)||(0,O.isNonNullable)(i.max)&&T&&(0,O.isLower)(i.max,T),E=g*Gf(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),x={},Y=S.filter(V=>(m?(0,O.isLower)(V.quality,m):!0)?((0,O.isNonNullable)(t)&&isFinite(t)&&(0,O.isNonNullable)(V.bitrate)?t-s>=V.bitrate*E:!0)?r.lazyQualitySwitch&&(0,O.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,O.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,O.isHigher)(V.quality,u.quality)?(x[V.quality]="Buffer",!1):!!c&&(0,O.isHigherOrEqual)(V.quality,c)?(x[V.quality]="DroppedFramesLimit",!1):I||((0,O.isNullable)(i.max)||(0,O.isLowerOrEqual)(V.quality,i.max))&&((0,O.isNullable)(i.min)||(0,O.isHigherOrEqual)(V.quality,i.min))?!0:(x[V.quality]="FitsQualityLimits",!1):(x[V.quality]="FitsThroughput",!1):(x[V.quality]="FitsContainer",!1))[0];Y&&Y.bitrate&&Ox.next(Y.bitrate);let ie=(M=Y!=null?Y:S[Math.ceil((S.length-1)/2)])!=null?M:a[0];return ie.quality!==((ee=l==null?void 0:l.last)==null?void 0:ee.quality)&&d({message:`
9
- [VIDEO TRACKS ABR]
10
- [available video tracks]
11
- ${a.map(V=>`{ id: ${V.id}, quality: ${V.quality}, bitrate: ${V.bitrate} }`).join(`
6
+ "use strict";var Wb=Object.create;var Yr=Object.defineProperty,Qb=Object.defineProperties,zb=Object.getOwnPropertyDescriptor,Kb=Object.getOwnPropertyDescriptors,Jb=Object.getOwnPropertyNames,ju=Object.getOwnPropertySymbols,Xb=Object.getPrototypeOf,Yu=Object.prototype.hasOwnProperty,Zb=Object.prototype.propertyIsEnumerable;var eg=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var it=Math.pow,Gu=(a,e,t)=>e in a?Yr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,V=(a,e)=>{for(var t in e||(e={}))Yu.call(e,t)&&Gu(a,t,e[t]);if(ju)for(var t of ju(e))Zb.call(e,t)&&Gu(a,t,e[t]);return a},Z=(a,e)=>Qb(a,Kb(e));var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),tg=(a,e)=>{for(var t in e)Yr(a,t,{get:e[t],enumerable:!0})},Wu=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jb(e))!Yu.call(a,i)&&i!==t&&Yr(a,i,{get:()=>e[i],enumerable:!(r=zb(e,i))||r.enumerable});return a};var ze=(a,e,t)=>(t=a!=null?Wb(Xb(a)):{},Wu(e||!a||!a.__esModule?Yr(t,"default",{value:a,enumerable:!0}):t,a)),rg=a=>Wu(Yr({},"__esModule",{value:!0}),a);var D=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),ig=function(a,e){this[0]=a,this[1]=e},be=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof ig,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[eg("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var De=b((gw,zu)=>{"use strict";zu.exports=function(a){try{return!!a()}catch(e){return!0}}});var Qr=b((Sw,Ku)=>{"use strict";var sg=De();Ku.exports=!sg(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Pe=b((vw,Zu)=>{"use strict";var Ju=Qr(),Xu=Function.prototype,zs=Xu.call,ng=Ju&&Xu.bind.bind(zs,zs);Zu.exports=Ju?ng:function(a){return function(){return zs.apply(a,arguments)}}});var dr=b((yw,tl)=>{"use strict";var el=Pe(),og=el({}.toString),ug=el("".slice);tl.exports=function(a){return ug(og(a),8,-1)}});var il=b((Tw,rl)=>{"use strict";var lg=Pe(),cg=De(),dg=dr(),Ks=Object,pg=lg("".split);rl.exports=cg(function(){return!Ks("z").propertyIsEnumerable(0)})?function(a){return dg(a)==="String"?pg(a,""):Ks(a)}:Ks});var pr=b((Iw,al)=>{"use strict";al.exports=function(a){return a==null}});var zr=b((Ew,sl)=>{"use strict";var hg=pr(),fg=TypeError;sl.exports=function(a){if(hg(a))throw new fg("Can't call method on "+a);return a}});var hr=b((xw,nl)=>{"use strict";var mg=il(),bg=zr();nl.exports=function(a){return mg(bg(a))}});var Js=b((Pw,ol)=>{"use strict";ol.exports=function(){}});var Ut=b((ww,ul)=>{"use strict";ul.exports={}});var de=b((Xs,ll)=>{"use strict";var Kr=function(a){return a&&a.Math===Math&&a};ll.exports=Kr(typeof globalThis=="object"&&globalThis)||Kr(typeof window=="object"&&window)||Kr(typeof self=="object"&&self)||Kr(typeof global=="object"&&global)||Kr(typeof Xs=="object"&&Xs)||function(){return this}()||Function("return this")()});var ce=b((Aw,cl)=>{"use strict";var Zs=typeof document=="object"&&document.all;cl.exports=typeof Zs=="undefined"&&Zs!==void 0?function(a){return typeof a=="function"||a===Zs}:function(a){return typeof a=="function"}});var hl=b((kw,pl)=>{"use strict";var gg=de(),Sg=ce(),dl=gg.WeakMap;pl.exports=Sg(dl)&&/native code/.test(String(dl))});var Fe=b((Rw,fl)=>{"use strict";var vg=ce();fl.exports=function(a){return typeof a=="object"?a!==null:vg(a)}});var qe=b((Lw,ml)=>{"use strict";var yg=De();ml.exports=!yg(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ea=b(($w,gl)=>{"use strict";var Tg=de(),bl=Fe(),en=Tg.document,Ig=bl(en)&&bl(en.createElement);gl.exports=function(a){return Ig?en.createElement(a):{}}});var tn=b((Mw,Sl)=>{"use strict";var Eg=qe(),xg=De(),Pg=Ea();Sl.exports=!Eg&&!xg(function(){return Object.defineProperty(Pg("div"),"a",{get:function(){return 7}}).a!==7})});var rn=b((Cw,vl)=>{"use strict";var wg=qe(),Ag=De();vl.exports=wg&&Ag(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var at=b((Dw,yl)=>{"use strict";var kg=Fe(),Rg=String,Lg=TypeError;yl.exports=function(a){if(kg(a))return a;throw new Lg(Rg(a)+" is not an object")}});var Oe=b((Ow,Tl)=>{"use strict";var $g=Qr(),xa=Function.prototype.call;Tl.exports=$g?xa.bind(xa):function(){return xa.apply(xa,arguments)}});var Pa=b((Bw,Il)=>{"use strict";Il.exports={}});var dt=b((Vw,xl)=>{"use strict";var an=Pa(),sn=de(),Mg=ce(),El=function(a){return Mg(a)?a:void 0};xl.exports=function(a,e){return arguments.length<2?El(an[a])||El(sn[a]):an[a]&&an[a][e]||sn[a]&&sn[a][e]}});var Jr=b((_w,Pl)=>{"use strict";var Cg=Pe();Pl.exports=Cg({}.isPrototypeOf)});var fr=b((Nw,kl)=>{"use strict";var Dg=de(),wl=Dg.navigator,Al=wl&&wl.userAgent;kl.exports=Al?String(Al):""});var on=b((Fw,Dl)=>{"use strict";var Cl=de(),nn=fr(),Rl=Cl.process,Ll=Cl.Deno,$l=Rl&&Rl.versions||Ll&&Ll.version,Ml=$l&&$l.v8,Ke,wa;Ml&&(Ke=Ml.split("."),wa=Ke[0]>0&&Ke[0]<4?1:+(Ke[0]+Ke[1]));!wa&&nn&&(Ke=nn.match(/Edge\/(\d+)/),(!Ke||Ke[1]>=74)&&(Ke=nn.match(/Chrome\/(\d+)/),Ke&&(wa=+Ke[1])));Dl.exports=wa});var un=b((qw,Bl)=>{"use strict";var Ol=on(),Og=De(),Bg=de(),Vg=Bg.String;Bl.exports=!!Object.getOwnPropertySymbols&&!Og(function(){var a=Symbol("symbol detection");return!Vg(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Ol&&Ol<41})});var ln=b((Uw,Vl)=>{"use strict";var _g=un();Vl.exports=_g&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var cn=b((Hw,_l)=>{"use strict";var Ng=dt(),Fg=ce(),qg=Jr(),Ug=ln(),Hg=Object;_l.exports=Ug?function(a){return typeof a=="symbol"}:function(a){var e=Ng("Symbol");return Fg(e)&&qg(e.prototype,Hg(a))}});var Xr=b((jw,Nl)=>{"use strict";var jg=String;Nl.exports=function(a){try{return jg(a)}catch(e){return"Object"}}});var pt=b((Gw,Fl)=>{"use strict";var Gg=ce(),Yg=Xr(),Wg=TypeError;Fl.exports=function(a){if(Gg(a))return a;throw new Wg(Yg(a)+" is not a function")}});var Zr=b((Yw,ql)=>{"use strict";var Qg=pt(),zg=pr();ql.exports=function(a,e){var t=a[e];return zg(t)?void 0:Qg(t)}});var Hl=b((Ww,Ul)=>{"use strict";var dn=Oe(),pn=ce(),hn=Fe(),Kg=TypeError;Ul.exports=function(a,e){var t,r;if(e==="string"&&pn(t=a.toString)&&!hn(r=dn(t,a))||pn(t=a.valueOf)&&!hn(r=dn(t,a))||e!=="string"&&pn(t=a.toString)&&!hn(r=dn(t,a)))return r;throw new Kg("Can't convert object to primitive value")}});var Je=b((Qw,jl)=>{"use strict";jl.exports=!0});var Wl=b((zw,Yl)=>{"use strict";var Gl=de(),Jg=Object.defineProperty;Yl.exports=function(a,e){try{Jg(Gl,a,{value:e,configurable:!0,writable:!0})}catch(t){Gl[a]=e}return e}});var ei=b((Kw,Kl)=>{"use strict";var Xg=Je(),Zg=de(),eS=Wl(),Ql="__core-js_shared__",zl=Kl.exports=Zg[Ql]||eS(Ql,{});(zl.versions||(zl.versions=[])).push({version:"3.38.0",mode:Xg?"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 fn=b((Jw,Xl)=>{"use strict";var Jl=ei();Xl.exports=function(a,e){return Jl[a]||(Jl[a]=e||{})}});var ti=b((Xw,Zl)=>{"use strict";var tS=zr(),rS=Object;Zl.exports=function(a){return rS(tS(a))}});var Xe=b((Zw,ec)=>{"use strict";var iS=Pe(),aS=ti(),sS=iS({}.hasOwnProperty);ec.exports=Object.hasOwn||function(e,t){return sS(aS(e),t)}});var mn=b((eA,tc)=>{"use strict";var nS=Pe(),oS=0,uS=Math.random(),lS=nS(1 .toString);tc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+lS(++oS+uS,36)}});var Te=b((tA,ic)=>{"use strict";var cS=de(),dS=fn(),rc=Xe(),pS=mn(),hS=un(),fS=ln(),mr=cS.Symbol,bn=dS("wks"),mS=fS?mr.for||mr:mr&&mr.withoutSetter||pS;ic.exports=function(a){return rc(bn,a)||(bn[a]=hS&&rc(mr,a)?mr[a]:mS("Symbol."+a)),bn[a]}});var oc=b((rA,nc)=>{"use strict";var bS=Oe(),ac=Fe(),sc=cn(),gS=Zr(),SS=Hl(),vS=Te(),yS=TypeError,TS=vS("toPrimitive");nc.exports=function(a,e){if(!ac(a)||sc(a))return a;var t=gS(a,TS),r;if(t){if(e===void 0&&(e="default"),r=bS(t,a,e),!ac(r)||sc(r))return r;throw new yS("Can't convert object to primitive value")}return e===void 0&&(e="number"),SS(a,e)}});var gn=b((iA,uc)=>{"use strict";var IS=oc(),ES=cn();uc.exports=function(a){var e=IS(a,"string");return ES(e)?e:e+""}});var Ht=b(cc=>{"use strict";var xS=qe(),PS=tn(),wS=rn(),Aa=at(),lc=gn(),AS=TypeError,Sn=Object.defineProperty,kS=Object.getOwnPropertyDescriptor,vn="enumerable",yn="configurable",Tn="writable";cc.f=xS?wS?function(e,t,r){if(Aa(e),t=lc(t),Aa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Tn in r&&!r[Tn]){var i=kS(e,t);i&&i[Tn]&&(e[t]=r.value,r={configurable:yn in r?r[yn]:i[yn],enumerable:vn in r?r[vn]:i[vn],writable:!1})}return Sn(e,t,r)}:Sn:function(e,t,r){if(Aa(e),t=lc(t),Aa(r),PS)try{return Sn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new AS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var ri=b((sA,dc)=>{"use strict";dc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var br=b((nA,pc)=>{"use strict";var RS=qe(),LS=Ht(),$S=ri();pc.exports=RS?function(a,e,t){return LS.f(a,e,$S(1,t))}:function(a,e,t){return a[e]=t,a}});var ka=b((oA,fc)=>{"use strict";var MS=fn(),CS=mn(),hc=MS("keys");fc.exports=function(a){return hc[a]||(hc[a]=CS(a))}});var Ra=b((uA,mc)=>{"use strict";mc.exports={}});var Pn=b((lA,Sc)=>{"use strict";var DS=hl(),gc=de(),OS=Fe(),BS=br(),In=Xe(),En=ei(),VS=ka(),_S=Ra(),bc="Object already initialized",xn=gc.TypeError,NS=gc.WeakMap,La,ii,$a,FS=function(a){return $a(a)?ii(a):La(a,{})},qS=function(a){return function(e){var t;if(!OS(e)||(t=ii(e)).type!==a)throw new xn("Incompatible receiver, "+a+" required");return t}};DS||En.state?(Ze=En.state||(En.state=new NS),Ze.get=Ze.get,Ze.has=Ze.has,Ze.set=Ze.set,La=function(a,e){if(Ze.has(a))throw new xn(bc);return e.facade=a,Ze.set(a,e),e},ii=function(a){return Ze.get(a)||{}},$a=function(a){return Ze.has(a)}):(jt=VS("state"),_S[jt]=!0,La=function(a,e){if(In(a,jt))throw new xn(bc);return e.facade=a,BS(a,jt,e),e},ii=function(a){return In(a,jt)?a[jt]:{}},$a=function(a){return In(a,jt)});var Ze,jt;Sc.exports={set:La,get:ii,has:$a,enforce:FS,getterFor:qS}});var wn=b((cA,Ic)=>{"use strict";var US=Qr(),Tc=Function.prototype,vc=Tc.apply,yc=Tc.call;Ic.exports=typeof Reflect=="object"&&Reflect.apply||(US?yc.bind(vc):function(){return yc.apply(vc,arguments)})});var An=b((dA,Ec)=>{"use strict";var HS=dr(),jS=Pe();Ec.exports=function(a){if(HS(a)==="Function")return jS(a)}});var Ac=b(wc=>{"use strict";var xc={}.propertyIsEnumerable,Pc=Object.getOwnPropertyDescriptor,GS=Pc&&!xc.call({1:2},1);wc.f=GS?function(e){var t=Pc(this,e);return!!t&&t.enumerable}:xc});var Lc=b(Rc=>{"use strict";var YS=qe(),WS=Oe(),QS=Ac(),zS=ri(),KS=hr(),JS=gn(),XS=Xe(),ZS=tn(),kc=Object.getOwnPropertyDescriptor;Rc.f=YS?kc:function(e,t){if(e=KS(e),t=JS(t),ZS)try{return kc(e,t)}catch(r){}if(XS(e,t))return zS(!WS(QS.f,e,t),e[t])}});var kn=b((fA,$c)=>{"use strict";var ev=De(),tv=ce(),rv=/#|\.prototype\./,ai=function(a,e){var t=av[iv(a)];return t===nv?!0:t===sv?!1:tv(e)?ev(e):!!e},iv=ai.normalize=function(a){return String(a).replace(rv,".").toLowerCase()},av=ai.data={},sv=ai.NATIVE="N",nv=ai.POLYFILL="P";$c.exports=ai});var si=b((mA,Cc)=>{"use strict";var Mc=An(),ov=pt(),uv=Qr(),lv=Mc(Mc.bind);Cc.exports=function(a,e){return ov(a),e===void 0?a:uv?lv(a,e):function(){return a.apply(e,arguments)}}});var Ue=b((bA,Oc)=>{"use strict";var ni=de(),cv=wn(),dv=An(),pv=ce(),hv=Lc().f,fv=kn(),gr=Pa(),mv=si(),Sr=br(),Dc=Xe();ei();var bv=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return cv(a,this,arguments)};return e.prototype=a.prototype,e};Oc.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ni:i?ni[t]:ni[t]&&ni[t].prototype,o=r?gr:gr[t]||Sr(gr,t,{})[t],u=o.prototype,l,c,d,p,h,m,g,S,T;for(p in e)l=fv(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Dc(n,p),m=o[p],c&&(a.dontCallGetSet?(T=hv(n,p),g=T&&T.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?S=mv(h,ni):a.wrap&&c?S=bv(h):s&&pv(h)?S=dv(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&Sr(S,"sham",!0),Sr(o,p,S),s&&(d=t+"Prototype",Dc(gr,d)||Sr(gr,d,{}),Sr(gr[d],p,h),a.real&&u&&(l||!u[p])&&Sr(u,p,h)))}});var _c=b((gA,Vc)=>{"use strict";var Rn=qe(),gv=Xe(),Bc=Function.prototype,Sv=Rn&&Object.getOwnPropertyDescriptor,Ln=gv(Bc,"name"),vv=Ln&&function(){}.name==="something",yv=Ln&&(!Rn||Rn&&Sv(Bc,"name").configurable);Vc.exports={EXISTS:Ln,PROPER:vv,CONFIGURABLE:yv}});var Fc=b((SA,Nc)=>{"use strict";var Tv=Math.ceil,Iv=Math.floor;Nc.exports=Math.trunc||function(e){var t=+e;return(t>0?Iv:Tv)(t)}});var Ma=b((vA,qc)=>{"use strict";var Ev=Fc();qc.exports=function(a){var e=+a;return e!==e||e===0?0:Ev(e)}});var Hc=b((yA,Uc)=>{"use strict";var xv=Ma(),Pv=Math.max,wv=Math.min;Uc.exports=function(a,e){var t=xv(a);return t<0?Pv(t+e,0):wv(t,e)}});var Gc=b((TA,jc)=>{"use strict";var Av=Ma(),kv=Math.min;jc.exports=function(a){var e=Av(a);return e>0?kv(e,9007199254740991):0}});var Ca=b((IA,Yc)=>{"use strict";var Rv=Gc();Yc.exports=function(a){return Rv(a.length)}});var zc=b((EA,Qc)=>{"use strict";var Lv=hr(),$v=Hc(),Mv=Ca(),Wc=function(a){return function(e,t,r){var i=Lv(e),s=Mv(i);if(s===0)return!a&&-1;var n=$v(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Qc.exports={includes:Wc(!0),indexOf:Wc(!1)}});var Xc=b((xA,Jc)=>{"use strict";var Cv=Pe(),$n=Xe(),Dv=hr(),Ov=zc().indexOf,Bv=Ra(),Kc=Cv([].push);Jc.exports=function(a,e){var t=Dv(a),r=0,i=[],s;for(s in t)!$n(Bv,s)&&$n(t,s)&&Kc(i,s);for(;e.length>r;)$n(t,s=e[r++])&&(~Ov(i,s)||Kc(i,s));return i}});var Mn=b((PA,Zc)=>{"use strict";Zc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var td=b((wA,ed)=>{"use strict";var Vv=Xc(),_v=Mn();ed.exports=Object.keys||function(e){return Vv(e,_v)}});var id=b(rd=>{"use strict";var Nv=qe(),Fv=rn(),qv=Ht(),Uv=at(),Hv=hr(),jv=td();rd.f=Nv&&!Fv?Object.defineProperties:function(e,t){Uv(e);for(var r=Hv(t),i=jv(t),s=i.length,n=0,o;s>n;)qv.f(e,o=i[n++],r[o]);return e}});var Cn=b((kA,ad)=>{"use strict";var Gv=dt();ad.exports=Gv("document","documentElement")});var Vn=b((RA,dd)=>{"use strict";var Yv=at(),Wv=id(),sd=Mn(),Qv=Ra(),zv=Cn(),Kv=Ea(),Jv=ka(),nd=">",od="<",On="prototype",Bn="script",ld=Jv("IE_PROTO"),Dn=function(){},cd=function(a){return od+Bn+nd+a+od+"/"+Bn+nd},ud=function(a){a.write(cd("")),a.close();var e=a.parentWindow.Object;return a=null,e},Xv=function(){var a=Kv("iframe"),e="java"+Bn+":",t;return a.style.display="none",zv.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(cd("document.F=Object")),t.close(),t.F},Da,Oa=function(){try{Da=new ActiveXObject("htmlfile")}catch(e){}Oa=typeof document!="undefined"?document.domain&&Da?ud(Da):Xv():ud(Da);for(var a=sd.length;a--;)delete Oa[On][sd[a]];return Oa()};Qv[ld]=!0;dd.exports=Object.create||function(e,t){var r;return e!==null?(Dn[On]=Yv(e),r=new Dn,Dn[On]=null,r[ld]=e):r=Oa(),t===void 0?r:Wv.f(r,t)}});var hd=b((LA,pd)=>{"use strict";var Zv=De();pd.exports=!Zv(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Nn=b(($A,md)=>{"use strict";var ey=Xe(),ty=ce(),ry=ti(),iy=ka(),ay=hd(),fd=iy("IE_PROTO"),_n=Object,sy=_n.prototype;md.exports=ay?_n.getPrototypeOf:function(a){var e=ry(a);if(ey(e,fd))return e[fd];var t=e.constructor;return ty(t)&&e instanceof t?t.prototype:e instanceof _n?sy:null}});var vr=b((MA,bd)=>{"use strict";var ny=br();bd.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:ny(a,e,t),a}});var Hn=b((CA,vd)=>{"use strict";var oy=De(),uy=ce(),ly=Fe(),cy=Vn(),gd=Nn(),dy=vr(),py=Te(),hy=Je(),Un=py("iterator"),Sd=!1,ht,Fn,qn;[].keys&&(qn=[].keys(),"next"in qn?(Fn=gd(gd(qn)),Fn!==Object.prototype&&(ht=Fn)):Sd=!0);var fy=!ly(ht)||oy(function(){var a={};return ht[Un].call(a)!==a});fy?ht={}:hy&&(ht=cy(ht));uy(ht[Un])||dy(ht,Un,function(){return this});vd.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:Sd}});var Ba=b((DA,Td)=>{"use strict";var my=Te(),by=my("toStringTag"),yd={};yd[by]="z";Td.exports=String(yd)==="[object z]"});var oi=b((OA,Id)=>{"use strict";var gy=Ba(),Sy=ce(),Va=dr(),vy=Te(),yy=vy("toStringTag"),Ty=Object,Iy=Va(function(){return arguments}())==="Arguments",Ey=function(a,e){try{return a[e]}catch(t){}};Id.exports=gy?Va:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=Ey(e=Ty(a),yy))=="string"?t:Iy?Va(e):(r=Va(e))==="Object"&&Sy(e.callee)?"Arguments":r}});var xd=b((BA,Ed)=>{"use strict";var xy=Ba(),Py=oi();Ed.exports=xy?{}.toString:function(){return"[object "+Py(this)+"]"}});var ui=b((VA,wd)=>{"use strict";var wy=Ba(),Ay=Ht().f,ky=br(),Ry=Xe(),Ly=xd(),$y=Te(),Pd=$y("toStringTag");wd.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(Ry(i,Pd)||Ay(i,Pd,{configurable:!0,value:e}),r&&!wy&&ky(i,"toString",Ly))}});var kd=b((_A,Ad)=>{"use strict";var My=Hn().IteratorPrototype,Cy=Vn(),Dy=ri(),Oy=ui(),By=Ut(),Vy=function(){return this};Ad.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=Cy(My,{next:Dy(+!r,t)}),Oy(a,i,!1,!0),By[i]=Vy,a}});var Ld=b((NA,Rd)=>{"use strict";var _y=Pe(),Ny=pt();Rd.exports=function(a,e,t){try{return _y(Ny(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Md=b((FA,$d)=>{"use strict";var Fy=Fe();$d.exports=function(a){return Fy(a)||a===null}});var Dd=b((qA,Cd)=>{"use strict";var qy=Md(),Uy=String,Hy=TypeError;Cd.exports=function(a){if(qy(a))return a;throw new Hy("Can't set "+Uy(a)+" as a prototype")}});var jn=b((UA,Od)=>{"use strict";var jy=Ld(),Gy=Fe(),Yy=zr(),Wy=Dd();Od.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=jy(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return Yy(i),Wy(s),Gy(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Yd=b((HA,Gd)=>{"use strict";var Qy=Ue(),zy=Oe(),_a=Je(),Hd=_c(),Ky=ce(),Jy=kd(),Bd=Nn(),Vd=jn(),Xy=ui(),Zy=br(),Gn=vr(),eT=Te(),_d=Ut(),jd=Hn(),tT=Hd.PROPER,rT=Hd.CONFIGURABLE,Nd=jd.IteratorPrototype,Na=jd.BUGGY_SAFARI_ITERATORS,li=eT("iterator"),Fd="keys",ci="values",qd="entries",Ud=function(){return this};Gd.exports=function(a,e,t,r,i,s,n){Jy(t,e,r);var o=function(T){if(T===i&&p)return p;if(!Na&&T&&T in c)return c[T];switch(T){case Fd:return function(){return new t(this,T)};case ci:return function(){return new t(this,T)};case qd:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[li]||c["@@iterator"]||i&&c[i],p=!Na&&d||o(i),h=e==="Array"&&c.entries||d,m,g,S;if(h&&(m=Bd(h.call(new a)),m!==Object.prototype&&m.next&&(!_a&&Bd(m)!==Nd&&(Vd?Vd(m,Nd):Ky(m[li])||Gn(m,li,Ud)),Xy(m,u,!0,!0),_a&&(_d[u]=Ud))),tT&&i===ci&&d&&d.name!==ci&&(!_a&&rT?Zy(c,"name",ci):(l=!0,p=function(){return zy(d,this)})),i)if(g={values:o(ci),keys:s?p:o(Fd),entries:o(qd)},n)for(S in g)(Na||l||!(S in c))&&Gn(c,S,g[S]);else Qy({target:e,proto:!0,forced:Na||l},g);return(!_a||n)&&c[li]!==p&&Gn(c,li,p,{name:i}),_d[e]=p,g}});var Qd=b((jA,Wd)=>{"use strict";Wd.exports=function(a,e){return{value:a,done:e}}});var Wn=b((GA,Zd)=>{"use strict";var iT=hr(),Yn=Js(),zd=Ut(),Jd=Pn(),aT=Ht().f,sT=Yd(),Fa=Qd(),nT=Je(),oT=qe(),Xd="Array Iterator",uT=Jd.set,lT=Jd.getterFor(Xd);Zd.exports=sT(Array,"Array",function(a,e){uT(this,{type:Xd,target:iT(a),index:0,kind:e})},function(){var a=lT(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Fa(void 0,!0);switch(a.kind){case"keys":return Fa(t,!1);case"values":return Fa(e[t],!1)}return Fa([t,e[t]],!1)},"values");var Kd=zd.Arguments=zd.Array;Yn("keys");Yn("values");Yn("entries");if(!nT&&oT&&Kd.name!=="values")try{aT(Kd,"name",{value:"values"})}catch(a){}});var tp=b((YA,ep)=>{"use strict";var cT=Te(),dT=Ut(),pT=cT("iterator"),hT=Array.prototype;ep.exports=function(a){return a!==void 0&&(dT.Array===a||hT[pT]===a)}});var Qn=b((WA,ip)=>{"use strict";var fT=oi(),rp=Zr(),mT=pr(),bT=Ut(),gT=Te(),ST=gT("iterator");ip.exports=function(a){if(!mT(a))return rp(a,ST)||rp(a,"@@iterator")||bT[fT(a)]}});var sp=b((QA,ap)=>{"use strict";var vT=Oe(),yT=pt(),TT=at(),IT=Xr(),ET=Qn(),xT=TypeError;ap.exports=function(a,e){var t=arguments.length<2?ET(a):e;if(yT(t))return TT(vT(t,a));throw new xT(IT(a)+" is not iterable")}});var up=b((zA,op)=>{"use strict";var PT=Oe(),np=at(),wT=Zr();op.exports=function(a,e,t){var r,i;np(a);try{if(r=wT(a,"return"),!r){if(e==="throw")throw t;return t}r=PT(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return np(r),t}});var Ua=b((KA,pp)=>{"use strict";var AT=si(),kT=Oe(),RT=at(),LT=Xr(),$T=tp(),MT=Ca(),lp=Jr(),CT=sp(),DT=Qn(),cp=up(),OT=TypeError,qa=function(a,e){this.stopped=a,this.result=e},dp=qa.prototype;pp.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=AT(e,r),l,c,d,p,h,m,g,S=function(w){return l&&cp(l,"normal",w),new qa(!0,w)},T=function(w){return i?(RT(w),o?u(w[0],w[1],S):u(w[0],w[1])):o?u(w,S):u(w)};if(s)l=a.iterator;else if(n)l=a;else{if(c=DT(a),!c)throw new OT(LT(a)+" is not iterable");if($T(c)){for(d=0,p=MT(a);p>d;d++)if(h=T(a[d]),h&&lp(dp,h))return h;return new qa(!1)}l=CT(a,c)}for(m=s?a.next:l.next;!(g=kT(m,l)).done;){try{h=T(g.value)}catch(w){cp(l,"throw",w)}if(typeof h=="object"&&h&&lp(dp,h))return h}return new qa(!1)}});var fp=b((JA,hp)=>{"use strict";var BT=qe(),VT=Ht(),_T=ri();hp.exports=function(a,e,t){BT?VT.f(a,e,_T(0,t)):a[e]=t}});var mp=b(()=>{"use strict";var NT=Ue(),FT=Ua(),qT=fp();NT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return FT(e,function(r,i){qT(t,r,i)},{AS_ENTRIES:!0}),t}})});var gp=b((ek,bp)=>{"use strict";Wn();mp();var UT=Pa();bp.exports=UT.Object.fromEntries});var vp=b((tk,Sp)=>{"use strict";Sp.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 Tp=b(()=>{"use strict";Wn();var HT=vp(),jT=de(),GT=ui(),yp=Ut();for(Ha in HT)GT(jT[Ha],Ha),yp[Ha]=yp.Array;var Ha});var Ep=b((ak,Ip)=>{"use strict";var YT=gp();Tp();Ip.exports=YT});var zn=b((sk,xp)=>{"use strict";var WT=Ep();xp.exports=WT});var Pp=b(()=>{"use strict"});var Kn=b((uk,wp)=>{"use strict";var di=de(),QT=fr(),zT=dr(),ja=function(a){return QT.slice(0,a.length)===a};wp.exports=function(){return ja("Bun/")?"BUN":ja("Cloudflare-Workers")?"CLOUDFLARE":ja("Deno/")?"DENO":ja("Node.js/")?"NODE":di.Bun&&typeof Bun.version=="string"?"BUN":di.Deno&&typeof Deno.version=="object"?"DENO":zT(di.process)==="process"?"NODE":di.window&&di.document?"BROWSER":"REST"}()});var Ga=b((lk,Ap)=>{"use strict";var KT=Kn();Ap.exports=KT==="NODE"});var Rp=b((ck,kp)=>{"use strict";var JT=Ht();kp.exports=function(a,e,t){return JT.f(a,e,t)}});var Mp=b((dk,$p)=>{"use strict";var XT=dt(),ZT=Rp(),eI=Te(),tI=qe(),Lp=eI("species");$p.exports=function(a){var e=XT(a);tI&&e&&!e[Lp]&&ZT(e,Lp,{configurable:!0,get:function(){return this}})}});var Dp=b((pk,Cp)=>{"use strict";var rI=Jr(),iI=TypeError;Cp.exports=function(a,e){if(rI(e,a))return a;throw new iI("Incorrect invocation")}});var Xn=b((hk,Op)=>{"use strict";var aI=Pe(),sI=ce(),Jn=ei(),nI=aI(Function.toString);sI(Jn.inspectSource)||(Jn.inspectSource=function(a){return nI(a)});Op.exports=Jn.inspectSource});var qp=b((fk,Fp)=>{"use strict";var oI=Pe(),uI=De(),Bp=ce(),lI=oi(),cI=dt(),dI=Xn(),Vp=function(){},_p=cI("Reflect","construct"),Zn=/^\s*(?:class|function)\b/,pI=oI(Zn.exec),hI=!Zn.test(Vp),pi=function(e){if(!Bp(e))return!1;try{return _p(Vp,[],e),!0}catch(t){return!1}},Np=function(e){if(!Bp(e))return!1;switch(lI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return hI||!!pI(Zn,dI(e))}catch(t){return!0}};Np.sham=!0;Fp.exports=!_p||uI(function(){var a;return pi(pi.call)||!pi(Object)||!pi(function(){a=!0})||a})?Np:pi});var Hp=b((mk,Up)=>{"use strict";var fI=qp(),mI=Xr(),bI=TypeError;Up.exports=function(a){if(fI(a))return a;throw new bI(mI(a)+" is not a constructor")}});var eo=b((bk,Gp)=>{"use strict";var jp=at(),gI=Hp(),SI=pr(),vI=Te(),yI=vI("species");Gp.exports=function(a,e){var t=jp(a).constructor,r;return t===void 0||SI(r=jp(t)[yI])?e:gI(r)}});var Wp=b((gk,Yp)=>{"use strict";var TI=Pe();Yp.exports=TI([].slice)});var zp=b((Sk,Qp)=>{"use strict";var II=TypeError;Qp.exports=function(a,e){if(a<e)throw new II("Not enough arguments");return a}});var to=b((vk,Kp)=>{"use strict";var EI=fr();Kp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(EI)});var co=b((yk,sh)=>{"use strict";var Be=de(),xI=wn(),PI=si(),Jp=ce(),wI=Xe(),ah=De(),Xp=Cn(),AI=Wp(),Zp=Ea(),kI=zp(),RI=to(),LI=Ga(),oo=Be.setImmediate,uo=Be.clearImmediate,$I=Be.process,ro=Be.Dispatch,MI=Be.Function,eh=Be.MessageChannel,CI=Be.String,io=0,hi={},th="onreadystatechange",fi,Gt,ao,so;ah(function(){fi=Be.location});var lo=function(a){if(wI(hi,a)){var e=hi[a];delete hi[a],e()}},no=function(a){return function(){lo(a)}},rh=function(a){lo(a.data)},ih=function(a){Be.postMessage(CI(a),fi.protocol+"//"+fi.host)};(!oo||!uo)&&(oo=function(e){kI(arguments.length,1);var t=Jp(e)?e:MI(e),r=AI(arguments,1);return hi[++io]=function(){xI(t,void 0,r)},Gt(io),io},uo=function(e){delete hi[e]},LI?Gt=function(a){$I.nextTick(no(a))}:ro&&ro.now?Gt=function(a){ro.now(no(a))}:eh&&!RI?(ao=new eh,so=ao.port2,ao.port1.onmessage=rh,Gt=PI(so.postMessage,so)):Be.addEventListener&&Jp(Be.postMessage)&&!Be.importScripts&&fi&&fi.protocol!=="file:"&&!ah(ih)?(Gt=ih,Be.addEventListener("message",rh,!1)):th in Zp("script")?Gt=function(a){Xp.appendChild(Zp("script"))[th]=function(){Xp.removeChild(this),lo(a)}}:Gt=function(a){setTimeout(no(a),0)});sh.exports={set:oo,clear:uo}});var uh=b((Tk,oh)=>{"use strict";var nh=de(),DI=qe(),OI=Object.getOwnPropertyDescriptor;oh.exports=function(a){if(!DI)return nh[a];var e=OI(nh,a);return e&&e.value}});var po=b((Ik,ch)=>{"use strict";var lh=function(){this.head=null,this.tail=null};lh.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};ch.exports=lh});var ph=b((Ek,dh)=>{"use strict";var BI=fr();dh.exports=/ipad|iphone|ipod/i.test(BI)&&typeof Pebble!="undefined"});var fh=b((xk,hh)=>{"use strict";var VI=fr();hh.exports=/web0s(?!.*chrome)/i.test(VI)});var Th=b((Pk,yh)=>{"use strict";var Tr=de(),_I=uh(),mh=si(),ho=co().set,NI=po(),FI=to(),qI=ph(),UI=fh(),fo=Ga(),bh=Tr.MutationObserver||Tr.WebKitMutationObserver,gh=Tr.document,Sh=Tr.process,Ya=Tr.Promise,go=_I("queueMicrotask"),yr,mo,bo,Wa,vh;go||(mi=new NI,bi=function(){var a,e;for(fo&&(a=Sh.domain)&&a.exit();e=mi.get();)try{e()}catch(t){throw mi.head&&yr(),t}a&&a.enter()},!FI&&!fo&&!UI&&bh&&gh?(mo=!0,bo=gh.createTextNode(""),new bh(bi).observe(bo,{characterData:!0}),yr=function(){bo.data=mo=!mo}):!qI&&Ya&&Ya.resolve?(Wa=Ya.resolve(void 0),Wa.constructor=Ya,vh=mh(Wa.then,Wa),yr=function(){vh(bi)}):fo?yr=function(){Sh.nextTick(bi)}:(ho=mh(ho,Tr),yr=function(){ho(bi)}),go=function(a){mi.head||yr(),mi.add(a)});var mi,bi;yh.exports=go});var Eh=b((wk,Ih)=>{"use strict";Ih.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Qa=b((Ak,xh)=>{"use strict";xh.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Yt=b((kk,Ph)=>{"use strict";var HI=de();Ph.exports=HI.Promise});var Ir=b((Rk,Rh)=>{"use strict";var jI=de(),gi=Yt(),GI=ce(),YI=kn(),WI=Xn(),QI=Te(),wh=Kn(),zI=Je(),So=on(),Ah=gi&&gi.prototype,KI=QI("species"),vo=!1,kh=GI(jI.PromiseRejectionEvent),JI=YI("Promise",function(){var a=WI(gi),e=a!==String(gi);if(!e&&So===66||zI&&!(Ah.catch&&Ah.finally))return!0;if(!So||So<51||!/native code/.test(a)){var t=new gi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[KI]=r,vo=t.then(function(){})instanceof r,!vo)return!0}return!e&&(wh==="BROWSER"||wh==="DENO")&&!kh});Rh.exports={CONSTRUCTOR:JI,REJECTION_EVENT:kh,SUBCLASSING:vo}});var Er=b((Lk,$h)=>{"use strict";var Lh=pt(),XI=TypeError,ZI=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new XI("Bad Promise constructor");e=r,t=i}),this.resolve=Lh(e),this.reject=Lh(t)};$h.exports.f=function(a){return new ZI(a)}});var Kh=b(()=>{"use strict";var eE=Ue(),tE=Je(),Xa=Ga(),Lt=de(),Ar=Oe(),Mh=vr(),Ch=jn(),rE=ui(),iE=Mp(),aE=pt(),Ja=ce(),sE=Fe(),nE=Dp(),oE=eo(),_h=co().set,xo=Th(),uE=Eh(),lE=Qa(),cE=po(),Nh=Pn(),Za=Yt(),Po=Ir(),Fh=Er(),es="Promise",qh=Po.CONSTRUCTOR,dE=Po.REJECTION_EVENT,pE=Po.SUBCLASSING,yo=Nh.getterFor(es),hE=Nh.set,xr=Za&&Za.prototype,Wt=Za,za=xr,Uh=Lt.TypeError,To=Lt.document,wo=Lt.process,Io=Fh.f,fE=Io,mE=!!(To&&To.createEvent&&Lt.dispatchEvent),Hh="unhandledrejection",bE="rejectionhandled",Dh=0,jh=1,gE=2,Ao=1,Gh=2,Ka,Oh,SE,Bh,Yh=function(a){var e;return sE(a)&&Ja(e=a.then)?e:!1},Wh=function(a,e){var t=e.value,r=e.state===jh,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Gh&&yE(e),e.rejection=Ao),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Uh("Promise-chain cycle")):(l=Yh(u))?Ar(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Qh=function(a,e){a.notified||(a.notified=!0,xo(function(){for(var t=a.reactions,r;r=t.get();)Wh(r,a);a.notified=!1,e&&!a.rejection&&vE(a)}))},zh=function(a,e,t){var r,i;mE?(r=To.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Lt.dispatchEvent(r)):r={promise:e,reason:t},!dE&&(i=Lt["on"+a])?i(r):a===Hh&&uE("Unhandled promise rejection",t)},vE=function(a){Ar(_h,Lt,function(){var e=a.facade,t=a.value,r=Vh(a),i;if(r&&(i=lE(function(){Xa?wo.emit("unhandledRejection",t,e):zh(Hh,e,t)}),a.rejection=Xa||Vh(a)?Gh:Ao,i.error))throw i.value})},Vh=function(a){return a.rejection!==Ao&&!a.parent},yE=function(a){Ar(_h,Lt,function(){var e=a.facade;Xa?wo.emit("rejectionHandled",e):zh(bE,e,a.value)})},Pr=function(a,e,t){return function(r){a(e,r,t)}},wr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=gE,Qh(a,!0))},Eo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Uh("Promise can't be resolved itself");var r=Yh(e);r?xo(function(){var i={done:!1};try{Ar(r,e,Pr(Eo,i,a),Pr(wr,i,a))}catch(s){wr(i,s,a)}}):(a.value=e,a.state=jh,Qh(a,!1))}catch(i){wr({done:!1},i,a)}}};if(qh&&(Wt=function(e){nE(this,za),aE(e),Ar(Ka,this);var t=yo(this);try{e(Pr(Eo,t),Pr(wr,t))}catch(r){wr(t,r)}},za=Wt.prototype,Ka=function(e){hE(this,{type:es,done:!1,notified:!1,parent:!1,reactions:new cE,rejection:!1,state:Dh,value:void 0})},Ka.prototype=Mh(za,"then",function(e,t){var r=yo(this),i=Io(oE(this,Wt));return r.parent=!0,i.ok=Ja(e)?e:!0,i.fail=Ja(t)&&t,i.domain=Xa?wo.domain:void 0,r.state===Dh?r.reactions.add(i):xo(function(){Wh(i,r)}),i.promise}),Oh=function(){var a=new Ka,e=yo(a);this.promise=a,this.resolve=Pr(Eo,e),this.reject=Pr(wr,e)},Fh.f=Io=function(a){return a===Wt||a===SE?new Oh(a):fE(a)},!tE&&Ja(Za)&&xr!==Object.prototype)){Bh=xr.then,pE||Mh(xr,"then",function(e,t){var r=this;return new Wt(function(i,s){Ar(Bh,r,i,s)}).then(e,t)},{unsafe:!0});try{delete xr.constructor}catch(a){}Ch&&Ch(xr,za)}eE({global:!0,constructor:!0,wrap:!0,forced:qh},{Promise:Wt});rE(Wt,es,!1,!0);iE(es)});var tf=b((Ck,ef)=>{"use strict";var TE=Te(),Xh=TE("iterator"),Zh=!1;try{Jh=0,ko={next:function(){return{done:!!Jh++}},return:function(){Zh=!0}},ko[Xh]=function(){return this},Array.from(ko,function(){throw 2})}catch(a){}var Jh,ko;ef.exports=function(a,e){try{if(!e&&!Zh)return!1}catch(i){return!1}var t=!1;try{var r={};r[Xh]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Ro=b((Dk,rf)=>{"use strict";var IE=Yt(),EE=tf(),xE=Ir().CONSTRUCTOR;rf.exports=xE||!EE(function(a){IE.all(a).then(void 0,function(){})})});var af=b(()=>{"use strict";var PE=Ue(),wE=Oe(),AE=pt(),kE=Er(),RE=Qa(),LE=Ua(),$E=Ro();PE({target:"Promise",stat:!0,forced:$E},{all:function(e){var t=this,r=kE.f(t),i=r.resolve,s=r.reject,n=RE(function(){var o=AE(t.resolve),u=[],l=0,c=1;LE(e,function(d){var p=l++,h=!1;c++,wE(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var nf=b(()=>{"use strict";var ME=Ue(),CE=Je(),DE=Ir().CONSTRUCTOR,$o=Yt(),OE=dt(),BE=ce(),VE=vr(),sf=$o&&$o.prototype;ME({target:"Promise",proto:!0,forced:DE,real:!0},{catch:function(a){return this.then(void 0,a)}});!CE&&BE($o)&&(Lo=OE("Promise").prototype.catch,sf.catch!==Lo&&VE(sf,"catch",Lo,{unsafe:!0}));var Lo});var of=b(()=>{"use strict";var _E=Ue(),NE=Oe(),FE=pt(),qE=Er(),UE=Qa(),HE=Ua(),jE=Ro();_E({target:"Promise",stat:!0,forced:jE},{race:function(e){var t=this,r=qE.f(t),i=r.reject,s=UE(function(){var n=FE(t.resolve);HE(e,function(o){NE(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var uf=b(()=>{"use strict";var GE=Ue(),YE=Er(),WE=Ir().CONSTRUCTOR;GE({target:"Promise",stat:!0,forced:WE},{reject:function(e){var t=YE.f(this),r=t.reject;return r(e),t.promise}})});var Mo=b((Hk,lf)=>{"use strict";var QE=at(),zE=Fe(),KE=Er();lf.exports=function(a,e){if(QE(a),zE(e)&&e.constructor===a)return e;var t=KE.f(a),r=t.resolve;return r(e),t.promise}});var pf=b(()=>{"use strict";var JE=Ue(),XE=dt(),cf=Je(),ZE=Yt(),df=Ir().CONSTRUCTOR,ex=Mo(),tx=XE("Promise"),rx=cf&&!df;JE({target:"Promise",stat:!0,forced:cf||df},{resolve:function(e){return ex(rx&&this===tx?ZE:this,e)}})});var hf=b(()=>{"use strict";Kh();af();nf();of();uf();pf()});var gf=b(()=>{"use strict";var ix=Ue(),ax=Je(),ts=Yt(),sx=De(),mf=dt(),bf=ce(),nx=eo(),ff=Mo(),ox=vr(),Do=ts&&ts.prototype,ux=!!ts&&sx(function(){Do.finally.call({then:function(){}},function(){})});ix({target:"Promise",proto:!0,real:!0,forced:ux},{finally:function(a){var e=nx(this,mf("Promise")),t=bf(a);return this.then(t?function(r){return ff(e,a()).then(function(){return r})}:a,t?function(r){return ff(e,a()).then(function(){throw r})}:a)}});!ax&&bf(ts)&&(Co=mf("Promise").prototype.finally,Do.finally!==Co&&ox(Do,"finally",Co,{unsafe:!0}));var Co});var rs=b((Kk,Sf)=>{"use strict";var lx=dt();Sf.exports=lx});var yf=b((Jk,vf)=>{"use strict";Pp();hf();gf();var cx=rs();vf.exports=cx("Promise","finally")});var If=b((Xk,Tf)=>{"use strict";var dx=yf();Tf.exports=dx});var is=b((Zk,Ef)=>{"use strict";var px=If();Ef.exports=px});var Cf=b(()=>{"use strict";var yx=Ue(),Tx=ti(),Ix=Ca(),Ex=Ma(),xx=Js();yx({target:"Array",proto:!0},{at:function(e){var t=Tx(this),r=Ix(t),i=Ex(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});xx("at")});var Of=b((JR,Df)=>{"use strict";Cf();var Px=rs();Df.exports=Px("Array","at")});var Vf=b((XR,Bf)=>{"use strict";var wx=Of();Bf.exports=wx});var vi=b((ZR,_f)=>{"use strict";var Ax=Vf();_f.exports=Ax});var xm=b(()=>{"use strict"});var Pm=b(()=>{"use strict"});var Am=b((QC,wm)=>{"use strict";var cP=Fe(),dP=dr(),pP=Te(),hP=pP("match");wm.exports=function(a){var e;return cP(a)&&((e=a[hP])!==void 0?!!e:dP(a)==="RegExp")}});var Rm=b((zC,km)=>{"use strict";var fP=oi(),mP=String;km.exports=function(a){if(fP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return mP(a)}});var $m=b((KC,Lm)=>{"use strict";var bP=at();Lm.exports=function(){var a=bP(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Dm=b((JC,Cm)=>{"use strict";var gP=Oe(),SP=Xe(),vP=Jr(),yP=$m(),Mm=RegExp.prototype;Cm.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Mm)&&!SP(a,"flags")&&vP(Mm,a)?gP(yP,a):e}});var Bm=b((XC,Om)=>{"use strict";var iu=Pe(),TP=ti(),IP=Math.floor,tu=iu("".charAt),EP=iu("".replace),ru=iu("".slice),xP=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,PP=/\$([$&'`]|\d{1,2})/g;Om.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=PP;return i!==void 0&&(i=TP(i),u=xP),EP(s,u,function(l,c){var d;switch(tu(c,0)){case"$":return"$";case"&":return a;case"`":return ru(e,0,t);case"'":return ru(e,n);case"<":d=i[ru(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=IP(p/10);return h===0?l:h<=o?r[h-1]===void 0?tu(c,1):r[h-1]+tu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var Nm=b(()=>{"use strict";var wP=Ue(),AP=Oe(),su=Pe(),Vm=zr(),kP=ce(),RP=pr(),LP=Am(),Br=Rm(),$P=Zr(),MP=Dm(),CP=Bm(),DP=Te(),OP=Je(),BP=DP("replace"),VP=TypeError,au=su("".indexOf),_P=su("".replace),_m=su("".slice),NP=Math.max;wP({target:"String",proto:!0},{replaceAll:function(e,t){var r=Vm(this),i,s,n,o,u,l,c,d,p,h,m=0,g="";if(!RP(e)){if(i=LP(e),i&&(s=Br(Vm(MP(e))),!~au(s,"g")))throw new VP("`.replaceAll` does not allow non-global regexes");if(n=$P(e,BP),n)return AP(n,e,r,t);if(OP&&i)return _P(Br(r),e,t)}for(o=Br(r),u=Br(e),l=kP(t),l||(t=Br(t)),c=u.length,d=NP(1,c),p=au(o,u);p!==-1;)h=l?Br(t(u,p,o)):CP(u,o,p,[],void 0,t),g+=_m(o,m,p)+h,m=p+c,p=p+d>o.length?-1:au(o,u,p+d);return m<o.length&&(g+=_m(o,m)),g}})});var qm=b((tD,Fm)=>{"use strict";xm();Pm();Nm();var FP=rs();Fm.exports=FP("String","replaceAll")});var Hm=b((rD,Um)=>{"use strict";var qP=qm();Um.exports=qP});var Gm=b((iD,jm)=>{"use strict";var UP=Hm();jm.exports=UP});var iw={};tg(iw,{ChromecastState:()=>Wr,HttpConnectionType:()=>ya,Observable:()=>lt.Observable,PlaybackState:()=>ye,Player:()=>fa,SDK_VERSION:()=>rw,Subject:()=>lt.Subject,Subscription:()=>lt.Subscription,Surface:()=>Ta,VERSION:()=>Qs,ValueSubject:()=>lt.ValueSubject,VideoFormat:()=>ct,VideoQuality:()=>lt.VideoQuality});module.exports=rg(iw);var Qs="2.0.108-dev.69cab4e9.0";var ye=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ye||{}),ct=(I=>(I.MPEG="MPEG",I.DASH="DASH",I.DASH_SEP="DASH_SEP",I.DASH_SEP_VK="DASH_SEP",I.DASH_WEBM="DASH_WEBM",I.DASH_WEBM_AV1="DASH_WEBM_AV1",I.DASH_STREAMS="DASH_STREAMS",I.DASH_WEBM_VK="DASH_WEBM",I.DASH_ONDEMAND="DASH_ONDEMAND",I.DASH_ONDEMAND_VK="DASH_ONDEMAND",I.DASH_LIVE="DASH_LIVE",I.DASH_LIVE_CMAF="DASH_LIVE_CMAF",I.DASH_LIVE_WEBM="DASH_LIVE_WEBM",I.HLS="HLS",I.HLS_ONDEMAND="HLS_ONDEMAND",I.HLS_JS="HLS",I.HLS_LIVE="HLS_LIVE",I.HLS_LIVE_CMAF="HLS_LIVE_CMAF",I.WEB_RTC_LIVE="WEB_RTC_LIVE",I))(ct||{});var Wr=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Wr||{}),ya=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ya||{});var Ta=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ta||{});var F=require("@vkontakte/videoplayer-shared");var Qu=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Ia=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,F.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Qu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,F.assertNever)(i.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,F.map)(i=>i.castState)),(0,F.observableFrom)([r.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(ag),(0,F.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o;let s=i==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();(0,F.assertNonNullable)(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;((0,F.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,F.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},ag=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,F.assertNever)(a)}};var fb=ze(zn(),1);var Af=ze(is(),1);var Oo=require("@vkontakte/videoplayer-shared");var ve=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,Oo.assertNever)(t)}return a},Bo=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,Oo.assertNever)(e)}};var A=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var st=require("@vkontakte/videoplayer-shared"),H=class{constructor(e){this.transitionStarted$=new st.Subject;this.transitionEnded$=new st.Subject;this.transitionUpdated$=new st.Subject;this.forceChanged$=new st.Subject;this.stateChangeStarted$=(0,st.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,st.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,st.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var xf=require("@vkontakte/videoplayer-shared"),Pf=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,xf.assertNever)(a)}};var R=require("@vkontakte/videoplayer-shared");var hx=5,fx=5,mx=500,wf=7e3,Si=class{constructor(e){this.subscription=new R.Subscription;this.loadMediaTimeoutSubscription=new R.Subscription;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}default:(0,R.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Pf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new R.Subscription;this.subscription.add(e),this.subscription.add((0,R.merge)(this.videoState.stateChangeStarted$.pipe((0,R.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,R.map)(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new R.Subject;e.add(i.pipe((0,R.debounce)(mx)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>hx)&&i.next(o),s=o})),e.add((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.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<fx&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,R.assertNever)(n)}}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,R.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,R.observableFrom)(["init"])).pipe((0,R.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];(0,R.assertNonNullable)(c);let d=(0,R.getHighestQuality)(Object.keys(c));(0,R.assertNonNullable)(d);let p=c[d];(0,R.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,R.assertNonNullable)(c),r=c.url,i="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 c=t[e];(0,R.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,R.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,R.assertNonNullable)(c),r=ve(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,R.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,R.isNonNullable)(o)&&(n.metadata.title=o),(0,R.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add((0,R.timeout)(wf).subscribe(()=>s(`timeout(${wf})`)))});(0,Af.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:R.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Fo=require("@vkontakte/videoplayer-shared");var kf=require("@vkontakte/videoplayer-shared"),Rf=a=>{try{a.pause(),a.playbackRate=0,(0,kf.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var as=require("@vkontakte/videoplayer-shared"),Vo=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},_o=window.WeakMap?new WeakMap:new Vo,No=window.WeakMap?new WeakMap:new Map,bx=(a,e=20)=>{let t=0;return(0,as.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},we=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,Fo.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),_o.set(t,r);let i=new as.Subscription;return i.add(bx(t,e)),No.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Ae=a=>{let e=No.get(a);e==null||e.unsubscribe(),No.delete(a);let t=_o.get(a);_o.delete(a),t?(0,Fo.clearVideoElement)(a):Rf(a)};var L=require("@vkontakte/videoplayer-shared");var $t=require("@vkontakte/videoplayer-shared"),ss=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,$t.isNullable)(i),l=new $t.Subscription;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},nt=(a,e,t)=>ss(e,()=>a.loop,r=>{(0,$t.isNonNullable)(r)&&(a.loop=r)},{onError:t}),ke=(a,e,t,r)=>ss(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,$t.isNonNullable)(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),He=(a,e,t,r)=>ss(e,()=>a.playbackRate,i=>{(0,$t.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Mt=ss;var gx=a=>["__",a.language,a.label].join("|"),Sx=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},qo=class a{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Mt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Mt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Mt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Mt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,L.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,L.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,L.filterChanged)()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;(0,L.isNonNullable)(t.align)&&(i.align=t.align),(0,L.isNonNullable)(t.position)&&(i.position=t.position),(0,L.isNonNullable)(t.size)&&(i.size=t.size),(0,L.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:gx(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!Sx(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,L.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,L.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},je=qo;var mt=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 Lf=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Uo=a=>{let e=Lf(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},$f=a=>{let e=Lf(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var $=require("@vkontakte/videoplayer-shared");var vx=3,Mf=(a,e,t=vx)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Re=a=>{let e=I=>(0,$.fromEvent)(a,I).pipe((0,$.mapTo)(void 0)),r=(0,$.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>(0,$.fromEvent)(a,I))).pipe((0,$.map)(I=>I.type==="ended"?a.readyState<2:a.readyState<3),(0,$.filterChanged)()),i=(0,$.merge)((0,$.fromEvent)(a,"progress"),(0,$.fromEvent)(a,"timeupdate")).pipe((0,$.map)(()=>Mf(a.buffered,a.currentTime))),s=$.clientChecker.isSafari?(0,$.combine)({play:e("play").pipe((0,$.once)()),playing:e("playing")}).pipe((0,$.mapTo)(void 0)):e("playing"),n=(0,$.fromEvent)(a,"volumechange").pipe((0,$.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,$.fromEvent)(a,"ratechange").pipe((0,$.map)(()=>a.playbackRate)),u=(0,$.fromEvent)(a,"error").pipe((0,$.filter)(()=>!!(a.error||a.played.length)),(0,$.map)(()=>{var x;let I=a.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:$.ErrorCategory.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(x=a.error)!=null?x:void 0}})),l=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(()=>a.currentTime)),c=new $.Subject,d=.3,p;l.subscribe(I=>{a.loop&&(0,$.isNonNullable)(p)&&(0,$.isNonNullable)(I)&&p>=a.duration-d&&I<=d&&c.next(p),p=I});let h=e("pause").pipe((0,$.filter)(()=>!a.error&&p!==a.duration)),m=(0,$.fromEvent)(a,"enterpictureinpicture"),g=(0,$.fromEvent)(a,"leavepictureinpicture"),S=new $.ValueSubject($f(a));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let T=new $.ValueSubject(Uo(a));return(0,$.fromEvent)(a,"fullscreenchange").pipe((0,$.map)(()=>Uo(a))).subscribe(T),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,$.fromEvent)(a,"durationchange").pipe((0,$.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:T}};var bt=require("@vkontakte/videoplayer-shared"),Ct=a=>{switch(a){case"mobile":return bt.VideoQuality.Q_144P;case"lowest":return bt.VideoQuality.Q_240P;case"low":return bt.VideoQuality.Q_360P;case"sd":case"medium":return bt.VideoQuality.Q_480P;case"hd":case"high":return bt.VideoQuality.Q_720P;case"fullhd":case"full":return bt.VideoQuality.Q_1080P;case"quadhd":case"quad":return bt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return bt.VideoQuality.Q_2160P}};var jo=ze(vi(),1),G=require("@vkontakte/videoplayer-shared");var Ho=!1,gt={},Nf=a=>{Ho=a},Ff=()=>{gt={}},qf=a=>{a(gt)},yi=(a,e)=>{var t;Ho&&(gt.meta=(t=gt.meta)!=null?t:{},gt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var r,i;if(!Ho)return;gt.series=(r=gt.series)!=null?r:{};let t=(i=gt.series[this.name])!=null?i:[];t.push([Date.now(),e]),gt.series[this.name]=t}};var kx=new Ie("best_bitrate"),Rx=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t,ns=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,G.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Lx='Assertion "ABR Tracks is empty array" failed',$x=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var ee,N,M,te,ue;(0,G.assertNotEmptyArray)(a,Lx);let p=r.usePixelRatio&&(ee=window.devicePixelRatio)!=null?ee:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},m=h&&(0,G.videoSizeToQuality)(h),g=r.considerPlaybackRate&&(0,G.isNonNullable)(o)?o:1,S=a.filter(B=>!(0,G.isInvariantQuality)(B.quality)).sort((B,k)=>(0,G.isHigher)(B.quality,k.quality)?-1:1),T=(N=(0,jo.default)(S,-1))==null?void 0:N.quality,w=(M=(0,jo.default)(S,0))==null?void 0:M.quality,I=(0,G.isNullable)(i)||(0,G.isNonNullable)(i.min)&&(0,G.isNonNullable)(i.max)&&(0,G.isLower)(i.max,i.min)||(0,G.isNonNullable)(i.min)&&w&&(0,G.isHigher)(i.min,w)||(0,G.isNonNullable)(i.max)&&T&&(0,G.isLower)(i.max,T),x=g*Rx(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),E={},Y=S.filter(B=>(m?(0,G.isLower)(B.quality,m):!0)?((0,G.isNonNullable)(t)&&isFinite(t)&&(0,G.isNonNullable)(B.bitrate)?t-s>=B.bitrate*x:!0)?r.lazyQualitySwitch&&(0,G.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,G.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,G.isHigher)(B.quality,u.quality)?(E[B.quality]="Buffer",!1):!!c&&(0,G.isHigherOrEqual)(B.quality,c)?(E[B.quality]="DroppedFramesLimit",!1):I||((0,G.isNullable)(i.max)||(0,G.isLowerOrEqual)(B.quality,i.max))&&((0,G.isNullable)(i.min)||(0,G.isHigherOrEqual)(B.quality,i.min))?!0:(E[B.quality]="FitsQualityLimits",!1):(E[B.quality]="FitsThroughput",!1):(E[B.quality]="FitsContainer",!1))[0];Y&&Y.bitrate&&kx.next(Y.bitrate);let U=(te=Y!=null?Y:S[Math.ceil((S.length-1)/2)])!=null?te:a[0];U.quality!==((ue=l==null?void 0:l.last)==null?void 0:ue.quality)&&d({message:`
7
+ [available tracks]
8
+ ${a.map(B=>`{ id: ${B.id}, quality: ${B.quality}, bitrate: ${B.bitrate} }`).join(`
12
9
  `)}
13
10
 
14
11
  [tuning]
15
- ${Object.entries(r!=null?r:{}).map(([V,pe])=>`${V}: ${pe}`).join(`
12
+ ${Object.entries(r!=null?r:{}).map(([B,k])=>`${B}: ${k}`).join(`
16
13
  `)}
17
14
 
18
15
  [limit params]
@@ -22,40 +19,22 @@
22
19
  playbackRate: ${o},
23
20
  playbackRateFactor: ${g},
24
21
  forwardBufferHealth: ${n},
25
- bitrateFactor: ${E},
22
+ bitrateFactor: ${x},
26
23
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
27
24
  droppedVideoMaxQualityLimit: ${c},
28
25
  limitsAreInvalid: ${I},
29
26
  maxQualityLimit: ${i==null?void 0:i.max},
30
27
  minQualityLimit: ${i==null?void 0:i.min},
31
28
 
32
- [limited video tracks]
33
- ${Object.entries(x).map(([V,pe])=>`${V}: ${pe}`).join(`
29
+ [limited tracks]
30
+ ${Object.entries(E).map(([B,k])=>`${B}: ${k}`).join(`
34
31
  `)||"All tracks are available"}
35
32
 
36
- [best video track] ${Y==null?void 0:Y.quality}
37
- [selected video track] ${ie==null?void 0:ie.quality}
38
- `}),Wf(r,d,ie,l)},Qf=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var m;(0,O.assertNotEmptyArray)(t,Yf);let l=i.considerPlaybackRate&&(0,O.isNonNullable)(s)?s:1,c=[...t].sort(Yo(-1)),d=a.bitrate;(0,O.assertNonNullable)(d);let p=l*Gf(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),h;return(0,O.isNonNullable)(r)&&isFinite(r)&&(h=c.find(g=>(0,O.isNonNullable)(g.bitrate)?r-d>=g.bitrate*p:!0)),h||(h=us(a,e,t,i.minVideoAudioRatio)),(h==null?void 0:h.bitrate)!==((m=o==null?void 0:o.last)==null?void 0:m.bitrate)&&u({message:`
39
- [AUDIO TRACKS ABR]
40
- [available audio tracks]
41
- ${e.map(g=>`{ id: ${g.id}, quality: ${g.quality}, bitrate: ${g.bitrate} }`).join(`
42
- `)}
43
-
44
- [tuning]
45
- ${Object.entries(i!=null?i:{}).map(([g,S])=>`${g}: ${S}`).join(`
46
- `)}
47
-
48
- [limit params]
49
- throughput: ${r},
50
- reserve: ${d},
51
- playbackRate: ${s},
52
- playbackRateFactor: ${l},
53
- forwardBufferHealth: ${n},
54
- bitrateFactor: ${p},
55
- minBufferToSwitchUp: ${i.minBufferToSwitchUp},
56
-
57
- [selected audio track] ${h==null?void 0:h.bitrate}
58
- `}),h&&Wf(i,u,h,o)};var Se=a=>new URL(a).hostname;var B=require("@vkontakte/videoplayer-shared");var zf=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},$e=a=>D(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!zf(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return zf(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});var Ve=require("@vkontakte/videoplayer-shared");var ut=require("@vkontakte/videoplayer-shared");function ve(){return(0,ut.now)()}function Wo(a){return ve()-a}function Qo(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(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 Kf(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Rr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,ut.assertNonNullable)(c);let M=Wo(c),ee;if(M<g){ee=g-M,setTimeout(S,ee);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,z()},T=M=>(s=M,q),A=M=>(d=M,q),I=()=>(h="json",q),E=()=>{if(!u){if(--l>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},x=M=>(p=M,q),z=()=>{c=ve(),n=new i,n.open("get",a);let M=0,ee,V=0,pe=()=>((0,ut.assertNonNullable)(c),Math.max(c,Math.max(ee||0,V||0)));if(s&&n.addEventListener("progress",L=>{let J=ve();s.updateChunk&&L.loaded>M&&(s.updateChunk(pe(),L.loaded-M),M=L.loaded,ee=J)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;(0,ut.assertNonNullable)(n);let L=n.status;if(L>=200&&L<300){if(n.response.byteLength&&s){let J=n.response.byteLength-M;J&&s.updateChunk&&s.updateChunk(pe(),J)}n.responseType==="json"&&!Object.values(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),p){let L=()=>{(0,ut.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(V=ve(),n.removeEventListener("readystatechange",L))};n.addEventListener("readystatechange",L)}return n.responseType=h,n.send(),q},q={withBitrateReporting:T,withParallel:x,withJSONResponse:I,withRetryCount:M=>(l=M,q),withRetryInterval:(M,ee)=>((0,ut.isNonNullable)(M)&&(g=M),(0,ut.isNonNullable)(ee)&&(m=ee),q),withTimeout:M=>(o=M,q),withFinally:A,send:z,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return q}var Ei=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var xi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ve(),i=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=ve()-r,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=Rr(t,s,()=>i("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=ve()}_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=ve();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var ls=1e4,zo=3;var Vx=6e4,_x=10,Nx=1,Fx=500,Pi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new Ei(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Qo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Qo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,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)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ve.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Kf(i,"progress",()=>{i.buffered.length?(i.currentTime=i.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 xi(zo,ls,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let E=s&&(!c||c===this.rep);return E||t("Not running!"),E},p=(E,x,z)=>{u&&u.abort(),u=Rr(this.urlResolver.resolve(E,!1),x,z,()=>this._retryCallback()).withTimeout(ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount(zo).withFinally(()=>{u=null}).send()},h=(E,x,z)=>{(0,Ve.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),x,z,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let x=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${x}=>${E}`),r.playbackRate=E)},g=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let z=ve()-1e4,Y=0;for(let W=0;W<this.bufferStates.length;W++){let Z=this.bufferStates[W];E=Math.min(E,Z.buf),Z.ts<z&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${E} drop=${Y} jitter=${this.sourceJitter}`);let ie=E-Nx;this.sourceJitter>=0?ie-=this.sourceJitter/2:this.sourceJitter-=1,ie>3?m(1.15):ie>1?m(1.1):ie>.3?m(1.05):m(1)}},T=E=>{let x,z=()=>x&&x.start?x.start.length:0,Y=L=>x.start[L]/1e3,ie=L=>x.dur[L]/1e3,W=L=>x.fragIndex+L,Z=(L,J)=>({chunkIdx:W(L),startTS:Y(L),dur:ie(L),discontinuity:J}),q=()=>{let L=0;if(x&&x.dur){let J=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ae=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ue=J;this.sourceJitter>1&&(ue+=this.sourceJitter-1);let fe=x.dur.length-1;for(;fe>=0&&(ue-=x.dur[fe],!(ue<=0));--fe);L=Math.min(fe,x.dur.length-1-ae),L=Math.max(L,0)}return Z(L,!0)},M=L=>{let J=z();if(!(J<=0)){if((0,Ve.isNonNullable)(L)){for(let ae=0;ae<J;ae++)if(Y(ae)>L)return Z(ae)}return q()}},ee=L=>{let J=z(),ae=L?L.chunkIdx+1:0,ue=ae-x.fragIndex;if(!(J<=0)){if(!L||ue<0||ue-J>_x)return t(`Resync: offset=${ue} bChunks=${J} chunk=`+JSON.stringify(L)),q();if(!(ue>=J))return Z(ae-x.fragIndex,!1)}},V=(L,J,ae)=>{l&&l.abort(),l=Rr(this.urlResolver.resolve(L,!0,this.lowLatency),J,ae,()=>this._retryCallback()).withTimeout(ls).withRetryCount(zo).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(L,J)=>{V(E,ae=>{if(!d())return;x=ae;let ue=!!x.lowLatency;ue!==this.lowLatency&&g(ue);let fe=0;for(let Ne=0;Ne<x.dur.length;++Ne)fe+=x.dur[Ne];fe>0&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(fe/x.dur.length)),i({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,L(M(J))},()=>this._handleNetworkError())},nextChunk:ee}},A=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:x,logger:z}=this.params,Y=T(e.jidxUrl),ie,W,Z,q,M=0,ee,V,pe,L=()=>{ee&&(clearTimeout(ee),ee=void 0);let K=Math.max(Fx,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),me=M+K,F=ve(),xe=Math.min(1e4,me-F);M=F;let Qe=()=>{l||d()&&Y.seek(()=>{d()&&(M=ve(),J(),L())})};xe>0?ee=window.setTimeout(()=>{this.paused?L():Qe()},xe):Qe()},J=()=>{let K;for(;K=Y.nextChunk(q);)q=K,Vt(K);let me=Y.nextChunk(Z);if(me){if(Z&&me.discontinuity){z("Detected discontinuity; restarting playback"),this.paused?L():(A(),this._initPlayerWith(e));return}Ne(me)}else L()},ae=(K,me)=>{if(!d()||!this.sourceBuffer)return;let F,xe,Qe,dt=Rt=>{window.setTimeout(()=>{d()&&ae(K,me)},Rt)};if(this.sourceBuffer.updating)z("Source buffer is updating; delaying appendBuffer"),dt(100);else{let Rt=ve(),_t=x.currentTime;!this.paused&&x.buffered.length>1&&V===_t&&Rt-pe>500&&(z("Stall suspected; trying to fix"),this._fixupStall()),V!==_t&&(V=_t,pe=Rt);let ur=this._getBufferSizeSec();if(ur>30)z(`Buffered ${ur} seconds; delaying appendBuffer`),dt(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:Rt,buf:ur}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),me&&me()}catch(Ur){if(Ur.name==="QuotaExceededError")z("QuotaExceededError; delaying appendBuffer"),Qe=this.sourceBuffer.buffered.length,Qe!==0&&(F=this.sourceBuffer.buffered.start(0),xe=_t,xe-F>4&&this.sourceBuffer.remove(F,xe-3)),dt(1e3);else throw Ur}}},ue=()=>{W&&ie&&(z([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(Z)]),ae(W,function(){W=null,J()}))},fe=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),Ne=K=>{d()&&h(fe(K),(me,F)=>{if(d()){if(F/=1e3,W=me,Z=K,n=K.startTS,F){let xe=Math.min(10,K.dur/F);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}ue()}},()=>this._handleNetworkError())},Vt=K=>{d()&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(fe(K),!1)))},kt=K=>{d()&&(e.cachedHeader=K,ae(K,()=>{ie=!0,ue()}))};s=!0,Y.seek(K=>{if(d()){if(M=ve(),!K){L();return}q=K,!(0,Ve.isNullable)(E)||K.startTS>E?Ne(K):(Z=K,J())}},E),e.cachedHeader?kt(e.cachedHeader):p(e.headerUrl,kt,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Ve.isNonNullable)(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ve.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ve.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/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(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=ve();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Wo(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ve();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Rr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ls).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;$e(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.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):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Vx))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var oe=require("@vkontakte/videoplayer-shared"),Ko=class{constructor(){this.onDroopedVideoFramesLimit$=new oe.Subject;this.subscription=new oe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new oe.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,oe.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,oe.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,oe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,oe.interval)(this.droppedFramesChecker.checkTime).pipe((0,oe.filter)(()=>this.playing),(0,oe.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,oe.debounce)(this.droppedFramesChecker.checkTime)),r=(0,oe.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,oe.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},cs=Ko;var ds=require("@vkontakte/videoplayer-shared"),Jf=require("@vkontakte/videoplayer-shared");var Ai=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var qx=(a,e)=>new ds.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ai()))},_(_({},r),e));i.observe(a);let s=(0,Jf.fromEvent)(document,"visibilitychange").pipe((0,ds.map)(n=>!document.hidden||Ai())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ge=qx;var Ux=["paused","playing","ready"],Hx=["paused","playing","ready"],wi=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new j("stopped");this.representations$=new B.ValueSubject([]);this.textTracksManager=new je;this.droppedFramesManager=new cs;this.maxSeekBackTime$=new B.ValueSubject(1/0);this.zeroTime$=new B.ValueSubject(void 0);this.liveOffset=new gt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:B.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Dt(u.name))!=null?r:(0,B.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p=_({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,B.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Hx.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Ux.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ye(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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(ye(this.params.source.url,u))}return;default:return(0,B.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:B.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,B.merge)(this.videoState.stateChangeStarted$.pipe((0,B.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,B.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Le(this.video);this.subscription.add(this.representations$.pipe((0,B.map)(i=>i.map(({track:s})=>s)),(0,B.filter)(i=>!!i.length),(0,B.once)()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,B.filterChanged)(),(0,B.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,B.combine)({zeroTime:this.zeroTime$.pipe((0,B.filter)(B.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Re(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(He(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ge(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,B.videoQualityToHeight)(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.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":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,B.assertNever)(i.to)}},t)).add((0,B.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ke(this.video)}createLiveDashPlayer(){let e=new Pi({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(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,B.isNonNullable)(t)?t:Ot(e.map(({track:g})=>g),{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=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,B.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;(0,B.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ye(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Xf=wi;var yt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var C=require("@vkontakte/videoplayer-shared");var ps=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];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}},Lr=class extends ps{constructor(){super(),this.listeners||ps.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)}},ki=class{constructor(){Object.defineProperty(this,"signal",{value:new Lr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ki.prototype[Symbol.toStringTag]="AbortController",Lr.prototype[Symbol.toStringTag]="AbortSignal");function hs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Jo(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!hs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ri=hs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Zf=Ri?Jo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Tt=Ri?Zf.fetch:window.fetch,T$=Ri?Zf.Request:window.Request,It=Ri?ki:window.AbortController,I$=Ri?Lr:window.AbortSignal;var pm=Ke(yi(),1);var Et=()=>window.ManagedMediaSource||window.MediaSource,fs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},em=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},tm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var lt=require("@vkontakte/videoplayer-shared");var Ye=document.createElement("video"),Yx='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Wx='video/mp4; codecs="hev1.1.6.L93.B0"',hm='video/webm; codecs="vp09.00.10.08"',fm='video/webm; codecs="av01.0.00M.08"',Qx='audio/mp4; codecs="mp4a.40.2"',zx='audio/webm; codecs="opus"',rm,im,Jt={mms:fs(),mse:em(),hls:!!((rm=Ye.canPlayType)!=null&&rm.call(Ye,"application/x-mpegurl")||(im=Ye.canPlayType)!=null&&im.call(Ye,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},am,sm,Me={mp4:!!((am=Ye.canPlayType)!=null&&am.call(Ye,"video/mp4")),webm:!!((sm=Ye.canPlayType)!=null&&sm.call(Ye,"video/webm")),cmaf:!0},bs,nm,gs,om,Ss,um,vs,lm,ys,cm,Ts,dm,Ce={h264:!!((nm=(bs=Et())==null?void 0:bs.isTypeSupported)!=null&&nm.call(bs,Yx)),h265:!!((om=(gs=Et())==null?void 0:gs.isTypeSupported)!=null&&om.call(gs,Wx)),vp9:!!((um=(Ss=Et())==null?void 0:Ss.isTypeSupported)!=null&&um.call(Ss,hm)),av1:!!((lm=(vs=Et())==null?void 0:vs.isTypeSupported)!=null&&lm.call(vs,fm)),aac:!!((cm=(ys=Et())==null?void 0:ys.isTypeSupported)!=null&&cm.call(ys,Qx)),opus:!!((dm=(Ts=Et())==null?void 0:Ts.isTypeSupported)!=null&&dm.call(Ts,zx))},$r=(Ce.h264||Ce.h265)&&Ce.aac,Xt,Kx=()=>D(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(X(_({},a),{video:X(_({},a.video),{contentType:fm})})),window.navigator.mediaCapabilities.decodingInfo(X(_({},a),{video:X(_({},a.video),{contentType:hm})}))]);Xt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Kx()}catch(a){console.error(a)}var Mr=Jt.hls&&Me.mp4,mm=()=>Object.keys(Ce).filter(a=>Ce[a]),bm=(a,e=!1,t=!1)=>{let r=Jt.mse||Jt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&Me.mp4&&$r;case"DASH_WEBM":return r&&Me.webm&&Ce.vp9&&Ce.opus;case"DASH_WEBM_AV1":return r&&Me.webm&&Ce.av1&&Ce.opus;case"DASH_STREAMS":return r&&(Me.mp4&&$r||Me.webm&&(Ce.vp9||Ce.av1)&&(Ce.opus||Ce.aac));case"DASH_LIVE":return Jt.mse&&Me.mp4&&$r;case"DASH_LIVE_CMAF":return r&&Me.mp4&&$r&&Me.cmaf;case"DASH_ONDEMAND":return r&&Me.mp4&&$r;case"HLS":case"HLS_ONDEMAND":return Mr||e&&Jt.mse&&Me.mp4&&$r;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Mr;case"MPEG":return Me.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Jt.webrtc&&Jt.ws&&Ce.h264&&(Me.mp4||Me.webm);default:return(0,lt.assertNever)(i)}})},ms=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Xt?Xt[t].smooth?[t,e]:Xt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Xt?Xt[t].powerEfficient?[t,e]:Xt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,lt.assertNever)(a)}return[e,t]},gm=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ms(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(lt.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...ms(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ms(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ms(a),...i,"HLS","HLS_ONDEMAND"];default:(0,lt.assertNever)(e)}return Mr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Sm=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=lt.clientChecker.isMac&&lt.clientChecker.isSafari;if(lt.clientChecker.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,lt.assertNever)(a)}else Mr&&!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"]},Xo=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],vm=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,pm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};var Cr=require("@vkontakte/videoplayer-shared"),ym=a=>{if(!a)return{id:"EmptyResponse",category:Cr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Cr.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Cr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Cr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Cr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Li=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var Nr=Ke(yi(),1);var Jx=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},Xx=a=>window.clearTimeout(a),Tm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Zo=Tm?Jx:window.requestIdleCallback,O$=Tm?Xx:window.cancelIdleCallback;var ob=Ke(ss(),1);var We=require("@vkontakte/videoplayer-shared");var Zx=16,Im=!1;try{Im=We.clientChecker.isSafari&&!!We.clientChecker.macVersion&&We.clientChecker.macVersion<=Zx}catch(a){console.error(a)}var eu=class{constructor(e){this.bufferFull$=new We.Subject;this.error$=new We.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:We.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return D(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return D(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return D(this,null,function*(){return new Promise(t=>{let r;Im&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:We.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,We.assertNever)(t)}}},Em=eu;var tu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var P=require("@vkontakte/videoplayer-shared");var te=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=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,i),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 i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Dr=class extends te{};var $i=class extends te{};var Mi=class extends te{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var Ci=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Oi=class extends te{constructor(e,t){super(e,t),this.data=this.content}};var de=class extends te{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Zt=class extends de{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Bi=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends de{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 Ni=class extends de{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Fi=class extends de{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var qi=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends de{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 Hi=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends de{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Yi=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Wi=class extends de{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 Qi=class extends de{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var zi=class extends de{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)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 tP={ftyp:Mi,moov:Ci,moof:Di,mdat:Oi,sidx:Zt,trak:Bi,mdia:qi,mfhd:Gi,tkhd:Ui,traf:Yi,tfhd:Wi,tfdt:Qi,trun:zi,minf:Hi,sv3d:Vi,st3d:_i,prhd:Ni,proj:ji,equi:Fi,uuid:$i,unknown:Dr},er=class a{constructor(e={}){this.options=_({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=tP[e];return r?new r(t,new a):new Dr(t,new a)}};var Or=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),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 iP=new TextDecoder("ascii"),aP=a=>iP.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",sP=a=>{let e=new Zt(a,new er),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},nP=(a,e)=>{let r=new er().parse(a),i=new Or(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},oP=(a,e)=>{let r=new er().parse(a),s=new Or(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},uP=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new er().parse(a),i=new Or(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.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},xm={validateData:aP,parseInit:uP,getIndexRange:()=>{},parseSegments:sP,parseFeedableSegmentChunk:nP,getSegmentEndTime:oP};var xt=require("@vkontakte/videoplayer-shared");var Am=require("@vkontakte/videoplayer-shared");var Pm={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"}},wm=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Ki(a,t),i=r in Pm,s=i?Pm[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Ki(u),d=l*at(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Ki=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*at(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*at(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*at(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},tt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ki(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,Am.assertNever)(e)}},tr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=wm(r);if(!e(i))return;i.type==="master"&&tr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},km=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=wm(a);return tr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=tt(o,n):s===17026?t=tt(o,n):s===17029&&(r=tt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Rm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],lP=[231,22612,22743,167,171,163,160,175],cP=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return tr(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let S=tt(m,h);l=Ki(S)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=tt(m,h):p===17545?i=tt(m,h):p===21420&&l===475249515?u=tt(m,h):p===374648427?tr(m,({tag:S,type:T,value:A})=>S===30321?(c=tt(A,T)===1,!1):!0):s&&n&&Rm.includes(p)&&(o=!0),!o}),(0,xt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,xt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,xt.assertNonNullable)(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},dP=a=>{if((0,xt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},pP=(a,e)=>{let t=!1,r=!1,i=o=>(0,xt.isNonNullable)(o.time)&&(0,xt.isNonNullable)(o.position),s=[],n;return tr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=tt(l,u));break;case 183:break;case 241:n&&(n.position=tt(l,u));break;default:t&&Rm.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},hP=a=>{let e=0,t=!1;try{tr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):lP.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Lm={validateData:km,parseInit:cP,getIndexRange:dP,parseSegments:pP,parseFeedableSegmentChunk:hP};var Br=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Lm;case"mp4":return xm}}throw new ReferenceError(`Unsupported mime type ${a}`)};var lu=Ke(Xm(),1);var uu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var _r=require("@vkontakte/videoplayer-shared");var Zm=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var eb=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},rr=(a,e)=>{let t=a;t=(0,lu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,lu.default)(t,n,(o,u)=>(0,_r.isNullable)(s)?o:(0,_r.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},rb=(a,e)=>{var E,x,z,Y,ie,W,Z,q,M,ee,V,pe,L,J,ae,ue,fe,Ne,Vt,kt,K,me,F,xe,Qe,dt,Rt,_t,ur,Ur,Iu,Eu,xu,Pu,Au,wu,ku,Ru,Lu,$u,Mu,Cu,Du,Ou,Bu,Vu,_u,Nu,Fu,qu;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(z=(x=(E=s.querySelector("BaseURL"))==null?void 0:E.textContent)==null?void 0:x.trim())!=null?z:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=eb(h);else if(m){let Pe=eb(m);(0,_r.isNonNullable)(Pe)&&(p=Pe)}else S&&(p=parseInt(S,10));let T=0,A=(ie=(Y=s.getAttribute("profiles"))==null?void 0:Y.split(","))!=null?ie:[];for(let Pe of u){let Cb=(W=Pe.getAttribute("id"))!=null?W:"id"+(T++).toString(10),Hr=(Z=Pe.getAttribute("mimeType"))!=null?Z:"",Vs=(q=Pe.getAttribute("codecs"))!=null?q:"",_s=(M=Pe.getAttribute("contentType"))!=null?M:Hr==null?void 0:Hr.split("/")[0],Db=(V=(ee=Pe.getAttribute("profiles"))==null?void 0:ee.split(","))!=null?V:[],Ob=(pe=Pe.getAttribute("lang"))!=null?pe:void 0,Bb=(ae=(J=(L=Pe.querySelector("Label"))==null?void 0:L.textContent)==null?void 0:J.trim())!=null?ae:void 0,Vb=Pe.querySelectorAll("Representation"),_b=Pe.querySelector("SegmentTemplate"),Nb=(fe=(ue=Pe.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?fe:void 0,jr=_s,be={id:Cb,language:Ob,isDefault:Nb==="main",label:Bb,codecs:Vs,hdr:jr==="video"&&uu(Vs),mime:Hr,representations:[]};for(let he of Vb){let Fb=(Ne=he.getAttribute("lang"))!=null?Ne:void 0,qb=(Vt=he.getAttribute("label"))!=null?Vt:void 0,Ub=(me=(K=(kt=he.querySelector("BaseURL"))==null?void 0:kt.textContent)==null?void 0:K.trim())!=null?me:"",Ns=new URL(Ub||o,e).toString(),lr=(F=he.getAttribute("mimeType"))!=null?F:Hr,ga=(Qe=(xe=he.getAttribute("codecs"))!=null?xe:Vs)!=null?Qe:"",Fs;if(_s==="text"){let Nt=he.getAttribute("id")||"",qs=Nt.includes("_auto");Fs={id:Nt,isAuto:qs,kind:"text",url:Ns}}else{let Nt=(Rt=(dt=he.getAttribute("contentType"))!=null?dt:lr==null?void 0:lr.split("/")[0])!=null?Rt:_s,qs=(ur=(_t=Pe.getAttribute("profiles"))==null?void 0:_t.split(","))!=null?ur:[],Hb=parseInt((Ur=he.getAttribute("width"))!=null?Ur:"",10),Uu=parseInt((Iu=he.getAttribute("height"))!=null?Iu:"",10),Hu=parseInt((Eu=he.getAttribute("bandwidth"))!=null?Eu:"",10)/1e3,ju=(xu=he.getAttribute("frameRate"))!=null?xu:"",jb=(Pu=he.getAttribute("quality"))!=null?Pu:void 0,Gb=ju?Zm(ju):void 0,Yb=(Au=he.getAttribute("id"))!=null?Au:"id"+(T++).toString(10),Wb=Nt==="video"?`${Uu}p`:Nt==="audio"?`${Hu}Kbps`:ga,Qb=`${Yb}@${Wb}`,zb=[...A,...Db,...qs],Us,Kb=he.querySelector("SegmentBase"),Ft=(wu=he.querySelector("SegmentTemplate"))!=null?wu:_b;if(Kb){let qt=(Ru=(ku=he.querySelector("SegmentBase Initialization"))==null?void 0:ku.getAttribute("range"))!=null?Ru:"",[Ut,js]=qt.split("-").map(cr=>parseInt(cr,10)),Lt={from:Ut,to:js},Gr=(Lu=he.querySelector("SegmentBase"))==null?void 0:Lu.getAttribute("indexRange"),[Gs,Sa]=Gr?Gr.split("-").map(cr=>parseInt(cr,10)):[],Yr=Gr?{from:Gs,to:Sa}:void 0;Us={type:"byteRange",url:Ns,initRange:Lt,indexRange:Yr}}else if(Ft){let qt={representationId:($u=he.getAttribute("id"))!=null?$u:void 0,bandwidth:(Mu=he.getAttribute("bandwidth"))!=null?Mu:void 0},Ut=parseInt((Cu=Ft.getAttribute("timescale"))!=null?Cu:"",10),js=(Du=Ft.getAttribute("initialization"))!=null?Du:"",Lt=Ft.getAttribute("media"),Gr=(Bu=parseInt((Ou=Ft.getAttribute("startNumber"))!=null?Ou:"",10))!=null?Bu:1,Gs=rr(js,qt);if(!Lt)throw new ReferenceError("No media attribute in SegmentTemplate");let Sa=(Vu=Ft.querySelectorAll("SegmentTimeline S"))!=null?Vu:[],Yr=[],cr=0,Ys="",Ws=0;if(Sa.length){let va=Gr,ze=0;for(let dr of Sa){let it=parseInt((_u=dr.getAttribute("d"))!=null?_u:"",10),Ht=parseInt((Nu=dr.getAttribute("r"))!=null?Nu:"",10)||0,ya=parseInt((Fu=dr.getAttribute("t"))!=null?Fu:"",10);ze=Number.isFinite(ya)?ya:ze;let Qs=it/Ut*1e3,zs=ze/Ut*1e3;for(let Ta=0;Ta<Ht+1;Ta++){let Xb=rr(Lt,X(_({},qt),{segmentNumber:va.toString(10),segmentTime:(ze+Ta*it).toString(10)})),Gu=(zs!=null?zs:0)+Ta*Qs,Zb=Gu+Qs;va++,Yr.push({time:{from:Gu,to:Zb},url:Xb})}ze+=(Ht+1)*it,cr+=(Ht+1)*Qs}Ws=ze/Ut*1e3,Ys=rr(Lt,X(_({},qt),{segmentNumber:va.toString(10),segmentTime:ze.toString(10)}))}else if((0,_r.isNonNullable)(p)){let ze=parseInt((qu=Ft.getAttribute("duration"))!=null?qu:"",10)/Ut*1e3,dr=Math.ceil(p/ze),it=0;for(let Ht=1;Ht<dr;Ht++){let ya=rr(Lt,X(_({},qt),{segmentNumber:Ht.toString(10),segmentTime:it.toString(10)}));Yr.push({time:{from:it,to:it+ze},url:ya}),it+=ze}Ws=it,Ys=rr(Lt,X(_({},qt),{segmentNumber:dr.toString(10),segmentTime:it.toString(10)}))}let Jb={time:{from:Ws,to:1/0},url:Ys};Us={type:"template",baseUrl:Ns,segmentTemplateUrl:Lt,initUrl:Gs,totalSegmentsDurationMs:cr,segments:Yr,nextSegmentBeyondManifest:Jb,timescale:Ut}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Nt||!lr)continue;let Hs={video:"video",audio:"audio",text:"text"}[Nt];if(!Hs)continue;jr||(jr=Hs),Fs={id:Qb,kind:Hs,segmentReference:Us,profiles:zb,duration:p,bitrate:Hu,mime:lr,codecs:ga,width:Hb,height:Uu,fps:Gb,quality:jb}}be.language||(be.language=Fb),be.label||(be.label=qb),be.mime||(be.mime=lr),be.codecs||(be.codecs=ga),be.hdr||(be.hdr=jr==="video"&&uu(ga)),be.representations.push(Fs)}jr&&i[jr].push(be)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:i}};var Ji=Ke(yi(),1);var ib=require("@vkontakte/videoplayer-shared"),ab=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?Dt(s):void 0)!=null?o:(0,ib.videoSizeToQuality)({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},sb=({id:a,bitrate:e})=>({id:a,bitrate:e}),Is=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Ji.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Ji.default)(t,-1)},nb=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),du=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ji.default)(r.split("."),0),isDefault:i}),pu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ji.default)(i.split("."),0)}),Es=a=>"url"in a,ir=a=>a.type==="template",Xi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Zi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new P.ValueSubject(0);this.onLastSegment$=new P.ValueSubject(!1);this.fullyBuffered$=new P.ValueSubject(!1);this.playingRepresentation$=new P.ValueSubject(void 0);this.playingRepresentationInit$=new P.ValueSubject(void 0);this.error$=new P.Subject;this.gaps=[];this.subscription=new P.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new It;this.destroyAbortController=new It;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,P.abortable)(this.destroyAbortController.signal,function(e){return ge(this,null,function*(){let t=this.representations.get(e);(0,P.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Em(this.sourceBuffer),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,tu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=yt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,l<c)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,P.assertNonNullable)(r,"No init buffer for starting representation"),(0,P.assertNonNullable)(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,P.abortable)(this.destroyAbortController.signal,function(e,t=!1){return ge(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,P.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,P.isNullable)(s)||(0,P.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,P.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,P.isNonNullable)(n)&&(this.isLive||(i.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,P.abortable)(this.destroyAbortController.signal,function(e){return ge(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!ir(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);(0,P.assertNonNullable)(i);let s=this.segments.get(r);(0,P.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,P.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new It,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if((0,P.isNullable)(e)||(0,P.isNullable)(this.downloadingRepresentationId)||(0,P.isNullable)(this.playingRepresentationId)||(0,P.isNullable)(this.sourceBuffer)||!(0,P.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,P.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=yt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&tu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=yt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,Nr.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&yt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Nr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,P.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!ir(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>X(_({},p),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Nr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(c)>=Math.floor(p.time.from)&&Math.floor(c)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,P.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!ir(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=rr(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&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(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let g=p<=r&&h>=r,S=p>r||g||m===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&S&&A&&this.sourceBuffer&&!Li(this.sourceBuffer.buffered,r))&&S&&A});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];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}loadSegments(e,t,r="auto"){return D(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return D(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,P.abortable)(o,function(){return ge(this,null,function*(){let c=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Br(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Xi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return D(this,null,function*(){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:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,P.abortable)(n,function(){return ge(this,null,function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,P.fromEvent)(window,"online").pipe((0,P.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Xi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(ir(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Nr.default)(e,0).byte.from,to:(0,Nr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ir(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return D(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){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){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Br(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,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 c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let g=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,T=g<i,A=S<=i;if(d.status==="downloading"&&T&&A){d.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+g,h);this.sourceBufferTaskQueue.append(I,s).then(E=>E&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(h,i-g),c.loadedBytes>c.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+g+c.feedingBytes,c.loadedBytes-c.feedingBytes),E=c.loadedBytes===h?I:Br(o.mime).parseFeedableSegmentChunk(I);E!=null&&E.byteLength&&(d.status="partially_fed",c.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,s).then(x=>{if(s.aborted)n();else if(x)c.fedBytes+=E.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return D(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,m=d<i,g=p<=i;if(m){if(c.status==="downloading"&&g){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===h?S:Br(u.mime).parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(c.status="partially_fed",l.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(l.fedBytes+=T.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}}})}onSegmentFullyAppended(e,t){var r;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 s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Zo(()=>(0,ob.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return D(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,P.abortable)(this.destroyAbortController.signal,function(){return ge(this,null,function*(){let o=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Br(e.mime),i)).then(o=>D(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&ir(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),r&&this.error$.next({id:"LoadInits",category:P.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return D(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return D(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return D(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,P.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(u.time),i=n(i);let l=Es(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}pruneBufferOld(e,t,r=!1){return D(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,P.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=Es(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;i+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=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(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Zo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||(0,P.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=1;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ea=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var ub=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};var se=require("@vkontakte/videoplayer-shared");var xs=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new se.ValueSubject(void 0);this.lastConnectionReused$=new se.ValueSubject(void 0);this.lastRequestFirstBytes$=new se.ValueSubject(void 0);this.abortAllController=new It;this.subscription=new se.Subscription;this.fetchManifest=(0,se.abortable)(this.abortAllController.signal,function(e){return ge(this,null,function*(){let t=e;this.requestQuic&&(t=ea(t));let r=yield Tt(t,{signal:this.abortAllController.signal}).catch(ta);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=(0,se.abortable)(this.abortAllController.signal,function(l){return ge(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var W,Z;let c=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let q=new URL(c,location.href);q.searchParams.append("bytes",`${r.from}-${r.to}`),c=q.toString();break}default:(0,se.assertNever)(t)}this.requestQuic&&(c=ea(c));let p=this.abortAllController.signal,h;if(n){let q=new It;if(h=(0,se.merge)((0,se.fromEvent)(this.abortAllController.signal,"abort"),(0,se.fromEvent)(n,"abort")).subscribe(()=>{try{q.abort()}catch(M){ta(M)}}),this.abortAllController.signal.aborted||n.aborted)try{q.abort()}catch(M){ta(M)}p=q.signal}let m=(0,se.now)(),g=yield Tt(c,{priority:s,headers:d,signal:p}).catch(ta),S=(0,se.now)();if(!g)return h==null||h.unsubscribe(),null;if((W=this.throughputEstimator)==null||W.addRawRtt(S-m),!g.ok||!g.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!i&&!o)return h==null||h.unsubscribe(),g.arrayBuffer();let[T,A]=g.body.tee(),I=T.getReader();o&&((Z=this.throughputEstimator)==null||Z.trackStream(A,u));let E=0,x=new Uint8Array(0),z=!1,Y=q=>{h==null||h.unsubscribe(),z=!0,ta(q)},ie=(0,se.abortable)(p,function(ee){return ge(this,arguments,function*({done:q,value:M}){if(E===0&&this.lastRequestFirstBytes$.next((0,se.now)()-m),p.aborted){h==null||h.unsubscribe();return}if(!q&&M){let V=new Uint8Array(x.length+M.length);V.set(x),V.set(M,x.length),x=V,E+=M.byteLength,i==null||i(new DataView(x.buffer),E),yield I==null?void 0:I.read().then(ie,Y)}})}.bind(this));return yield I==null?void 0:I.read().then(ie,Y),h==null||h.unsubscribe(),z?null:x.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,se.abortable)(this.abortAllController.signal,function(e,t,r){return ge(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(T=e.indexRange)!=null?T:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let A=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!A)return null;g=new DataView(A)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,se.abortable)(this.abortAllController.signal,function(e,t){return ge(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>X(_({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=ub(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return D(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,se.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},ta=a=>{if(!Xi(a))throw a};var ar=(a,e,t)=>t*e+(1-t)*a,hu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,lb=(a,e,t,r)=>{let i=0,s=t,n=hu(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};var ra=require("@vkontakte/videoplayer-shared");var Bt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ra.ValueSubject(e.initial),this.debounced$=new ra.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ee(`raw_${t}`),this.smoothedSeries$=new Ee(`smoothed_${t}`),this.reportedSeries$=new Ee(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=at(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,ra.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Ps=class extends Bt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ar(this.slow,e,this.params.emaAlphaSlow),this.fast=ar(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var As=class extends Bt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=hu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ar(this.emaSmoothed,e,this.params.emaAlpha);let r=lb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var ws=class extends Bt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?ar(this.smoothed,t,this.params.emaAlpha):t}};var sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ps({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new As({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ws(_({initial:e,label:"liveEdgeDelay"},t))}};var fu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var db=["timeupdate","progress","play","seeked","stalled","waiting"];var ks=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new j("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.isLive$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new v.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new It;this.initManifest=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return ge(this,null,function*(){var i;this.element=e,this.manifestUrlString=ye(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,function(){return ge(this,null,function*(){var s,n;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t;try{t=rb(e!=null?e:"",this.manifestUrlString)}catch(o){let u=(s=ym(e))!=null?s:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(u)}if(!t)return null;let r=(o,u,l)=>{var c,d,p,h;return!!((d=(c=this.element)==null?void 0:c.canPlayType)!=null&&d.call(c,u)&&((h=(p=Et())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${l}"`))||o==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((n=t.duration)!=null?n:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:p,codecs:h})=>r(o,p,h)),c=new Set(l.map(({codecs:p})=>p)),d=vm(c);if(d&&(i[o]=l.filter(({codecs:p})=>p.startsWith(d))),o==="video"){let p=this.tuning.preferHDR,h=i.video.some(g=>g.hdr),m=i.video.some(g=>!g.hdr);v.clientChecker.isHDR&&p&&h?i.video=i.video.filter(g=>g.hdr):m&&(i.video=i.video.filter(g=>!g.hdr))}}return X(_({},t),{streams:i})})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return ge(this,null,function*(){var d;(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?tm():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&fs())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}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((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Zi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Zi("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,v.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=_o(this.manifestUrlString,2);this.manifestUrlString=ye(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add((0,v.merge)(...db.filter(p=>p!=="waiting").map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?yt(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.filter)(p=>!!p),(0,v.tap)(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,v.filterChanged)()).subscribe(h=>fu(this.element,1))),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,v.filter)(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add((0,v.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:m})=>{if(!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,A=h-g,I=1;Math.abs(A)>S&&(I=1+Math.sign(A)*T),fu(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let T=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var E,x;return(x=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?x:T}))-T}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(g=>D(this,[g],function*({liveLoadBufferLength:h,bufferLength:m}){if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,T=_o(this.manifestUrlString,2),A=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(A,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,z=isFinite(h)?h:m,Y=this.isActiveLowLatency$.getValue(),ie=A<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(Y&&ie);let W="none";if(Y?W="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&ie?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(Z=>Z.proceedLowLatencyLive()),W="active_low_latency"):T!==0&&z<I?W="live_forward_buffering":z<I+x&&(W="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),W==="live_forward_buffering"||W==="live_with_target_offset"){let Z=p-(I+E),q=this.normolizeLiveOffset(Math.trunc(T+Z/S)),M=Math.abs(q-T),ee;!h||M<=this.tuning.dashCmafLive.offsetCalculationError?ee=T:q>0&&M>this.tuning.dashCmafLive.offsetCalculationError?ee=q:ee=0,this.manifestUrlString=ye(this.manifestUrlString,ee,2)}W!=="none"&&W!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=(0,v.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=(0,v.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:u,someBufferEnded:l}).pipe((0,v.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let c=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{var h;return(h=p.duration)!=null?h:0})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")})}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new xs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=sr.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,_({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return D(this,null,function*(){var r,i,s,n;(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ye(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...db.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Li(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var r,i;if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let s=this.element.currentTime*1e3;(r=this.videoBufferManager)==null||r.maintain(s),(i=this.audioBufferManager)==null||i.maintain(s)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return D(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Li(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return D(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],i=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-i<=t&&n.to+i>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var Rs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ls=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/at(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=_({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*at(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var pb=`attribute vec2 a_vertex;
33
+ [best track] ${Y==null?void 0:Y.quality}
34
+ [selected track] ${U==null?void 0:U.quality}
35
+ `});let W=U&&l&&l.history[U.id]&&(0,G.now)()-l.history[U.id]<=r.trackCooldown&&(!l.last||U.id!==l.last.id);if(U!=null&&U.id&&l&&!W&&l.recordSelection(U),W&&(l!=null&&l.last)){let B=l.last;return l==null||l.recordSwitch(B),d({message:`
36
+ [last selected] ${B==null?void 0:B.quality}
37
+ `}),B}return l==null||l.recordSwitch(U),U},Dt=$x;var ge=a=>new URL(a).hostname;var O=require("@vkontakte/videoplayer-shared");var Uf=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Le=a=>D(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!Uf(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return Uf(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});var Ve=require("@vkontakte/videoplayer-shared");var ot=require("@vkontakte/videoplayer-shared");function Se(){return(0,ot.now)()}function Go(a){return Se()-a}function Yo(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(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 Hf(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function kr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,ot.assertNonNullable)(c);let M=Go(c),te;if(M<g){te=g-M,setTimeout(S,te);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,z()},T=M=>(s=M,N),w=M=>(d=M,N),I=()=>(h="json",N),x=()=>{if(!u){if(--l>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},E=M=>(p=M,N),z=()=>{c=Se(),n=new i,n.open("get",a);let M=0,te,ue=0,B=()=>((0,ot.assertNonNullable)(c),Math.max(c,Math.max(te||0,ue||0)));if(s&&n.addEventListener("progress",k=>{let J=Se();s.updateChunk&&k.loaded>M&&(s.updateChunk(B(),k.loaded-M),M=k.loaded,te=J)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(u)return;(0,ot.assertNonNullable)(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let J=n.response.byteLength-M;J&&s.updateChunk&&s.updateChunk(B(),J)}n.responseType==="json"&&!Object.values(n.response).length?x():(d&&d(),e(n.response))}else x()}),n.addEventListener("error",()=>{x()}),p){let k=()=>{(0,ot.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ue=Se(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),N},N={withBitrateReporting:T,withParallel:E,withJSONResponse:I,withRetryCount:M=>(l=M,N),withRetryInterval:(M,te)=>((0,ot.isNonNullable)(M)&&(g=M),(0,ot.isNonNullable)(te)&&(m=te),N),withTimeout:M=>(o=M,N),withFinally:w,send:z,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return N}var Ti=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ii=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Se(),i=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=Se()-r,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=kr(t,s,()=>i("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=Se()}_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=Se();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var os=1e4,Wo=3;var Cx=6e4,Dx=10,Ox=1,Bx=500,Ei=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new Ti(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Yo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Yo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,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)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ve.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Hf(i,"progress",()=>{i.buffered.length?(i.currentTime=i.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 Ii(Wo,os,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let x=s&&(!c||c===this.rep);return x||t("Not running!"),x},p=(x,E,z)=>{u&&u.abort(),u=kr(this.urlResolver.resolve(x,!1),E,z,()=>this._retryCallback()).withTimeout(os).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Wo).withFinally(()=>{u=null}).send()},h=(x,E,z)=>{(0,Ve.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),E,z,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=x=>{let E=r.playbackRate;r.playbackRate!==x&&(t(`Playback rate switch: ${E}=>${x}`),r.playbackRate=x)},g=x=>{this.lowLatency=x,t(`lowLatency changed to ${x}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let x=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let z=Se()-1e4,Y=0;for(let W=0;W<this.bufferStates.length;W++){let ee=this.bufferStates[W];x=Math.min(x,ee.buf),ee.ts<z&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${x} drop=${Y} jitter=${this.sourceJitter}`);let U=x-Ox;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?m(1.15):U>1?m(1.1):U>.3?m(1.05):m(1)}},T=x=>{let E,z=()=>E&&E.start?E.start.length:0,Y=k=>E.start[k]/1e3,U=k=>E.dur[k]/1e3,W=k=>E.fragIndex+k,ee=(k,J)=>({chunkIdx:W(k),startTS:Y(k),dur:U(k),discontinuity:J}),N=()=>{let k=0;if(E&&E.dur){let J=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ae=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,le=J;this.sourceJitter>1&&(le+=this.sourceJitter-1);let fe=E.dur.length-1;for(;fe>=0&&(le-=E.dur[fe],!(le<=0));--fe);k=Math.min(fe,E.dur.length-1-ae),k=Math.max(k,0)}return ee(k,!0)},M=k=>{let J=z();if(!(J<=0)){if((0,Ve.isNonNullable)(k)){for(let ae=0;ae<J;ae++)if(Y(ae)>k)return ee(ae)}return N()}},te=k=>{let J=z(),ae=k?k.chunkIdx+1:0,le=ae-E.fragIndex;if(!(J<=0)){if(!k||le<0||le-J>Dx)return t(`Resync: offset=${le} bChunks=${J} chunk=`+JSON.stringify(k)),N();if(!(le>=J))return ee(ae-E.fragIndex,!1)}},ue=(k,J,ae)=>{l&&l.abort(),l=kr(this.urlResolver.resolve(k,!0,this.lowLatency),J,ae,()=>this._retryCallback()).withTimeout(os).withRetryCount(Wo).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,J)=>{ue(x,ae=>{if(!d())return;E=ae;let le=!!E.lowLatency;le!==this.lowLatency&&g(le);let fe=0;for(let X=0;X<E.dur.length;++X)fe+=E.dur[X];fe>0&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(fe/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,k(M(J))},()=>this._handleNetworkError())},nextChunk:te}},w=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:x=>{let{videoElement:E,logger:z}=this.params,Y=T(e.jidxUrl),U,W,ee,N,M=0,te,ue,B,k=()=>{te&&(clearTimeout(te),te=void 0);let K=Math.max(Bx,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=M+K,Ce=Se(),Ne=Math.min(1e4,Ee-Ce);M=Ce;let At=()=>{l||d()&&Y.seek(()=>{d()&&(M=Se(),J(),k())})};Ne>0?te=window.setTimeout(()=>{this.paused?k():At()},Ne):At()},J=()=>{let K;for(;K=Y.nextChunk(N);)N=K,sr(K);let Ee=Y.nextChunk(ee);if(Ee){if(ee&&Ee.discontinuity){z("Detected discontinuity; restarting playback"),this.paused?k():(w(),this._initPlayerWith(e));return}X(Ee)}else k()},ae=(K,Ee)=>{if(!d()||!this.sourceBuffer)return;let Ce,Ne,At,nr=kt=>{window.setTimeout(()=>{d()&&ae(K,Ee)},kt)};if(this.sourceBuffer.updating)z("Source buffer is updating; delaying appendBuffer"),nr(100);else{let kt=Se(),Bt=E.currentTime;!this.paused&&E.buffered.length>1&&ue===Bt&&kt-B>500&&(z("Stall suspected; trying to fix"),this._fixupStall()),ue!==Bt&&(ue=Bt,B=kt);let or=this._getBufferSizeSec();if(or>30)z(`Buffered ${or} seconds; delaying appendBuffer`),nr(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:kt,buf:or}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(qr){if(qr.name==="QuotaExceededError")z("QuotaExceededError; delaying appendBuffer"),At=this.sourceBuffer.buffered.length,At!==0&&(Ce=this.sourceBuffer.buffered.start(0),Ne=Bt,Ne-Ce>4&&this.sourceBuffer.remove(Ce,Ne-3)),nr(1e3);else throw qr}}},le=()=>{W&&U&&(z([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(ee)]),ae(W,function(){W=null,J()}))},fe=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),X=K=>{d()&&h(fe(K),(Ee,Ce)=>{if(d()){if(Ce/=1e3,W=Ee,ee=K,n=K.startTS,Ce){let Ne=Math.min(10,K.dur/Ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ne:Ne}le()}},()=>this._handleNetworkError())},sr=K=>{d()&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(fe(K),!1)))},wt=K=>{d()&&(e.cachedHeader=K,ae(K,()=>{U=!0,le()}))};s=!0,Y.seek(K=>{if(d()){if(M=Se(),!K){k();return}N=K,!(0,Ve.isNullable)(x)||K.startTS>x?X(K):(ee=K,J())}},x),e.cachedHeader?wt(e.cachedHeader):p(e.headerUrl,wt,()=>this._handleNetworkError())},stop:w,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Ve.isNonNullable)(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ve.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ve.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/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(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=Se();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Go(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=Se();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=kr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(os).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;Le(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.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):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Cx))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var oe=require("@vkontakte/videoplayer-shared"),Qo=class{constructor(){this.onDroopedVideoFramesLimit$=new oe.Subject;this.subscription=new oe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new oe.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,oe.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,oe.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,oe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,oe.interval)(this.droppedFramesChecker.checkTime).pipe((0,oe.filter)(()=>this.playing),(0,oe.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,oe.debounce)(this.droppedFramesChecker.checkTime)),r=(0,oe.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,oe.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},us=Qo;var ls=require("@vkontakte/videoplayer-shared"),jf=require("@vkontakte/videoplayer-shared");var xi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Vx=(a,e)=>new ls.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||xi()))},V(V({},r),e));i.observe(a);let s=(0,jf.fromEvent)(document,"visibilitychange").pipe((0,ls.map)(n=>!document.hidden||xi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ge=Vx;var _x=["paused","playing","ready"],Nx=["paused","playing","ready"],Pi=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new H("stopped");this.representations$=new O.ValueSubject([]);this.textTracksManager=new je;this.droppedFramesManager=new us;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new mt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:O.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Ct(u.name))!=null?r:(0,O.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p=V({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,O.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Nx.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&_x.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ve(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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(ve(this.params.source.url,u))}return;default:return(0,O.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Re(this.video);this.subscription.add(this.representations$.pipe((0,O.map)(i=>i.map(({track:s})=>s)),(0,O.filter)(i=>!!i.length),(0,O.once)()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,O.filterChanged)(),(0,O.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(ke(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(He(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ge(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,O.videoQualityToHeight)(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.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":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,O.assertNever)(i.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}createLiveDashPlayer(){let e=new Ei({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(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,O.isNonNullable)(t)?t:Dt(e.map(({track:g})=>g),{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=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,O.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;(0,O.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ve(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Gf=Pi;var St=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var C=require("@vkontakte/videoplayer-shared");var cs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Rr=class extends cs{constructor(){super(),this.listeners||cs.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)}},wi=class{constructor(){Object.defineProperty(this,"signal",{value:new Rr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(wi.prototype[Symbol.toStringTag]="AbortController",Rr.prototype[Symbol.toStringTag]="AbortSignal");function ds(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function zo(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!ds({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ai=ds({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Yf=Ai?zo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,vt=Ai?Yf.fetch:window.fetch,g$=Ai?Yf.Request:window.Request,yt=Ai?wi:window.AbortController,S$=Ai?Rr:window.AbortSignal;var sm=ze(vi(),1);var Tt=()=>window.ManagedMediaSource||window.MediaSource,ps=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Wf=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Qf=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ut=require("@vkontakte/videoplayer-shared");var Ye=document.createElement("video"),Ux='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Hx='video/mp4; codecs="hev1.1.6.L93.B0"',nm='video/webm; codecs="vp09.00.10.08"',om='video/webm; codecs="av01.0.00M.08"',jx='audio/mp4; codecs="mp4a.40.2"',Gx='audio/webm; codecs="opus"',zf,Kf,Qt={mms:ps(),mse:Wf(),hls:!!((zf=Ye.canPlayType)!=null&&zf.call(Ye,"application/x-mpegurl")||(Kf=Ye.canPlayType)!=null&&Kf.call(Ye,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Jf,Xf,$e={mp4:!!((Jf=Ye.canPlayType)!=null&&Jf.call(Ye,"video/mp4")),webm:!!((Xf=Ye.canPlayType)!=null&&Xf.call(Ye,"video/webm")),cmaf:!0},fs,Zf,ms,em,bs,tm,gs,rm,Ss,im,vs,am,Me={h264:!!((Zf=(fs=Tt())==null?void 0:fs.isTypeSupported)!=null&&Zf.call(fs,Ux)),h265:!!((em=(ms=Tt())==null?void 0:ms.isTypeSupported)!=null&&em.call(ms,Hx)),vp9:!!((tm=(bs=Tt())==null?void 0:bs.isTypeSupported)!=null&&tm.call(bs,nm)),av1:!!((rm=(gs=Tt())==null?void 0:gs.isTypeSupported)!=null&&rm.call(gs,om)),aac:!!((im=(Ss=Tt())==null?void 0:Ss.isTypeSupported)!=null&&im.call(Ss,jx)),opus:!!((am=(vs=Tt())==null?void 0:vs.isTypeSupported)!=null&&am.call(vs,Gx))},Lr=(Me.h264||Me.h265)&&Me.aac,zt,Yx=()=>D(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Z(V({},a),{video:Z(V({},a.video),{contentType:om})})),window.navigator.mediaCapabilities.decodingInfo(Z(V({},a),{video:Z(V({},a.video),{contentType:nm})}))]);zt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Yx()}catch(a){console.error(a)}var $r=Qt.hls&&$e.mp4,um=()=>Object.keys(Me).filter(a=>Me[a]),lm=(a,e=!1,t=!1)=>{let r=Qt.mse||Qt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&$e.mp4&&Lr;case"DASH_WEBM":return r&&$e.webm&&Me.vp9&&Me.opus;case"DASH_WEBM_AV1":return r&&$e.webm&&Me.av1&&Me.opus;case"DASH_STREAMS":return r&&($e.mp4&&Lr||$e.webm&&(Me.vp9||Me.av1)&&(Me.opus||Me.aac));case"DASH_LIVE":return Qt.mse&&$e.mp4&&Lr;case"DASH_LIVE_CMAF":return r&&$e.mp4&&Lr&&$e.cmaf;case"DASH_ONDEMAND":return r&&$e.mp4&&Lr;case"HLS":case"HLS_ONDEMAND":return $r||e&&Qt.mse&&$e.mp4&&Lr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return $r;case"MPEG":return $e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Qt.webrtc&&Qt.ws&&Me.h264&&($e.mp4||$e.webm);default:return(0,ut.assertNever)(i)}})},hs=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return zt?zt[t].smooth?[t,e]:zt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return zt?zt[t].powerEfficient?[t,e]:zt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ut.assertNever)(a)}return[e,t]},cm=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...hs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ut.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...hs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...hs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...hs(a),...i,"HLS","HLS_ONDEMAND"];default:(0,ut.assertNever)(e)}return $r?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},dm=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=ut.clientChecker.isMac&&ut.clientChecker.isSafari;if(ut.clientChecker.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,ut.assertNever)(a)}else $r&&!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"]},Ko=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],pm=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,sm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};var Mr=require("@vkontakte/videoplayer-shared"),hm=a=>{if(!a)return{id:"EmptyResponse",category:Mr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Mr.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Mr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Mr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Mr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var ki=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var _r=ze(vi(),1);var Wx=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},Qx=a=>window.clearTimeout(a),fm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Jo=fm?Wx:window.requestIdleCallback,$$=fm?Qx:window.cancelIdleCallback;var eb=ze(is(),1);var We=require("@vkontakte/videoplayer-shared");var zx=16,mm=!1;try{mm=We.clientChecker.isSafari&&!!We.clientChecker.macVersion&&We.clientChecker.macVersion<=zx}catch(a){console.error(a)}var Xo=class{constructor(e){this.bufferFull$=new We.Subject;this.error$=new We.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:We.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return D(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return D(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return D(this,null,function*(){return new Promise(t=>{let r;mm&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:We.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,We.assertNever)(t)}}},bm=Xo;var Zo=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var P=require("@vkontakte/videoplayer-shared");var re=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=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,i),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 i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}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 Cr=class extends re{};var Ri=class extends re{};var Li=class extends re{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var $i=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ci=class extends re{constructor(e,t){super(e,t),this.data=this.content}};var pe=class extends re{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Kt=class extends pe{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Di=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Oi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends pe{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 Vi=class extends pe{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var _i=class extends pe{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ni=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fi=class extends pe{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 qi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Hi=class extends pe{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ji=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends pe{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 Yi=class extends pe{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Wi=class extends pe{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)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 Jx={ftyp:Li,moov:$i,moof:Mi,mdat:Ci,sidx:Kt,trak:Di,mdia:Ni,mfhd:Hi,tkhd:Fi,traf:ji,tfhd:Gi,tfdt:Yi,trun:Wi,minf:qi,sv3d:Oi,st3d:Bi,prhd:Vi,proj:Ui,equi:_i,uuid:Ri,unknown:Cr},Jt=class a{constructor(e={}){this.options=V({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Jx[e];return r?new r(t,new a):new Cr(t,new a)}};var Dr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),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 Zx=new TextDecoder("ascii"),eP=a=>Zx.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",tP=a=>{let e=new Kt(a,new Jt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},rP=(a,e)=>{let r=new Jt().parse(a),i=new Dr(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},iP=(a,e)=>{let r=new Jt().parse(a),s=new Dr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},aP=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Jt().parse(a),i=new Dr(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.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},gm={validateData:eP,parseInit:aP,getIndexRange:()=>{},parseSegments:tP,parseFeedableSegmentChunk:rP,getSegmentEndTime:iP};var It=require("@vkontakte/videoplayer-shared");var vm=require("@vkontakte/videoplayer-shared");var Sm={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"}},ym=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Qi(a,t),i=r in Sm,s=i?Sm[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Qi(u),d=l*it(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Qi=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*it(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*it(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*it(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},et=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Qi(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,vm.assertNever)(e)}},Xt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=ym(r);if(!e(i))return;i.type==="master"&&Xt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Tm=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=ym(a);return Xt(i.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(r=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Im=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],sP=[231,22612,22743,167,171,163,160,175],nP=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Xt(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let S=et(m,h);l=Qi(S)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=et(m,h):p===17545?i=et(m,h):p===21420&&l===475249515?u=et(m,h):p===374648427?Xt(m,({tag:S,type:T,value:w})=>S===30321?(c=et(w,T)===1,!1):!0):s&&n&&Im.includes(p)&&(o=!0),!o}),(0,It.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,It.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,It.assertNonNullable)(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},oP=a=>{if((0,It.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},uP=(a,e)=>{let t=!1,r=!1,i=o=>(0,It.isNonNullable)(o.time)&&(0,It.isNonNullable)(o.position),s=[],n;return Xt(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=et(l,u));break;case 183:break;case 241:n&&(n.position=et(l,u));break;default:t&&Im.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},lP=a=>{let e=0,t=!1;try{Xt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):sP.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Em={validateData:Tm,parseInit:nP,getIndexRange:oP,parseSegments:uP,parseFeedableSegmentChunk:lP};var Or=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Em;case"mp4":return gm}}throw new ReferenceError(`Unsupported mime type ${a}`)};var ou=ze(Gm(),1);var nu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var Vr=require("@vkontakte/videoplayer-shared");var Ym=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Wm=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Zt=(a,e)=>{let t=a;t=(0,ou.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,ou.default)(t,n,(o,u)=>(0,Vr.isNullable)(s)?o:(0,Vr.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},zm=(a,e)=>{var x,E,z,Y,U,W,ee,N,M,te,ue,B,k,J,ae,le,fe,X,sr,wt,K,Ee,Ce,Ne,At,nr,kt,Bt,or,qr,yu,Tu,Iu,Eu,xu,Pu,wu,Au,ku,Ru,Lu,$u,Mu,Cu,Du,Ou,Bu,Vu,_u,Nu;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(z=(E=(x=s.querySelector("BaseURL"))==null?void 0:x.textContent)==null?void 0:E.trim())!=null?z:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Wm(h);else if(m){let xe=Wm(m);(0,Vr.isNonNullable)(xe)&&(p=xe)}else S&&(p=parseInt(S,10));let T=0,w=(U=(Y=s.getAttribute("profiles"))==null?void 0:Y.split(","))!=null?U:[];for(let xe of u){let wb=(W=xe.getAttribute("id"))!=null?W:"id"+(T++).toString(10),Ur=(ee=xe.getAttribute("mimeType"))!=null?ee:"",Os=(N=xe.getAttribute("codecs"))!=null?N:"",Bs=(M=xe.getAttribute("contentType"))!=null?M:Ur==null?void 0:Ur.split("/")[0],Ab=(ue=(te=xe.getAttribute("profiles"))==null?void 0:te.split(","))!=null?ue:[],kb=(B=xe.getAttribute("lang"))!=null?B:void 0,Rb=(ae=(J=(k=xe.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:J.trim())!=null?ae:void 0,Lb=xe.querySelectorAll("Representation"),$b=xe.querySelector("SegmentTemplate"),Mb=(fe=(le=xe.querySelector("Role"))==null?void 0:le.getAttribute("value"))!=null?fe:void 0,Hr=Bs,me={id:wb,language:kb,isDefault:Mb==="main",label:Rb,codecs:Os,hdr:Hr==="video"&&nu(Os),mime:Ur,representations:[]};for(let he of Lb){let Cb=(X=he.getAttribute("lang"))!=null?X:void 0,Db=(sr=he.getAttribute("label"))!=null?sr:void 0,Ob=(Ee=(K=(wt=he.querySelector("BaseURL"))==null?void 0:wt.textContent)==null?void 0:K.trim())!=null?Ee:"",Vs=new URL(Ob||o,e).toString(),ur=(Ce=he.getAttribute("mimeType"))!=null?Ce:Ur,ma=(At=(Ne=he.getAttribute("codecs"))!=null?Ne:Os)!=null?At:"",_s;if(Bs==="text"){let Vt=he.getAttribute("id")||"",Ns=Vt.includes("_auto");_s={id:Vt,isAuto:Ns,kind:"text",url:Vs}}else{let Vt=(kt=(nr=he.getAttribute("contentType"))!=null?nr:ur==null?void 0:ur.split("/")[0])!=null?kt:Bs,Ns=(or=(Bt=xe.getAttribute("profiles"))==null?void 0:Bt.split(","))!=null?or:[],Bb=parseInt((qr=he.getAttribute("width"))!=null?qr:"",10),Fu=parseInt((yu=he.getAttribute("height"))!=null?yu:"",10),qu=parseInt((Tu=he.getAttribute("bandwidth"))!=null?Tu:"",10)/1e3,Uu=(Iu=he.getAttribute("frameRate"))!=null?Iu:"",Vb=(Eu=he.getAttribute("quality"))!=null?Eu:void 0,_b=Uu?Ym(Uu):void 0,Nb=(xu=he.getAttribute("id"))!=null?xu:"id"+(T++).toString(10),Fb=Vt==="video"?`${Fu}p`:Vt==="audio"?`${qu}Kbps`:ma,qb=`${Nb}@${Fb}`,Ub=[...w,...Ab,...Ns],Fs,Hb=he.querySelector("SegmentBase"),_t=(Pu=he.querySelector("SegmentTemplate"))!=null?Pu:$b;if(Hb){let Nt=(Au=(wu=he.querySelector("SegmentBase Initialization"))==null?void 0:wu.getAttribute("range"))!=null?Au:"",[Ft,Us]=Nt.split("-").map(lr=>parseInt(lr,10)),Rt={from:Ft,to:Us},jr=(ku=he.querySelector("SegmentBase"))==null?void 0:ku.getAttribute("indexRange"),[Hs,ba]=jr?jr.split("-").map(lr=>parseInt(lr,10)):[],Gr=jr?{from:Hs,to:ba}:void 0;Fs={type:"byteRange",url:Vs,initRange:Rt,indexRange:Gr}}else if(_t){let Nt={representationId:(Ru=he.getAttribute("id"))!=null?Ru:void 0,bandwidth:(Lu=he.getAttribute("bandwidth"))!=null?Lu:void 0},Ft=parseInt(($u=_t.getAttribute("timescale"))!=null?$u:"",10),Us=(Mu=_t.getAttribute("initialization"))!=null?Mu:"",Rt=_t.getAttribute("media"),jr=(Du=parseInt((Cu=_t.getAttribute("startNumber"))!=null?Cu:"",10))!=null?Du:1,Hs=Zt(Us,Nt);if(!Rt)throw new ReferenceError("No media attribute in SegmentTemplate");let ba=(Ou=_t.querySelectorAll("SegmentTimeline S"))!=null?Ou:[],Gr=[],lr=0,js="",Gs=0;if(ba.length){let ga=jr,Qe=0;for(let cr of ba){let rt=parseInt((Bu=cr.getAttribute("d"))!=null?Bu:"",10),qt=parseInt((Vu=cr.getAttribute("r"))!=null?Vu:"",10)||0,Sa=parseInt((_u=cr.getAttribute("t"))!=null?_u:"",10);Qe=Number.isFinite(Sa)?Sa:Qe;let Ys=rt/Ft*1e3,Ws=Qe/Ft*1e3;for(let va=0;va<qt+1;va++){let Gb=Zt(Rt,Z(V({},Nt),{segmentNumber:ga.toString(10),segmentTime:(Qe+va*rt).toString(10)})),Hu=(Ws!=null?Ws:0)+va*Ys,Yb=Hu+Ys;ga++,Gr.push({time:{from:Hu,to:Yb},url:Gb})}Qe+=(qt+1)*rt,lr+=(qt+1)*Ys}Gs=Qe/Ft*1e3,js=Zt(Rt,Z(V({},Nt),{segmentNumber:ga.toString(10),segmentTime:Qe.toString(10)}))}else if((0,Vr.isNonNullable)(p)){let Qe=parseInt((Nu=_t.getAttribute("duration"))!=null?Nu:"",10)/Ft*1e3,cr=Math.ceil(p/Qe),rt=0;for(let qt=1;qt<cr;qt++){let Sa=Zt(Rt,Z(V({},Nt),{segmentNumber:qt.toString(10),segmentTime:rt.toString(10)}));Gr.push({time:{from:rt,to:rt+Qe},url:Sa}),rt+=Qe}Gs=rt,js=Zt(Rt,Z(V({},Nt),{segmentNumber:cr.toString(10),segmentTime:rt.toString(10)}))}let jb={time:{from:Gs,to:1/0},url:js};Fs={type:"template",baseUrl:Vs,segmentTemplateUrl:Rt,initUrl:Hs,totalSegmentsDurationMs:lr,segments:Gr,nextSegmentBeyondManifest:jb,timescale:Ft}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Vt||!ur)continue;let qs={video:"video",audio:"audio",text:"text"}[Vt];if(!qs)continue;Hr||(Hr=qs),_s={id:qb,kind:qs,segmentReference:Fs,profiles:Ub,duration:p,bitrate:qu,mime:ur,codecs:ma,width:Bb,height:Fu,fps:_b,quality:Vb}}me.language||(me.language=Cb),me.label||(me.label=Db),me.mime||(me.mime=ur),me.codecs||(me.codecs=ma),me.hdr||(me.hdr=Hr==="video"&&nu(ma)),me.representations.push(_s)}Hr&&i[Hr].push(me)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:i}};var zi=ze(vi(),1);var Km=require("@vkontakte/videoplayer-shared"),Jm=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?Ct(s):void 0)!=null?o:(0,Km.videoSizeToQuality)({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Xm=({id:a,bitrate:e})=>({id:a,bitrate:e}),ys=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,zi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,zi.default)(t,-1)},Zm=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),lu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,zi.default)(r.split("."),0),isDefault:i}),cu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,zi.default)(i.split("."),0)}),Ts=a=>"url"in a,er=a=>a.type==="template",Ki=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Ji=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new P.ValueSubject(0);this.onLastSegment$=new P.ValueSubject(!1);this.fullyBuffered$=new P.ValueSubject(!1);this.playingRepresentation$=new P.ValueSubject(void 0);this.playingRepresentationInit$=new P.ValueSubject(void 0);this.error$=new P.Subject;this.gaps=[];this.subscription=new P.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new yt;this.destroyAbortController=new yt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,P.abortable)(this.destroyAbortController.signal,function(e){return be(this,null,function*(){let t=this.representations.get(e);(0,P.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new bm(this.sourceBuffer),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Zo(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=St(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,l<c)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,P.assertNonNullable)(r,"No init buffer for starting representation"),(0,P.assertNonNullable)(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,P.abortable)(this.destroyAbortController.signal,function(e,t=!1){return be(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,P.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,P.isNullable)(s)||(0,P.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,P.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,P.isNonNullable)(n)&&(this.isLive||(i.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,P.abortable)(this.destroyAbortController.signal,function(e){return be(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!er(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);(0,P.assertNonNullable)(i);let s=this.segments.get(r);(0,P.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,P.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new yt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if((0,P.isNullable)(e)||(0,P.isNullable)(this.downloadingRepresentationId)||(0,P.isNullable)(this.playingRepresentationId)||(0,P.isNullable)(this.sourceBuffer)||!(0,P.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,P.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=St(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&Zo(this.sourceBuffer.buffered)>=this.bufferLimit){let d=St(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,_r.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&St(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,_r.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,P.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!er(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>Z(V({},p),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,_r.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(c)>=Math.floor(p.time.from)&&Math.floor(c)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,P.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!er(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=Zt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&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(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let g=p<=r&&h>=r,S=p>r||g||m===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),w=this.preloadOnly&&p<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&S&&w&&this.sourceBuffer&&!ki(this.sourceBuffer.buffered,r))&&S&&w});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];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}loadSegments(e,t,r="auto"){return D(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return D(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,P.abortable)(o,function(){return be(this,null,function*(){let c=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Or(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ki(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return D(this,null,function*(){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:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,P.abortable)(n,function(){return be(this,null,function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,P.fromEvent)(window,"online").pipe((0,P.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ki(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(er(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,_r.default)(e,0).byte.from,to:(0,_r.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!er(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return D(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){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){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Or(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,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 c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let g=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,T=g<i,w=S<=i;if(d.status==="downloading"&&T&&w){d.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+g,h);this.sourceBufferTaskQueue.append(I,s).then(x=>x&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(h,i-g),c.loadedBytes>c.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+g+c.feedingBytes,c.loadedBytes-c.feedingBytes),x=c.loadedBytes===h?I:Or(o.mime).parseFeedableSegmentChunk(I);x!=null&&x.byteLength&&(d.status="partially_fed",c.feedingBytes+=x.byteLength,this.sourceBufferTaskQueue.append(x,s).then(E=>{if(s.aborted)n();else if(E)c.fedBytes+=x.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return D(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,m=d<i,g=p<=i;if(m){if(c.status==="downloading"&&g){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===h?S:Or(u.mime).parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(c.status="partially_fed",l.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(l.fedBytes+=T.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}}})}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ts(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Jo(()=>(0,eb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return D(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,P.abortable)(this.destroyAbortController.signal,function(){return be(this,null,function*(){let o=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Or(e.mime),i)).then(o=>D(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&er(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),r&&this.error$.next({id:"LoadInits",category:P.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return D(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return D(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return D(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,P.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(u.time),i=n(i);let l=Ts(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}pruneBufferOld(e,t,r=!1){return D(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,P.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=Ts(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;i+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=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(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Jo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||(0,P.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=1;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Xi=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var tb=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};var se=require("@vkontakte/videoplayer-shared");var Is=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new se.ValueSubject(void 0);this.lastConnectionReused$=new se.ValueSubject(void 0);this.lastRequestFirstBytes$=new se.ValueSubject(void 0);this.abortAllController=new yt;this.subscription=new se.Subscription;this.fetchManifest=(0,se.abortable)(this.abortAllController.signal,function(e){return be(this,null,function*(){let t=e;this.requestQuic&&(t=Xi(t));let r=yield vt(t,{signal:this.abortAllController.signal}).catch(Zi);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=(0,se.abortable)(this.abortAllController.signal,function(l){return be(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var W,ee;let c=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let N=new URL(c,location.href);N.searchParams.append("bytes",`${r.from}-${r.to}`),c=N.toString();break}default:(0,se.assertNever)(t)}this.requestQuic&&(c=Xi(c));let p=this.abortAllController.signal,h;if(n){let N=new yt;if(h=(0,se.merge)((0,se.fromEvent)(this.abortAllController.signal,"abort"),(0,se.fromEvent)(n,"abort")).subscribe(()=>{try{N.abort()}catch(M){Zi(M)}}),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(M){Zi(M)}p=N.signal}let m=(0,se.now)(),g=yield vt(c,{priority:s,headers:d,signal:p}).catch(Zi),S=(0,se.now)();if(!g)return h==null||h.unsubscribe(),null;if((W=this.throughputEstimator)==null||W.addRawRtt(S-m),!g.ok||!g.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!i&&!o)return h==null||h.unsubscribe(),g.arrayBuffer();let[T,w]=g.body.tee(),I=T.getReader();o&&((ee=this.throughputEstimator)==null||ee.trackStream(w,u));let x=0,E=new Uint8Array(0),z=!1,Y=N=>{h==null||h.unsubscribe(),z=!0,Zi(N)},U=(0,se.abortable)(p,function(te){return be(this,arguments,function*({done:N,value:M}){if(x===0&&this.lastRequestFirstBytes$.next((0,se.now)()-m),p.aborted){h==null||h.unsubscribe();return}if(!N&&M){let ue=new Uint8Array(E.length+M.length);ue.set(E),ue.set(M,E.length),E=ue,x+=M.byteLength,i==null||i(new DataView(E.buffer),x),yield I==null?void 0:I.read().then(U,Y)}})}.bind(this));return yield I==null?void 0:I.read().then(U,Y),h==null||h.unsubscribe(),z?null:E.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,se.abortable)(this.abortAllController.signal,function(e,t,r){return be(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(T=e.indexRange)!=null?T:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let w=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!w)return null;g=new DataView(w)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,se.abortable)(this.abortAllController.signal,function(e,t){return be(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>Z(V({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=tb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return D(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,se.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Zi=a=>{if(!Ki(a))throw a};var tr=(a,e,t)=>t*e+(1-t)*a,du=(a,e)=>a.reduce((t,r)=>t+r,0)/e,rb=(a,e,t,r)=>{let i=0,s=t,n=du(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};var ea=require("@vkontakte/videoplayer-shared");var Ot=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ea.ValueSubject(e.initial),this.debounced$=new ea.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${t}`),this.smoothedSeries$=new Ie(`smoothed_${t}`),this.reportedSeries$=new Ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=it(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,ea.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Es=class extends Ot{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=tr(this.slow,e,this.params.emaAlphaSlow),this.fast=tr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var xs=class extends Ot{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=du(this.pastMeasures,this.takenMeasures);this.emaSmoothed=tr(this.emaSmoothed,e,this.params.emaAlpha);let r=rb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Ps=class extends Ot{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?tr(this.smoothed,t,this.params.emaAlpha):t}};var rr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Es({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new xs({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Ps(V({initial:e,label:"liveEdgeDelay"},t))}};var pu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var ab=["timeupdate","progress","play","seeked","stalled","waiting"];var ws=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new H("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.isLive$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new v.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new yt;this.initManifest=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return be(this,null,function*(){var i;this.element=e,this.manifestUrlString=ve(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,function(){return be(this,null,function*(){var s,n;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t;try{t=zm(e!=null?e:"",this.manifestUrlString)}catch(o){let u=(s=hm(e))!=null?s:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(u)}if(!t)return null;let r=(o,u,l)=>{var c,d,p,h;return!!((d=(c=this.element)==null?void 0:c.canPlayType)!=null&&d.call(c,u)&&((h=(p=Tt())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${l}"`))||o==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((n=t.duration)!=null?n:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:p,codecs:h})=>r(o,p,h)),c=new Set(l.map(({codecs:p})=>p)),d=pm(c);if(d&&(i[o]=l.filter(({codecs:p})=>p.startsWith(d))),o==="video"){let p=this.tuning.preferHDR,h=i.video.some(g=>g.hdr),m=i.video.some(g=>!g.hdr);v.clientChecker.isHDR&&p&&h?i.video=i.video.filter(g=>g.hdr):m&&(i.video=i.video.filter(g=>!g.hdr))}}return Z(V({},t),{streams:i})})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return be(this,null,function*(){var d;(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Qf():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ps())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}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((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ji("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Ji("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,v.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=Bo(this.manifestUrlString,2);this.manifestUrlString=ve(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add((0,v.merge)(...ab.filter(p=>p!=="waiting").map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?St(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.filter)(p=>!!p),(0,v.tap)(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,v.filterChanged)()).subscribe(h=>pu(this.element,1))),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,v.filter)(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add((0,v.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:m})=>{if(!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=h-g,I=1;Math.abs(w)>S&&(I=1+Math.sign(w)*T),pu(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let T=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var x,E;return(E=(x=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:x.to)!=null?E:T}))-T}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(g=>D(this,[g],function*({liveLoadBufferLength:h,bufferLength:m}){if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,T=Bo(this.manifestUrlString,2),w=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(w,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,z=isFinite(h)?h:m,Y=this.isActiveLowLatency$.getValue(),U=w<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(Y&&U);let W="none";if(Y?W="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&U?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(ee=>ee.proceedLowLatencyLive()),W="active_low_latency"):T!==0&&z<I?W="live_forward_buffering":z<I+E&&(W="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),W==="live_forward_buffering"||W==="live_with_target_offset"){let ee=p-(I+x),N=this.normolizeLiveOffset(Math.trunc(T+ee/S)),M=Math.abs(N-T),te;!h||M<=this.tuning.dashCmafLive.offsetCalculationError?te=T:N>0&&M>this.tuning.dashCmafLive.offsetCalculationError?te=N:te=0,this.manifestUrlString=ve(this.manifestUrlString,te,2)}W!=="none"&&W!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=(0,v.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=(0,v.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:u,someBufferEnded:l}).pipe((0,v.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let c=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{var h;return(h=p.duration)!=null?h:0})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")})}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Is({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=rr.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,V({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return D(this,null,function*(){var r,i,s,n;(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ve(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...ab.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&ki(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var r,i;if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let s=this.element.currentTime*1e3;(r=this.videoBufferManager)==null||r.maintain(s),(i=this.audioBufferManager)==null||i.maintain(s)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return D(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),ki(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return D(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],i=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-i<=t&&n.to+i>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var As=class{constructor(e,t){this.fov=e,this.orientation=t}};var ks=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/it(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=V({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*it(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var sb=`attribute vec2 a_vertex;
59
38
  attribute vec2 a_texel;
60
39
 
61
40
  varying vec2 v_texel;
@@ -66,7 +45,7 @@ void main(void) {
66
45
  // save texel vector to pass to fragment shader
67
46
  v_texel = a_texel;
68
47
  }
69
- `;var hb=`#ifdef GL_ES
48
+ `;var nb=`#ifdef GL_ES
70
49
  precision highp float;
71
50
  precision highp int;
72
51
  #else
@@ -109,5 +88,5 @@ void main(void) {
109
88
  // sample using new coordinates
110
89
  gl_FragColor = texture2D(u_texture, tc);
111
90
  }
112
- `;var $s=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Rs(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ls(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(pb,this.gl.VERTEX_SHADER),r=this.createShader(hb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,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 nr=class{constructor(e){this.subscription=new C.Subscription;this.videoState=new j("stopped");this.elementSize$=new C.ValueSubject(void 0);this.textTracksManager=new je;this.droppedFramesManager=new cs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ii;this.audioTrackSwitchHistory=new Ii;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,C.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new $s(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.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=we(e.container,e.tuning),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(Se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ks({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Le(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:C.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,C.filter)(l=>!!l.length),(0,C.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:l})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,C.filter)(C.isNonNullable),(0,C.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,C.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),s((0,C.observeElementSize)(this.video),this.elementSize$),s(Ge(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if((0,C.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(du(h));let m=[];for(let g of h.representations){let S=sb(g);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:g})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(pu(p));let h=[];for(let m of p.representations){let g=ab(m);g&&(h.push(g),this.videoTracksMap.set(g,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=nb(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>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:C.ErrorCategory.WTF,message:"Switching representations threw",thrown:l});this.subscription.add((0,C.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,C.fromEvent)(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,g).catch(n)}},i)),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((0,C.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(pu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,C.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(du(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,C.map)(({to:l})=>l==="ready"),(0,C.filterChanged)());this.subscription.add((0,C.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,C.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,C.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,C.observableFrom)(["init"])).pipe((0,C.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var Y,ie,W,Z,q,M,ee,V,pe,L,J,ae,ue,fe,Ne,Vt,kt,K,me;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(Y=e.videoTrack.getState())==null?void 0:Y.id,n=[...this.videoTracksMap.keys()].find(({id:F})=>F===i),o=t.currentVideoTrack$.getValue(),u=((Z=(W=e.videoStream.getState())!=null?W:n&&((ie=this.videoTracksMap.get(n))==null?void 0:ie.stream))!=null?Z:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:F})=>F===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=yt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(q=e.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(M=[...this.audioStreamsMap.keys()].find(({id:F})=>F===(m==null?void 0:m.id)))!=null?M:this.audioStreamsMap.keys().next().value,S=0;if(g){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let F=us(n,c,(ee=this.audioStreamsMap.get(g))!=null?ee:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(V=F==null?void 0:F.bitrate)!=null?V:-1/0)}else{let F=Is(n,c,(pe=this.audioStreamsMap.get(g))!=null?pe:[]);S=Math.max(S,(L=F==null?void 0:F.bitrate)!=null?L:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let F=us(o,c,(J=this.audioStreamsMap.get(g))!=null?J:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(ae=F==null?void 0:F.bitrate)!=null?ae:-1/0)}else{let F=Is(o,c,(ue=this.audioStreamsMap.get(g))!=null?ue:[]);S=Math.max(S,(fe=F==null?void 0:F.bitrate)!=null?fe:-1/0)}}let T=Ot(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:A}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(T=(Ne=c.filter(F=>!(0,C.isInvariantQuality)(F.quality)).sort((F,xe)=>{var Qe,dt;return((Qe=xe.bitrate)!=null?Qe:0)-((dt=F.bitrate)!=null?dt:0)}).filter(F=>(0,C.isLowerOrEqual)(F.quality,T.quality)&&(0,C.isLowerOrEqual)(F.quality,A))[0])!=null?Ne:T);let I=r?T!=null?T:n:n!=null?n:T,E;this.params.tuning.useSeparateAudioVideoABR?E=g&&Qf(I,c,(Vt=this.audioStreamsMap.get(g))!=null?Vt:[],{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}):E=g&&Is(I,c,(kt=this.audioStreamsMap.get(g))!=null?kt:[]);let x=(K=this.videoTracksMap.get(I))==null?void 0:K.representation,z=E&&((me=this.audioTracksMap.get(E))==null?void 0:me.representation);if(x&&z)return[x,z];if(x&&!z&&this.audioTracksMap.size===0)return[x,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){$e(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ke(this.video)}};var aa=class extends nr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var or=require("@vkontakte/videoplayer-shared");var sa=class extends nr{constructor(e){super(e),this.liveOffset=new gt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,or.combine)({interval:(0,or.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add((0,or.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,or.map)(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var fb=Ke(ss(),1);var G=require("@vkontakte/videoplayer-shared");var rt={};var Fr=(a,e)=>new G.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),na=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new j("initializing");this.textTracksManager=new je;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,G.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,G.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,G.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,G.assertNever)(e)}break;default:(0,G.assertNever)(t)}};this.video=we(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(Se(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ke(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:G.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,fb.default)(import("hls.js").then(i=>{e||(rt.Hls=i.default,rt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,G.assertNonNullable)(rt.Hls,"hls.js not loaded"),this.hls=new rt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,G.assertNonNullable)(rt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:G.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Le(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,r)),this.subscription.add(Re(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(He(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ge(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,G.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Fr(this.hls,rt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:G.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Fr(this.hls,rt.Events.MANIFEST_PARSED).pipe((0,G.map)(({levels:l})=>l.reduce((c,d)=>{var A,I;let p=d.name||d.height.toString(10),{width:h,height:m}=d,g=(I=Dt((A=d.attrs.QUALITY)!=null?A:""))!=null?I:(0,G.videoSizeToQuality)({width:h,height:m});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(Fr(this.hls,rt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Fr(this.hls,rt.Events.LEVEL_LOADING).pipe((0,G.map)(({url:l})=>Se(l))),t.hostname$),s(Fr(this.hls,rt.Events.FRAG_CHANGED),l=>{var p,h,m,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Ct(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Fr(this.hls,rt.Events.LEVEL_SWITCHED).pipe((0,G.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,G.filter)(G.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ct(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,G.isNullable)(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,G.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return D(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield $e(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),w(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"),w(this.params.desiredState.playbackState,"stopped",!0)}};var mb="X-Playback-Duration",mu=a=>D(void 0,null,function*(){var i;let e=yield Tt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(mb)?parseInt(e.headers.get(mb),10):void 0});var H=require("@vkontakte/videoplayer-shared");var gu=Ke(Jn(),1);var Ms=require("@vkontakte/videoplayer-shared");var ZP=a=>{let e=null;if(a.QUALITY&&(e=Dt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,Ms.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},eA=(a,e)=>{var s,n;let t=a.split(`
113
- `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,gu.default)(l[1].split(",").map(A=>A.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=ZP(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[A,I]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));A&&I&&(S={width:A,height:I})}let T=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:T,bandwidth:m,size:S,fps:g})}if(c){let d=(0,gu.default)(c[1].split(",").map(g=>g.split("=")).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},tA=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),bu=0,bb=(r,...i)=>D(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield Tt(a)).text();bu+=1;try{let{qualityManifests:o,textTracks:u}=eA(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(bu<=t.manifestRetryMaxCount)return yield tA((0,Ms.getExponentialDelay)(bu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),bb(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Cs=bb;var oa=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new j("stopped");this.textTracksManager=new je;this.manifests$=new H.ValueSubject([]);this.liveOffset=new gt;this.manifestStartTime$=new H.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(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 c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,H.assertNever)(t)}};var t;this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:H.VideoQuality.INVARIANT,url:this.params.source.url},Cs(ye(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:H.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:H.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.maxSeekBackTime$=new H.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:H.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Le(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ge(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,H.filterChanged)(),(0,H.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,H.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Se(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,H.combine)({startTime:this.manifestStartTime$.pipe((0,H.filter)(H.isNonNullable)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,H.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,H.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,H.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ye(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),mu(n).then(l=>{var c;if(!(0,H.isNullable)(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if((0,H.isNullable)(d)||!isFinite(d))try{Tt(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();mu(g).then(S=>{(0,H.isNullable)(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){$e(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};var Q=require("@vkontakte/videoplayer-shared");var ua=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new j("stopped");this.textTracksManager=new je;this.manifests$=new Q.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(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 c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,Q.assertNever)(t)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Q.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Cs(ye(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Q.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Q.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Le(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,Q.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,Q.isNonNullable)(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(m=>m.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Se(h.url));let m=this.params.desiredState.playbackRate.getState(),g=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(m!==g){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(m),S.playbackRate=m)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,Q.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!Q.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,Q.merge)((0,Q.fromEvent)(o,"addtrack"),(0,Q.fromEvent)(o,"removetrack"),(0,Q.fromEvent)(o,"change"),(0,Q.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,Q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,Q.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){$e(this.video).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Q.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var re=require("@vkontakte/videoplayer-shared");var la=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new je;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(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:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:re.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Le(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,re.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ge(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,re.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,re.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ke(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,re.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,re.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ea(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Se(t))}playIfAllowed(){$e(this.video).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!(0,re.isInvariantQuality)(d.track.quality)&&(0,re.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,re.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!(0,re.isInvariantQuality)(h.track.quality)&&(0,re.isHigher)(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=Ot(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};var ne=require("@vkontakte/videoplayer-shared");var Sb=require("@vkontakte/videoplayer-shared");var gb=["stun:videostun.mycdn.me:80"],rA=1e3,iA=3,Su=()=>null,Ds=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=Su;this.externalStopCallback=Su;this.externalErrorCallback=Su;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return D(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return D(this,null,function*(){try{let e={iceServers:[{urls:gb}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return D(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return D(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:Sb.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return D(this,null,function*(){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()))}}createOffer(){return D(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),rA)}normalizeOptions(e={}){let t={stunServerList:gb,maxRetryNumber:iA,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 j("stopped");this.maxSeekBackTime$=new ne.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,ne.assertNever)(e)}};this.subscription=new ne.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=we(e.container,e.tuning),this.liveStreamClient=new Ds(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ke(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ne.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ne.merge)(this.videoState.stateChangeStarted$.pipe((0,ne.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ne.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Le(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),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(Ge(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Re(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,ne.assertNever)(n.to)}},r)).add((0,ne.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ne.observableFrom)(["init"])).pipe((0,ne.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Se(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:ne.VideoQuality.INVARIANT}),this.video.srcObject=e,w(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:ne.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){$e(this.video).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ne.ErrorCategory.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}};var y=require("@vkontakte/videoplayer-shared");var Pt=require("@vkontakte/videoplayer-shared"),vb=a=>new Pt.Observable(e=>{let t=new Pt.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Pt.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Pt.map)(({type:l})=>l!==void 0)),n=new Pt.Subject,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.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),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var _e=require("@vkontakte/videoplayer-shared");var pa=null,Os=null;function vu(){return pa||(pa=new(window.AudioContext||window.webkitAudioContext)),Os||(Os=new GainNode(pa,{gain:1}),Os.connect(pa.destination)),{audioCtx:pa,gainNode:Os}}var yb=require("@vkontakte/videoplayer-shared");var qr=class qr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new _e.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe((0,_e.filter)(n=>!!n.type),(0,_e.once)()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){yb.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,_e.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,_e.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,_e.once)()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:i}=vu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${qr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:qr.errorId,category:_e.ErrorCategory.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:qr.errorId,category:_e.ErrorCategory.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=vu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};qr.errorId="VolumeMultiplierManager";var ha=qr;var aA={chunkDuration:5e3,maxParallelRequests:5},fa=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject("")};this.subscription=new y.Subscription;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=bm([...Sm(this.params.tuning),...gm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>(0,y.isNonNullable)(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new da(s);let n=[...Xo(!0),...Xo(!1)];this.chromecastFormatsIterator=new da(n.filter(u=>(0,y.isNonNullable)(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new ha(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(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"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,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(0,y.assertNonNullable)(o),new aa(X(_({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new sa(X(_({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),Mr||!this.params.tuning.useHlsJs?new ua(X(_({},n),{source:o})):new na(X(_({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new oa(X(_({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new la(X(_({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Xf(X(_({},n),{source:o,config:X(_({},aA),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ca({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new vi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);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 X(_({},e),{url:r(e.url)})}return(0,Tb.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,r=0;return e.add((0,y.merge)(this.providerOutput.error$,vb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(i=>({id:`ProviderHangup:${i}`,category:y.ErrorCategory.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=i.category===y.ErrorCategory.NETWORK,o=i.category===y.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};var N=require("@vkontakte/videoplayer-shared");var sA=5e3,Ib="one_video_throughput",Eb="one_video_rtt",At=window.navigator.connection,xb=()=>{let a=At==null?void 0:At.downlink;if((0,N.isNonNullable)(a)&&a!==10)return a*1e3},Pb=()=>{let a=At==null?void 0:At.rtt;if((0,N.isNonNullable)(a)&&a!==3e3)return a},Ab=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},yu=class a{constructor(e){this.subscription=new N.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(Ib)||(e.useBrowserEstimation?xb():void 0)||sA,r=(s=(i=a.load(Eb))!=null?i:e.useBrowserEstimation?Pb():void 0)!=null?s:0;if(this.throughput$=new N.ValueSubject(t),this.rtt$=new N.ValueSubject(r),this.rttAdjustedThroughput$=new N.ValueSubject(Ab(t,r,e.rttPenaltyRequestSize)),this.throughput=sr.getSmoothedValue(t,-1,e),this.rtt=sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=xb();u&&this.throughput.next(u);let l=Pb();(0,N.isNonNullable)(l)&&this.rtt.next(l)};At&&"onchange"in At&&this.subscription.add((0,N.fromEvent)(At,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{N.safeStorage.set(Ib,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{N.safeStorage.set(Eb,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,N.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,N.map)(({throughput:n,rtt:o})=>Ab(n,o,e.rttPenaltyRequestSize)),(0,N.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,N.now)(),i=new N.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,N.fromEvent)(e,"progress").pipe((0,N.once)()).subscribe(s=>{t=s.loaded,r=(0,N.now)()}));break;case 1:case 0:i.add((0,N.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,N.now)()}));break}i.add((0,N.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,N.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=(0,N.now)(),n=0,o=(0,N.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>D(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,(0,N.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,N.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=d.byteLength,s=(0,N.now)()}else n+=d.byteLength;o=(0,N.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,N.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,N.now)()-o,this.concurrentDownloads.size),n=0,o=(0,N.now)());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=N.safeStorage.get(e);if((0,N.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},wb=yu;var ma=require("@vkontakte/videoplayer-shared");var kb={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:ma.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ma.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Rb=a=>{var e;return X(_({},(0,ma.fillWithDefault)(a,kb)),{configName:[...(e=a.configName)!=null?e:[],...kb.configName]})};var f=require("@vkontakte/videoplayer-shared");var wt=require("@vkontakte/videoplayer-shared"),Tu=({seekState:a,position$:e})=>(0,wt.merge)(a.stateChangeEnded$.pipe((0,wt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,wt.filter)(wt.isNonNullable)),e.pipe((0,wt.filter)(()=>a.getState().state==="none")));var Lb=require("@vkontakte/videoplayer-shared"),$b=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,Lb.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Bs=require("@vkontakte/videoplayer-shared"),Mb=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,Bs.filter)(i=>i.length>0),(0,Bs.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var ba=class{constructor(e={configName:[]}){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:Hf};if(this.initLogs(),this.tuning=Rb(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new xa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new wb(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,i)=>{let s=Reflect.get(t,r,i);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let u=n.map(d=>JSON.stringify(d,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:f.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,i;return this.config=e,this.domContainer=$b(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new fa({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(i=e.failoverHosts)!=null?i:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ai()?(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue();return e>=r&&!i&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return 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.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;(0,f.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>_({type:"external"},t))),this}selectTextTrack(e){var t;return Mb(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState(X(_({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,f.map)(n=>n.map(({quality:o})=>o).sort((o,u)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(u)?-1:(0,f.isHigher)(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$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Tu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(Tu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=Ot(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),Uf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>qf(r)),this.providerContainer.current$.subscribe(({type:r})=>Ti("provider",r)),e.duration$.subscribe(r=>Ti("duration",r)),e.availableVideoTracks$.pipe((0,f.filter)(r=>!!r.length),(0,f.once)()).subscribe(r=>Ti("tracks",r)),this.events.fatalError$.subscribe(new Ee("fatalError")),this.events.managedError$.subscribe(new Ee("managedError")),e.position$.subscribe(new Ee("position")),e.currentVideoTrack$.pipe((0,f.map)(r=>r==null?void 0:r.quality)).subscribe(new Ee("quality")),this.info.currentBuffer$.subscribe(new Ee("buffer")),e.isBuffering$.subscribe(new Ee("isBuffering"))].forEach(r=>this.subscription.add(r)),Ti("codecs",mm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>D(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(i)})})});this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var ct=require("@vkontakte/videoplayer-shared"),nA=`@vkontakte/videoplayer-core@${Ks}`;
91
+ `;var Rs=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new As(this.params.fov,this.params.orientation),this.cameraRotationManager=new ks(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(sb,this.gl.VERTEX_SHADER),r=this.createShader(nb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,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 ir=class{constructor(e){this.subscription=new C.Subscription;this.videoState=new H("stopped");this.elementSize$=new C.ValueSubject(void 0);this.textTracksManager=new je;this.droppedFramesManager=new us;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ns;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&A(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,C.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Rs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.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=we(e.container,e.tuning),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(ge(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ws({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Re(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:C.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,C.filter)(l=>!!l.length),(0,C.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:l})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,C.filter)(C.isNonNullable),(0,C.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,C.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),s((0,C.observeElementSize)(this.video),this.elementSize$),s(Ge(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if((0,C.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(lu(h));let m=[];for(let g of h.representations){let S=Xm(g);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:g})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(cu(p));let h=[];for(let m of p.representations){let g=Jm(m);g&&(h.push(g),this.videoTracksMap.set(g,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=Zm(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>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=l=>e.error$.next({id:"RepresentationSwitch",category:C.ErrorCategory.WTF,message:"Switching representations threw",thrown:l});this.subscription.add((0,C.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,C.fromEvent)(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,g).catch(n)}},i)),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((0,C.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(cu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,C.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(lu(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,C.map)(({to:l})=>l==="ready"),(0,C.filterChanged)());this.subscription.add((0,C.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,C.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,C.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,C.observableFrom)(["init"])).pipe((0,C.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var Y,U,W,ee,N,M,te,ue,B,k,J,ae,le,fe;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(Y=e.videoTrack.getState())==null?void 0:Y.id,n=[...this.videoTracksMap.keys()].find(({id:X})=>X===i),o=t.currentVideoTrack$.getValue(),u=((ee=(W=e.videoStream.getState())!=null?W:n&&((U=this.videoTracksMap.get(n))==null?void 0:U.stream))!=null?ee:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:X})=>X===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=St(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(N=e.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(M=[...this.audioStreamsMap.keys()].find(({id:X})=>X===(m==null?void 0:m.id)))!=null?M:this.audioStreamsMap.keys().next().value,S=0;if(g){if(n&&!r){let X=ys(n,c,(te=this.audioStreamsMap.get(g))!=null?te:[]);S=Math.max(S,(ue=X==null?void 0:X.bitrate)!=null?ue:-1/0)}if(o){let X=ys(o,c,(B=this.audioStreamsMap.get(g))!=null?B:[]);S=Math.max(S,(k=X==null?void 0:X.bitrate)!=null?k:-1/0)}}let T=Dt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:w}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(T=(J=c.filter(X=>!(0,C.isInvariantQuality)(X.quality)).sort((X,sr)=>{var wt,K;return((wt=sr.bitrate)!=null?wt:0)-((K=X.bitrate)!=null?K:0)}).filter(X=>(0,C.isLowerOrEqual)(X.quality,T.quality)&&(0,C.isLowerOrEqual)(X.quality,w))[0])!=null?J:T);let I=r?T!=null?T:n:n!=null?n:T,x=g&&ys(I,c,(ae=this.audioStreamsMap.get(g))!=null?ae:[]),E=(le=this.videoTracksMap.get(I))==null?void 0:le.representation,z=x&&((fe=this.audioTracksMap.get(x))==null?void 0:fe.representation);if(E&&z)return[E,z];if(E&&!z&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Le(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}};var ra=class extends ir{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ar=require("@vkontakte/videoplayer-shared");var ia=class extends ir{constructor(e){super(e),this.liveOffset=new mt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,ar.combine)({interval:(0,ar.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add((0,ar.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ar.map)(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var ob=ze(is(),1);var j=require("@vkontakte/videoplayer-shared");var tt={};var Nr=(a,e)=>new j.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),aa=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new H("initializing");this.textTracksManager=new je;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,j.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,j.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,j.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,j.assertNever)(e)}break;default:(0,j.assertNever)(t)}};this.video=we(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(ge(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:j.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,ob.default)(import("hls.js").then(i=>{e||(tt.Hls=i.default,tt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,j.assertNonNullable)(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,j.assertNonNullable)(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:j.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Re(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(nt(this.video,e.isLooped,r)),this.subscription.add(ke(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(He(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ge(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,j.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Nr(this.hls,tt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:j.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Nr(this.hls,tt.Events.MANIFEST_PARSED).pipe((0,j.map)(({levels:l})=>l.reduce((c,d)=>{var w,I;let p=d.name||d.height.toString(10),{width:h,height:m}=d,g=(I=Ct((w=d.attrs.QUALITY)!=null?w:""))!=null?I:(0,j.videoSizeToQuality)({width:h,height:m});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(Nr(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Nr(this.hls,tt.Events.LEVEL_LOADING).pipe((0,j.map)(({url:l})=>ge(l))),t.hostname$),s(Nr(this.hls,tt.Events.FRAG_CHANGED),l=>{var p,h,m,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Mt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Nr(this.hls,tt.Events.LEVEL_SWITCHED).pipe((0,j.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,j.filter)(j.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Mt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,j.isNullable)(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,j.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,j.observableFrom)(["init"])).pipe((0,j.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return D(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Le(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:j.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0)}};var ub="X-Playback-Duration",hu=a=>D(void 0,null,function*(){var i;let e=yield vt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(ub)?parseInt(e.headers.get(ub),10):void 0});var q=require("@vkontakte/videoplayer-shared");var mu=ze(zn(),1);var Ls=require("@vkontakte/videoplayer-shared");var zP=a=>{let e=null;if(a.QUALITY&&(e=Ct(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,Ls.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},KP=(a,e)=>{var s,n;let t=a.split(`
92
+ `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,mu.default)(l[1].split(",").map(w=>w.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=zP(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[w,I]=d.RESOLUTION.split("x").map(x=>parseInt(x,10));w&&I&&(S={width:w,height:I})}let T=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:T,bandwidth:m,size:S,fps:g})}if(c){let d=(0,mu.default)(c[1].split(",").map(g=>g.split("=")).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},JP=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),fu=0,lb=(r,...i)=>D(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield vt(a)).text();fu+=1;try{let{qualityManifests:o,textTracks:u}=KP(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(fu<=t.manifestRetryMaxCount)return yield JP((0,Ls.getExponentialDelay)(fu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),lb(a,e,t)}return{qualityManifests:[],textTracks:[]}}),$s=lb;var sa=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("stopped");this.textTracksManager=new je;this.manifests$=new q.ValueSubject([]);this.liveOffset=new mt;this.manifestStartTime$=new q.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,q.assertNever)(t)}};var t;this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:q.VideoQuality.INVARIANT,url:this.params.source.url},$s(ve(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:q.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:q.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.maxSeekBackTime$=new q.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:q.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Re(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ge(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,q.filterChanged)(),(0,q.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,q.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ge(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,q.combine)({startTime:this.manifestStartTime$.pipe((0,q.filter)(q.isNonNullable)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,q.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,q.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ve(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),hu(n).then(l=>{var c;if(!(0,q.isNullable)(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if((0,q.isNullable)(d)||!isFinite(d))try{vt(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();hu(g).then(S=>{(0,q.isNullable)(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};var Q=require("@vkontakte/videoplayer-shared");var na=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new H("stopped");this.textTracksManager=new je;this.manifests$=new Q.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,Q.assertNever)(t)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Q.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),$s(ve(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Q.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Q.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Re(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,Q.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,Q.isNonNullable)(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(m=>m.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ge(h.url));let m=this.params.desiredState.playbackRate.getState(),g=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(m!==g){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(m),S.playbackRate=m)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,Q.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!Q.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,Q.merge)((0,Q.fromEvent)(o,"addtrack"),(0,Q.fromEvent)(o,"removetrack"),(0,Q.fromEvent)(o,"change"),(0,Q.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,Q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,Q.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Q.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var ie=require("@vkontakte/videoplayer-shared");var oa=class{constructor(e){this.subscription=new ie.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new je;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,ie.assertNever)(e)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:ie.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Re(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,ie.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ge(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,ie.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,ie.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ie.observableFrom)(["init"])).pipe((0,ie.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ae(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,ie.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ie.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Xi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ge(t))}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ie.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!(0,ie.isInvariantQuality)(d.track.quality)&&(0,ie.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,ie.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!(0,ie.isInvariantQuality)(h.track.quality)&&(0,ie.isHigher)(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=Dt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};var ne=require("@vkontakte/videoplayer-shared");var db=require("@vkontakte/videoplayer-shared");var cb=["stun:videostun.mycdn.me:80"],XP=1e3,ZP=3,bu=()=>null,Ms=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=bu;this.externalStopCallback=bu;this.externalErrorCallback=bu;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return D(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return D(this,null,function*(){try{let e={iceServers:[{urls:cb}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return D(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return D(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:db.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return D(this,null,function*(){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()))}}createOffer(){return D(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),XP)}normalizeOptions(e={}){let t={stunServerList:cb,maxRetryNumber:ZP,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ua=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new ne.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,ne.assertNever)(e)}};this.subscription=new ne.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=we(e.container,e.tuning),this.liveStreamClient=new Ms(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ae(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ne.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ne.merge)(this.videoState.stateChangeStarted$.pipe((0,ne.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ne.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Re(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),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(Ge(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ke(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,ne.assertNever)(n.to)}},r)).add((0,ne.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ne.observableFrom)(["init"])).pipe((0,ne.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ge(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:ne.VideoQuality.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:ne.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ne.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var la=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared");var Et=require("@vkontakte/videoplayer-shared"),pb=a=>new Et.Observable(e=>{let t=new Et.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Et.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Et.map)(({type:l})=>l!==void 0)),n=new Et.Subject,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.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),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var _e=require("@vkontakte/videoplayer-shared");var ca=null,Cs=null;function gu(){return ca||(ca=new(window.AudioContext||window.webkitAudioContext)),Cs||(Cs=new GainNode(ca,{gain:1}),Cs.connect(ca.destination)),{audioCtx:ca,gainNode:Cs}}var hb=require("@vkontakte/videoplayer-shared");var Fr=class Fr{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new _e.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe((0,_e.filter)(n=>!!n.type),(0,_e.once)()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){hb.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,_e.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,_e.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,_e.once)()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:i}=gu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Fr.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Fr.errorId,category:_e.ErrorCategory.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Fr.errorId,category:_e.ErrorCategory.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=gu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Fr.errorId="VolumeMultiplierManager";var da=Fr;var ew={chunkDuration:5e3,maxParallelRequests:5},pa=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject("")};this.subscription=new y.Subscription;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=lm([...dm(this.params.tuning),...cm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>(0,y.isNonNullable)(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new la(s);let n=[...Ko(!0),...Ko(!1)];this.chromecastFormatsIterator=new la(n.filter(u=>(0,y.isNonNullable)(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new da(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(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"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,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(0,y.assertNonNullable)(o),new ra(Z(V({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ia(Z(V({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),$r||!this.params.tuning.useHlsJs?new na(Z(V({},n),{source:o})):new aa(Z(V({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new sa(Z(V({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new oa(Z(V({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Gf(Z(V({},n),{source:o,config:Z(V({},ew),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ua({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new Si({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);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 Z(V({},e),{url:r(e.url)})}return(0,fb.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,r=0;return e.add((0,y.merge)(this.providerOutput.error$,pb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(i=>({id:`ProviderHangup:${i}`,category:y.ErrorCategory.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=i.category===y.ErrorCategory.NETWORK,o=i.category===y.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};var _=require("@vkontakte/videoplayer-shared");var tw=5e3,mb="one_video_throughput",bb="one_video_rtt",xt=window.navigator.connection,gb=()=>{let a=xt==null?void 0:xt.downlink;if((0,_.isNonNullable)(a)&&a!==10)return a*1e3},Sb=()=>{let a=xt==null?void 0:xt.rtt;if((0,_.isNonNullable)(a)&&a!==3e3)return a},vb=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Su=class a{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(mb)||(e.useBrowserEstimation?gb():void 0)||tw,r=(s=(i=a.load(bb))!=null?i:e.useBrowserEstimation?Sb():void 0)!=null?s:0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(r),this.rttAdjustedThroughput$=new _.ValueSubject(vb(t,r,e.rttPenaltyRequestSize)),this.throughput=rr.getSmoothedValue(t,-1,e),this.rtt=rr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=gb();u&&this.throughput.next(u);let l=Sb();(0,_.isNonNullable)(l)&&this.rtt.next(l)};xt&&"onchange"in xt&&this.subscription.add((0,_.fromEvent)(xt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{_.safeStorage.set(mb,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{_.safeStorage.set(bb,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,_.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,_.map)(({throughput:n,rtt:o})=>vb(n,o,e.rttPenaltyRequestSize)),(0,_.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,_.now)(),i=new _.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,_.fromEvent)(e,"progress").pipe((0,_.once)()).subscribe(s=>{t=s.loaded,r=(0,_.now)()}));break;case 1:case 0:i.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,_.now)()}));break}i.add((0,_.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,_.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=(0,_.now)(),n=0,o=(0,_.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>D(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,_.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=d.byteLength,s=(0,_.now)()}else n+=d.byteLength;o=(0,_.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,_.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,_.now)()-o,this.concurrentDownloads.size),n=0,o=(0,_.now)());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},yb=Su;var ha=require("@vkontakte/videoplayer-shared");var Tb={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:ha.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ha.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Ib=a=>{var e;return Z(V({},(0,ha.fillWithDefault)(a,Tb)),{configName:[...(e=a.configName)!=null?e:[],...Tb.configName]})};var f=require("@vkontakte/videoplayer-shared");var Pt=require("@vkontakte/videoplayer-shared"),vu=({seekState:a,position$:e})=>(0,Pt.merge)(a.stateChangeEnded$.pipe((0,Pt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Pt.filter)(Pt.isNonNullable)),e.pipe((0,Pt.filter)(()=>a.getState().state==="none")));var Eb=require("@vkontakte/videoplayer-shared"),xb=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,Eb.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Ds=require("@vkontakte/videoplayer-shared"),Pb=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,Ds.filter)(i=>i.length>0),(0,Ds.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var fa=class{constructor(e={configName:[]}){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),videoStream:new H(void 0),audioStream:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:qf};if(this.initLogs(),this.tuning=Ib(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ia({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new yb(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,i)=>{let s=Reflect.get(t,r,i);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let u=n.map(d=>JSON.stringify(d,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:f.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,i;return this.config=e,this.domContainer=xb(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new pa({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(i=e.failoverHosts)!=null?i:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!xi()?(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue();return e>=r&&!i&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return 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.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;(0,f.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>V({type:"external"},t))),this}selectTextTrack(e){var t;return Pb(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState(Z(V({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,f.map)(n=>n.map(({quality:o})=>o).sort((o,u)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(u)?-1:(0,f.isHigher)(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$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:vu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(vu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=Dt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),Ff(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Nf(r)),this.providerContainer.current$.subscribe(({type:r})=>yi("provider",r)),e.duration$.subscribe(r=>yi("duration",r)),e.availableVideoTracks$.pipe((0,f.filter)(r=>!!r.length),(0,f.once)()).subscribe(r=>yi("tracks",r)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe((0,f.map)(r=>r==null?void 0:r.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(r=>this.subscription.add(r)),yi("codecs",um())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>D(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(i)})})});this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var lt=require("@vkontakte/videoplayer-shared"),rw=`@vkontakte/videoplayer-core@${Qs}`;