@vkontakte/videoplayer-core 2.0.105-dev.17a808f4.0 → 2.0.105-dev.35548197.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.esm.js CHANGED
@@ -1,40 +1,40 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.105-dev.17a808f4.0
3
- * Wed, 10 Jul 2024 00:40:51 GMT
2
+ * @vkontakte/videoplayer-core v2.0.105-dev.35548197.0
3
+ * Wed, 10 Jul 2024 13:05:36 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-105/doc/
5
5
  */
6
- var lS=Object.create;var xu=Object.defineProperty;var cS=Object.getOwnPropertyDescriptor;var dS=Object.getOwnPropertyNames;var pS=Object.getPrototypeOf,hS=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var fS=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of dS(e))!hS.call(i,a)&&a!==t&&xu(i,a,{get:()=>e[a],enumerable:!(r=cS(e,a))||r.enumerable});return i};var _e=(i,e,t)=>(t=i!=null?lS(pS(i)):{},fS(e||!i||!i.__esModule?xu(t,"default",{value:i,enumerable:!0}):t,i));var pe=f((pR,Cu)=>{"use strict";Cu.exports=function(i){try{return!!i()}catch{return!0}}});var xr=f((hR,Mu)=>{"use strict";var IS=pe();Mu.exports=!IS(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ee=f((fR,Vu)=>{"use strict";var Du=xr(),Ou=Function.prototype,Ms=Ou.call,ES=Du&&Ou.bind.bind(Ms,Ms);Vu.exports=Du?ES:function(i){return function(){return Ms.apply(i,arguments)}}});var jt=f((mR,_u)=>{"use strict";var Bu=ee(),xS=Bu({}.toString),PS=Bu("".slice);_u.exports=function(i){return PS(xS(i),8,-1)}});var Fu=f((bR,Nu)=>{"use strict";var kS=ee(),AS=pe(),wS=jt(),Ds=Object,RS=kS("".split);Nu.exports=AS(function(){return!Ds("z").propertyIsEnumerable(0)})?function(i){return wS(i)=="String"?RS(i,""):Ds(i)}:Ds});var Gt=f((SR,qu)=>{"use strict";qu.exports=function(i){return i==null}});var Xi=f((vR,Uu)=>{"use strict";var $S=Gt(),LS=TypeError;Uu.exports=function(i){if($S(i))throw LS("Can't call method on "+i);return i}});var Yt=f((gR,Hu)=>{"use strict";var CS=Fu(),MS=Xi();Hu.exports=function(i){return CS(MS(i))}});var Os=f((yR,ju)=>{"use strict";ju.exports=function(){}});var St=f((TR,Gu)=>{"use strict";Gu.exports={}});var j=f((Yu,Wu)=>{"use strict";var Zi=function(i){return i&&i.Math==Math&&i};Wu.exports=Zi(typeof globalThis=="object"&&globalThis)||Zi(typeof window=="object"&&window)||Zi(typeof self=="object"&&self)||Zi(typeof global=="object"&&global)||function(){return this}()||Yu||Function("return this")()});var Bs=f((IR,Qu)=>{"use strict";var Vs=typeof document=="object"&&document.all,DS=typeof Vs>"u"&&Vs!==void 0;Qu.exports={all:Vs,IS_HTMLDDA:DS}});var F=f((ER,Ku)=>{"use strict";var zu=Bs(),OS=zu.all;Ku.exports=zu.IS_HTMLDDA?function(i){return typeof i=="function"||i===OS}:function(i){return typeof i=="function"}});var Zu=f((xR,Xu)=>{"use strict";var VS=j(),BS=F(),Ju=VS.WeakMap;Xu.exports=BS(Ju)&&/native code/.test(String(Ju))});var De=f((PR,rl)=>{"use strict";var el=F(),tl=Bs(),_S=tl.all;rl.exports=tl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:el(i)||i===_S}:function(i){return typeof i=="object"?i!==null:el(i)}});var Oe=f((kR,il)=>{"use strict";var NS=pe();il.exports=!NS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var ea=f((AR,sl)=>{"use strict";var FS=j(),al=De(),_s=FS.document,qS=al(_s)&&al(_s.createElement);sl.exports=function(i){return qS?_s.createElement(i):{}}});var Ns=f((wR,nl)=>{"use strict";var US=Oe(),HS=pe(),jS=ea();nl.exports=!US&&!HS(function(){return Object.defineProperty(jS("div"),"a",{get:function(){return 7}}).a!=7})});var Fs=f((RR,ol)=>{"use strict";var GS=Oe(),YS=pe();ol.exports=GS&&YS(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Pe=f(($R,ul)=>{"use strict";var WS=De(),QS=String,zS=TypeError;ul.exports=function(i){if(WS(i))return i;throw zS(QS(i)+" is not an object")}});var te=f((LR,ll)=>{"use strict";var KS=xr(),ta=Function.prototype.call;ll.exports=KS?ta.bind(ta):function(){return ta.apply(ta,arguments)}});var ra=f((CR,cl)=>{"use strict";cl.exports={}});var Ne=f((MR,pl)=>{"use strict";var qs=ra(),Us=j(),JS=F(),dl=function(i){return JS(i)?i:void 0};pl.exports=function(i,e){return arguments.length<2?dl(qs[i])||dl(Us[i]):qs[i]&&qs[i][e]||Us[i]&&Us[i][e]}});var Pr=f((DR,hl)=>{"use strict";var XS=ee();hl.exports=XS({}.isPrototypeOf)});var kr=f((OR,fl)=>{"use strict";fl.exports=typeof navigator<"u"&&String(navigator.userAgent)||""});var js=f((VR,yl)=>{"use strict";var gl=j(),Hs=kr(),ml=gl.process,bl=gl.Deno,Sl=ml&&ml.versions||bl&&bl.version,vl=Sl&&Sl.v8,ke,ia;vl&&(ke=vl.split("."),ia=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!ia&&Hs&&(ke=Hs.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=Hs.match(/Chrome\/(\d+)/),ke&&(ia=+ke[1])));yl.exports=ia});var Gs=f((BR,Il)=>{"use strict";var Tl=js(),ZS=pe(),ev=j(),tv=ev.String;Il.exports=!!Object.getOwnPropertySymbols&&!ZS(function(){var i=Symbol();return!tv(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Tl&&Tl<41})});var Ys=f((_R,El)=>{"use strict";var rv=Gs();El.exports=rv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Ws=f((NR,xl)=>{"use strict";var iv=Ne(),av=F(),sv=Pr(),nv=Ys(),ov=Object;xl.exports=nv?function(i){return typeof i=="symbol"}:function(i){var e=iv("Symbol");return av(e)&&sv(e.prototype,ov(i))}});var Ar=f((FR,Pl)=>{"use strict";var uv=String;Pl.exports=function(i){try{return uv(i)}catch{return"Object"}}});var Fe=f((qR,kl)=>{"use strict";var lv=F(),cv=Ar(),dv=TypeError;kl.exports=function(i){if(lv(i))return i;throw dv(cv(i)+" is not a function")}});var wr=f((UR,Al)=>{"use strict";var pv=Fe(),hv=Gt();Al.exports=function(i,e){var t=i[e];return hv(t)?void 0:pv(t)}});var Rl=f((HR,wl)=>{"use strict";var Qs=te(),zs=F(),Ks=De(),fv=TypeError;wl.exports=function(i,e){var t,r;if(e==="string"&&zs(t=i.toString)&&!Ks(r=Qs(t,i))||zs(t=i.valueOf)&&!Ks(r=Qs(t,i))||e!=="string"&&zs(t=i.toString)&&!Ks(r=Qs(t,i)))return r;throw fv("Can't convert object to primitive value")}});var Ae=f((jR,$l)=>{"use strict";$l.exports=!0});var Ml=f((GR,Cl)=>{"use strict";var Ll=j(),mv=Object.defineProperty;Cl.exports=function(i,e){try{mv(Ll,i,{value:e,configurable:!0,writable:!0})}catch{Ll[i]=e}return e}});var aa=f((YR,Ol)=>{"use strict";var bv=j(),Sv=Ml(),Dl="__core-js_shared__",vv=bv[Dl]||Sv(Dl,{});Ol.exports=vv});var Js=f((WR,Bl)=>{"use strict";var gv=Ae(),Vl=aa();(Bl.exports=function(i,e){return Vl[i]||(Vl[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:gv?"pure":"global",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Rr=f((QR,_l)=>{"use strict";var yv=Xi(),Tv=Object;_l.exports=function(i){return Tv(yv(i))}});var we=f((zR,Nl)=>{"use strict";var Iv=ee(),Ev=Rr(),xv=Iv({}.hasOwnProperty);Nl.exports=Object.hasOwn||function(e,t){return xv(Ev(e),t)}});var Xs=f((KR,Fl)=>{"use strict";var Pv=ee(),kv=0,Av=Math.random(),wv=Pv(1 .toString);Fl.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+wv(++kv+Av,36)}});var Q=f((JR,Ul)=>{"use strict";var Rv=j(),$v=Js(),ql=we(),Lv=Xs(),Cv=Gs(),Mv=Ys(),Wt=Rv.Symbol,Zs=$v("wks"),Dv=Mv?Wt.for||Wt:Wt&&Wt.withoutSetter||Lv;Ul.exports=function(i){return ql(Zs,i)||(Zs[i]=Cv&&ql(Wt,i)?Wt[i]:Dv("Symbol."+i)),Zs[i]}});var Yl=f((XR,Gl)=>{"use strict";var Ov=te(),Hl=De(),jl=Ws(),Vv=wr(),Bv=Rl(),_v=Q(),Nv=TypeError,Fv=_v("toPrimitive");Gl.exports=function(i,e){if(!Hl(i)||jl(i))return i;var t=Vv(i,Fv),r;if(t){if(e===void 0&&(e="default"),r=Ov(t,i,e),!Hl(r)||jl(r))return r;throw Nv("Can't convert object to primitive value")}return e===void 0&&(e="number"),Bv(i,e)}});var sa=f((ZR,Wl)=>{"use strict";var qv=Yl(),Uv=Ws();Wl.exports=function(i){var e=qv(i,"string");return Uv(e)?e:e+""}});var vt=f(zl=>{"use strict";var Hv=Oe(),jv=Ns(),Gv=Fs(),na=Pe(),Ql=sa(),Yv=TypeError,en=Object.defineProperty,Wv=Object.getOwnPropertyDescriptor,tn="enumerable",rn="configurable",an="writable";zl.f=Hv?Gv?function(e,t,r){if(na(e),t=Ql(t),na(r),typeof e=="function"&&t==="prototype"&&"value"in r&&an in r&&!r[an]){var a=Wv(e,t);a&&a[an]&&(e[t]=r.value,r={configurable:rn in r?r[rn]:a[rn],enumerable:tn in r?r[tn]:a[tn],writable:!1})}return en(e,t,r)}:en:function(e,t,r){if(na(e),t=Ql(t),na(r),jv)try{return en(e,t,r)}catch{}if("get"in r||"set"in r)throw Yv("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var $r=f((t$,Kl)=>{"use strict";Kl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var gt=f((r$,Jl)=>{"use strict";var Qv=Oe(),zv=vt(),Kv=$r();Jl.exports=Qv?function(i,e,t){return zv.f(i,e,Kv(1,t))}:function(i,e,t){return i[e]=t,i}});var oa=f((i$,Zl)=>{"use strict";var Jv=Js(),Xv=Xs(),Xl=Jv("keys");Zl.exports=function(i){return Xl[i]||(Xl[i]=Xv(i))}});var ua=f((a$,ec)=>{"use strict";ec.exports={}});var un=f((s$,ic)=>{"use strict";var Zv=Zu(),rc=j(),eg=De(),tg=gt(),sn=we(),nn=aa(),rg=oa(),ig=ua(),tc="Object already initialized",on=rc.TypeError,ag=rc.WeakMap,la,Lr,ca,sg=function(i){return ca(i)?Lr(i):la(i,{})},ng=function(i){return function(e){var t;if(!eg(e)||(t=Lr(e)).type!==i)throw on("Incompatible receiver, "+i+" required");return t}};Zv||nn.state?(Re=nn.state||(nn.state=new ag),Re.get=Re.get,Re.has=Re.has,Re.set=Re.set,la=function(i,e){if(Re.has(i))throw on(tc);return e.facade=i,Re.set(i,e),e},Lr=function(i){return Re.get(i)||{}},ca=function(i){return Re.has(i)}):(yt=rg("state"),ig[yt]=!0,la=function(i,e){if(sn(i,yt))throw on(tc);return e.facade=i,tg(i,yt,e),e},Lr=function(i){return sn(i,yt)?i[yt]:{}},ca=function(i){return sn(i,yt)});var Re,yt;ic.exports={set:la,get:Lr,has:ca,enforce:sg,getterFor:ng}});var ln=f((n$,oc)=>{"use strict";var og=xr(),nc=Function.prototype,ac=nc.apply,sc=nc.call;oc.exports=typeof Reflect=="object"&&Reflect.apply||(og?sc.bind(ac):function(){return sc.apply(ac,arguments)})});var cn=f((o$,uc)=>{"use strict";var ug=jt(),lg=ee();uc.exports=function(i){if(ug(i)==="Function")return lg(i)}});var pc=f(dc=>{"use strict";var lc={}.propertyIsEnumerable,cc=Object.getOwnPropertyDescriptor,cg=cc&&!lc.call({1:2},1);dc.f=cg?function(e){var t=cc(this,e);return!!t&&t.enumerable}:lc});var dn=f(fc=>{"use strict";var dg=Oe(),pg=te(),hg=pc(),fg=$r(),mg=Yt(),bg=sa(),Sg=we(),vg=Ns(),hc=Object.getOwnPropertyDescriptor;fc.f=dg?hc:function(e,t){if(e=mg(e),t=bg(t),vg)try{return hc(e,t)}catch{}if(Sg(e,t))return fg(!pg(hg.f,e,t),e[t])}});var pn=f((c$,mc)=>{"use strict";var gg=pe(),yg=F(),Tg=/#|\.prototype\./,Cr=function(i,e){var t=Eg[Ig(i)];return t==Pg?!0:t==xg?!1:yg(e)?gg(e):!!e},Ig=Cr.normalize=function(i){return String(i).replace(Tg,".").toLowerCase()},Eg=Cr.data={},xg=Cr.NATIVE="N",Pg=Cr.POLYFILL="P";mc.exports=Cr});var Mr=f((d$,Sc)=>{"use strict";var bc=cn(),kg=Fe(),Ag=xr(),wg=bc(bc.bind);Sc.exports=function(i,e){return kg(i),e===void 0?i:Ag?wg(i,e):function(){return i.apply(e,arguments)}}});var Se=f((p$,gc)=>{"use strict";var da=j(),Rg=ln(),$g=cn(),Lg=F(),Cg=dn().f,Mg=pn(),Qt=ra(),Dg=Mr(),zt=gt(),vc=we(),Og=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return Rg(i,this,arguments)};return e.prototype=i.prototype,e};gc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?da:a?da[t]:(da[t]||{}).prototype,o=r?Qt:Qt[t]||zt(Qt,t,{})[t],l=o.prototype,u,d,c,p,h,m,S,v,g;for(p in e)u=Mg(r?p:t+(a?".":"#")+p,i.forced),d=!u&&n&&vc(n,p),m=o[p],d&&(i.dontCallGetSet?(g=Cg(n,p),S=g&&g.value):S=n[p]),h=d&&S?S:e[p],!(d&&typeof m==typeof h)&&(i.bind&&d?v=Dg(h,da):i.wrap&&d?v=Og(h):s&&Lg(h)?v=$g(h):v=h,(i.sham||h&&h.sham||m&&m.sham)&&zt(v,"sham",!0),zt(o,p,v),s&&(c=t+"Prototype",vc(Qt,c)||zt(Qt,c,{}),zt(Qt[c],p,h),i.real&&l&&(u||!l[p])&&zt(l,p,h)))}});var Ic=f((h$,Tc)=>{"use strict";var hn=Oe(),Vg=we(),yc=Function.prototype,Bg=hn&&Object.getOwnPropertyDescriptor,fn=Vg(yc,"name"),_g=fn&&function(){}.name==="something",Ng=fn&&(!hn||hn&&Bg(yc,"name").configurable);Tc.exports={EXISTS:fn,PROPER:_g,CONFIGURABLE:Ng}});var xc=f((f$,Ec)=>{"use strict";var Fg=Math.ceil,qg=Math.floor;Ec.exports=Math.trunc||function(e){var t=+e;return(t>0?qg:Fg)(t)}});var pa=f((m$,Pc)=>{"use strict";var Ug=xc();Pc.exports=function(i){var e=+i;return e!==e||e===0?0:Ug(e)}});var Ac=f((b$,kc)=>{"use strict";var Hg=pa(),jg=Math.max,Gg=Math.min;kc.exports=function(i,e){var t=Hg(i);return t<0?jg(t+e,0):Gg(t,e)}});var Rc=f((S$,wc)=>{"use strict";var Yg=pa(),Wg=Math.min;wc.exports=function(i){return i>0?Wg(Yg(i),9007199254740991):0}});var ha=f((v$,$c)=>{"use strict";var Qg=Rc();$c.exports=function(i){return Qg(i.length)}});var Mc=f((g$,Cc)=>{"use strict";var zg=Yt(),Kg=Ac(),Jg=ha(),Lc=function(i){return function(e,t,r){var a=zg(e),s=Jg(a),n=Kg(r,s),o;if(i&&t!=t){for(;s>n;)if(o=a[n++],o!=o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};Cc.exports={includes:Lc(!0),indexOf:Lc(!1)}});var Vc=f((y$,Oc)=>{"use strict";var Xg=ee(),mn=we(),Zg=Yt(),ey=Mc().indexOf,ty=ua(),Dc=Xg([].push);Oc.exports=function(i,e){var t=Zg(i),r=0,a=[],s;for(s in t)!mn(ty,s)&&mn(t,s)&&Dc(a,s);for(;e.length>r;)mn(t,s=e[r++])&&(~ey(a,s)||Dc(a,s));return a}});var bn=f((T$,Bc)=>{"use strict";Bc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Nc=f((I$,_c)=>{"use strict";var ry=Vc(),iy=bn();_c.exports=Object.keys||function(e){return ry(e,iy)}});var qc=f(Fc=>{"use strict";var ay=Oe(),sy=Fs(),ny=vt(),oy=Pe(),uy=Yt(),ly=Nc();Fc.f=ay&&!sy?Object.defineProperties:function(e,t){oy(e);for(var r=uy(t),a=ly(t),s=a.length,n=0,o;s>n;)ny.f(e,o=a[n++],r[o]);return e}});var Sn=f((x$,Uc)=>{"use strict";var cy=Ne();Uc.exports=cy("document","documentElement")});var Tn=f((P$,zc)=>{"use strict";var dy=Pe(),py=qc(),Hc=bn(),hy=ua(),fy=Sn(),my=ea(),by=oa(),jc=">",Gc="<",gn="prototype",yn="script",Wc=by("IE_PROTO"),vn=function(){},Qc=function(i){return Gc+yn+jc+i+Gc+"/"+yn+jc},Yc=function(i){i.write(Qc("")),i.close();var e=i.parentWindow.Object;return i=null,e},Sy=function(){var i=my("iframe"),e="java"+yn+":",t;return i.style.display="none",fy.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Qc("document.F=Object")),t.close(),t.F},fa,ma=function(){try{fa=new ActiveXObject("htmlfile")}catch{}ma=typeof document<"u"?document.domain&&fa?Yc(fa):Sy():Yc(fa);for(var i=Hc.length;i--;)delete ma[gn][Hc[i]];return ma()};hy[Wc]=!0;zc.exports=Object.create||function(e,t){var r;return e!==null?(vn[gn]=dy(e),r=new vn,vn[gn]=null,r[Wc]=e):r=ma(),t===void 0?r:py.f(r,t)}});var Jc=f((k$,Kc)=>{"use strict";var vy=pe();Kc.exports=!vy(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var En=f((A$,Zc)=>{"use strict";var gy=we(),yy=F(),Ty=Rr(),Iy=oa(),Ey=Jc(),Xc=Iy("IE_PROTO"),In=Object,xy=In.prototype;Zc.exports=Ey?In.getPrototypeOf:function(i){var e=Ty(i);if(gy(e,Xc))return e[Xc];var t=e.constructor;return yy(t)&&e instanceof t?t.prototype:e instanceof In?xy:null}});var Kt=f((w$,ed)=>{"use strict";var Py=gt();ed.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Py(i,e,t),i}});var An=f((R$,id)=>{"use strict";var ky=pe(),Ay=F(),wy=De(),Ry=Tn(),td=En(),$y=Kt(),Ly=Q(),Cy=Ae(),kn=Ly("iterator"),rd=!1,qe,xn,Pn;[].keys&&(Pn=[].keys(),"next"in Pn?(xn=td(td(Pn)),xn!==Object.prototype&&(qe=xn)):rd=!0);var My=!wy(qe)||ky(function(){var i={};return qe[kn].call(i)!==i});My?qe={}:Cy&&(qe=Ry(qe));Ay(qe[kn])||$y(qe,kn,function(){return this});id.exports={IteratorPrototype:qe,BUGGY_SAFARI_ITERATORS:rd}});var ba=f(($$,sd)=>{"use strict";var Dy=Q(),Oy=Dy("toStringTag"),ad={};ad[Oy]="z";sd.exports=String(ad)==="[object z]"});var Jt=f((L$,nd)=>{"use strict";var Vy=ba(),By=F(),Sa=jt(),_y=Q(),Ny=_y("toStringTag"),Fy=Object,qy=Sa(function(){return arguments}())=="Arguments",Uy=function(i,e){try{return i[e]}catch{}};nd.exports=Vy?Sa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Uy(e=Fy(i),Ny))=="string"?t:qy?Sa(e):(r=Sa(e))=="Object"&&By(e.callee)?"Arguments":r}});var ud=f((C$,od)=>{"use strict";var Hy=ba(),jy=Jt();od.exports=Hy?{}.toString:function(){return"[object "+jy(this)+"]"}});var va=f((M$,cd)=>{"use strict";var Gy=ba(),Yy=vt().f,Wy=gt(),Qy=we(),zy=ud(),Ky=Q(),ld=Ky("toStringTag");cd.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;Qy(a,ld)||Yy(a,ld,{configurable:!0,value:e}),r&&!Gy&&Wy(a,"toString",zy)}}});var pd=f((D$,dd)=>{"use strict";var Jy=An().IteratorPrototype,Xy=Tn(),Zy=$r(),eT=va(),tT=St(),rT=function(){return this};dd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=Xy(Jy,{next:Zy(+!r,t)}),eT(i,a,!1,!0),tT[a]=rT,i}});var fd=f((O$,hd)=>{"use strict";var iT=ee(),aT=Fe();hd.exports=function(i,e,t){try{return iT(aT(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var bd=f((V$,md)=>{"use strict";var sT=F(),nT=String,oT=TypeError;md.exports=function(i){if(typeof i=="object"||sT(i))return i;throw oT("Can't set "+nT(i)+" as a prototype")}});var wn=f((B$,Sd)=>{"use strict";var uT=fd(),lT=Pe(),cT=bd();Sd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=uT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return lT(a),cT(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var wd=f((_$,Ad)=>{"use strict";var dT=Se(),pT=te(),ga=Ae(),Pd=Ic(),hT=F(),fT=pd(),vd=En(),gd=wn(),mT=va(),bT=gt(),Rn=Kt(),ST=Q(),yd=St(),kd=An(),vT=Pd.PROPER,gT=Pd.CONFIGURABLE,Td=kd.IteratorPrototype,ya=kd.BUGGY_SAFARI_ITERATORS,Dr=ST("iterator"),Id="keys",Or="values",Ed="entries",xd=function(){return this};Ad.exports=function(i,e,t,r,a,s,n){fT(t,e,r);var o=function(g){if(g===a&&p)return p;if(!ya&&g in d)return d[g];switch(g){case Id:return function(){return new t(this,g)};case Or:return function(){return new t(this,g)};case Ed:return function(){return new t(this,g)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,d=i.prototype,c=d[Dr]||d["@@iterator"]||a&&d[a],p=!ya&&c||o(a),h=e=="Array"&&d.entries||c,m,S,v;if(h&&(m=vd(h.call(new i)),m!==Object.prototype&&m.next&&(!ga&&vd(m)!==Td&&(gd?gd(m,Td):hT(m[Dr])||Rn(m,Dr,xd)),mT(m,l,!0,!0),ga&&(yd[l]=xd))),vT&&a==Or&&c&&c.name!==Or&&(!ga&&gT?bT(d,"name",Or):(u=!0,p=function(){return pT(c,this)})),a)if(S={values:o(Or),keys:s?p:o(Id),entries:o(Ed)},n)for(v in S)(ya||u||!(v in d))&&Rn(d,v,S[v]);else dT({target:e,proto:!0,forced:ya||u},S);return(!ga||n)&&d[Dr]!==p&&Rn(d,Dr,p,{name:a}),yd[e]=p,S}});var $d=f((N$,Rd)=>{"use strict";Rd.exports=function(i,e){return{value:i,done:e}}});var Ln=f((F$,Od)=>{"use strict";var yT=Yt(),$n=Os(),Ld=St(),Md=un(),TT=vt().f,IT=wd(),Ta=$d(),ET=Ae(),xT=Oe(),Dd="Array Iterator",PT=Md.set,kT=Md.getterFor(Dd);Od.exports=IT(Array,"Array",function(i,e){PT(this,{type:Dd,target:yT(i),index:0,kind:e})},function(){var i=kT(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Ta(void 0,!0)):t=="keys"?Ta(r,!1):t=="values"?Ta(e[r],!1):Ta([r,e[r]],!1)},"values");var Cd=Ld.Arguments=Ld.Array;$n("keys");$n("values");$n("entries");if(!ET&&xT&&Cd.name!=="values")try{TT(Cd,"name",{value:"values"})}catch{}});var Bd=f((q$,Vd)=>{"use strict";var AT=Q(),wT=St(),RT=AT("iterator"),$T=Array.prototype;Vd.exports=function(i){return i!==void 0&&(wT.Array===i||$T[RT]===i)}});var Cn=f((U$,Nd)=>{"use strict";var LT=Jt(),_d=wr(),CT=Gt(),MT=St(),DT=Q(),OT=DT("iterator");Nd.exports=function(i){if(!CT(i))return _d(i,OT)||_d(i,"@@iterator")||MT[LT(i)]}});var qd=f((H$,Fd)=>{"use strict";var VT=te(),BT=Fe(),_T=Pe(),NT=Ar(),FT=Cn(),qT=TypeError;Fd.exports=function(i,e){var t=arguments.length<2?FT(i):e;if(BT(t))return _T(VT(t,i));throw qT(NT(i)+" is not iterable")}});var jd=f((j$,Hd)=>{"use strict";var UT=te(),Ud=Pe(),HT=wr();Hd.exports=function(i,e,t){var r,a;Ud(i);try{if(r=HT(i,"return"),!r){if(e==="throw")throw t;return t}r=UT(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Ud(r),t}});var Ea=f((G$,Qd)=>{"use strict";var jT=Mr(),GT=te(),YT=Pe(),WT=Ar(),QT=Bd(),zT=ha(),Gd=Pr(),KT=qd(),JT=Cn(),Yd=jd(),XT=TypeError,Ia=function(i,e){this.stopped=i,this.result=e},Wd=Ia.prototype;Qd.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),l=jT(e,r),u,d,c,p,h,m,S,v=function(k){return u&&Yd(u,"normal",k),new Ia(!0,k)},g=function(k){return a?(YT(k),o?l(k[0],k[1],v):l(k[0],k[1])):o?l(k,v):l(k)};if(s)u=i.iterator;else if(n)u=i;else{if(d=JT(i),!d)throw XT(WT(i)+" is not iterable");if(QT(d)){for(c=0,p=zT(i);p>c;c++)if(h=g(i[c]),h&&Gd(Wd,h))return h;return new Ia(!1)}u=KT(i,d)}for(m=s?i.next:u.next;!(S=GT(m,u)).done;){try{h=g(S.value)}catch(k){Yd(u,"throw",k)}if(typeof h=="object"&&h&&Gd(Wd,h))return h}return new Ia(!1)}});var Kd=f((Y$,zd)=>{"use strict";var ZT=sa(),eI=vt(),tI=$r();zd.exports=function(i,e,t){var r=ZT(e);r in i?eI.f(i,r,tI(0,t)):i[r]=t}});var Jd=f(()=>{"use strict";var rI=Se(),iI=Ea(),aI=Kd();rI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return iI(e,function(r,a){aI(t,r,a)},{AS_ENTRIES:!0}),t}})});var Zd=f((z$,Xd)=>{"use strict";Ln();Jd();var sI=ra();Xd.exports=sI.Object.fromEntries});var tp=f((K$,ep)=>{"use strict";ep.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 ap=f(()=>{"use strict";Ln();var nI=tp(),oI=j(),uI=Jt(),lI=gt(),rp=St(),cI=Q(),ip=cI("toStringTag");for(xa in nI)Mn=oI[xa],Pa=Mn&&Mn.prototype,Pa&&uI(Pa)!==ip&&lI(Pa,ip,xa),rp[xa]=rp.Array;var Mn,Pa,xa});var np=f((Z$,sp)=>{"use strict";var dI=Zd();ap();sp.exports=dI});var Dn=f((eL,op)=>{"use strict";var pI=np();op.exports=pI});var up=f(()=>{"use strict"});var Vr=f((iL,lp)=>{"use strict";var hI=jt();lp.exports=typeof process<"u"&&hI(process)=="process"});var dp=f((aL,cp)=>{"use strict";var fI=vt();cp.exports=function(i,e,t){return fI.f(i,e,t)}});var fp=f((sL,hp)=>{"use strict";var mI=Ne(),bI=dp(),SI=Q(),vI=Oe(),pp=SI("species");hp.exports=function(i){var e=mI(i);vI&&e&&!e[pp]&&bI(e,pp,{configurable:!0,get:function(){return this}})}});var bp=f((nL,mp)=>{"use strict";var gI=Pr(),yI=TypeError;mp.exports=function(i,e){if(gI(e,i))return i;throw yI("Incorrect invocation")}});var Vn=f((oL,Sp)=>{"use strict";var TI=ee(),II=F(),On=aa(),EI=TI(Function.toString);II(On.inspectSource)||(On.inspectSource=function(i){return EI(i)});Sp.exports=On.inspectSource});var Ep=f((uL,Ip)=>{"use strict";var xI=ee(),PI=pe(),vp=F(),kI=Jt(),AI=Ne(),wI=Vn(),gp=function(){},RI=[],yp=AI("Reflect","construct"),Bn=/^\s*(?:class|function)\b/,$I=xI(Bn.exec),LI=!Bn.exec(gp),Br=function(e){if(!vp(e))return!1;try{return yp(gp,RI,e),!0}catch{return!1}},Tp=function(e){if(!vp(e))return!1;switch(kI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return LI||!!$I(Bn,wI(e))}catch{return!0}};Tp.sham=!0;Ip.exports=!yp||PI(function(){var i;return Br(Br.call)||!Br(Object)||!Br(function(){i=!0})||i})?Tp:Br});var Pp=f((lL,xp)=>{"use strict";var CI=Ep(),MI=Ar(),DI=TypeError;xp.exports=function(i){if(CI(i))return i;throw DI(MI(i)+" is not a constructor")}});var _n=f((cL,Ap)=>{"use strict";var kp=Pe(),OI=Pp(),VI=Gt(),BI=Q(),_I=BI("species");Ap.exports=function(i,e){var t=kp(i).constructor,r;return t===void 0||VI(r=kp(t)[_I])?e:OI(r)}});var Rp=f((dL,wp)=>{"use strict";var NI=ee();wp.exports=NI([].slice)});var Lp=f((pL,$p)=>{"use strict";var FI=TypeError;$p.exports=function(i,e){if(i<e)throw FI("Not enough arguments");return i}});var Nn=f((hL,Cp)=>{"use strict";var qI=kr();Cp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(qI)});var Qn=f((fL,qp)=>{"use strict";var he=j(),UI=ln(),HI=Mr(),Mp=F(),jI=we(),Fp=pe(),Dp=Sn(),GI=Rp(),Op=ea(),YI=Lp(),WI=Nn(),QI=Vr(),Gn=he.setImmediate,Yn=he.clearImmediate,zI=he.process,Fn=he.Dispatch,KI=he.Function,Vp=he.MessageChannel,JI=he.String,qn=0,_r={},Bp="onreadystatechange",Nr,Tt,Un,Hn;Fp(function(){Nr=he.location});var Wn=function(i){if(jI(_r,i)){var e=_r[i];delete _r[i],e()}},jn=function(i){return function(){Wn(i)}},_p=function(i){Wn(i.data)},Np=function(i){he.postMessage(JI(i),Nr.protocol+"//"+Nr.host)};(!Gn||!Yn)&&(Gn=function(e){YI(arguments.length,1);var t=Mp(e)?e:KI(e),r=GI(arguments,1);return _r[++qn]=function(){UI(t,void 0,r)},Tt(qn),qn},Yn=function(e){delete _r[e]},QI?Tt=function(i){zI.nextTick(jn(i))}:Fn&&Fn.now?Tt=function(i){Fn.now(jn(i))}:Vp&&!WI?(Un=new Vp,Hn=Un.port2,Un.port1.onmessage=_p,Tt=HI(Hn.postMessage,Hn)):he.addEventListener&&Mp(he.postMessage)&&!he.importScripts&&Nr&&Nr.protocol!=="file:"&&!Fp(Np)?(Tt=Np,he.addEventListener("message",_p,!1)):Bp in Op("script")?Tt=function(i){Dp.appendChild(Op("script"))[Bp]=function(){Dp.removeChild(this),Wn(i)}}:Tt=function(i){setTimeout(jn(i),0)});qp.exports={set:Gn,clear:Yn}});var zn=f((mL,Hp)=>{"use strict";var Up=function(){this.head=null,this.tail=null};Up.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};Hp.exports=Up});var Gp=f((bL,jp)=>{"use strict";var XI=kr();jp.exports=/ipad|iphone|ipod/i.test(XI)&&typeof Pebble<"u"});var Wp=f((SL,Yp)=>{"use strict";var ZI=kr();Yp.exports=/web0s(?!.*chrome)/i.test(ZI)});var th=f((vL,eh)=>{"use strict";var It=j(),Qp=Mr(),eE=dn().f,Kn=Qn().set,tE=zn(),rE=Nn(),iE=Gp(),aE=Wp(),Jn=Vr(),zp=It.MutationObserver||It.WebKitMutationObserver,Kp=It.document,Jp=It.process,ka=It.Promise,Xp=eE(It,"queueMicrotask"),eo=Xp&&Xp.value,Xt,Xn,Zn,Aa,Zp;eo||(Fr=new tE,qr=function(){var i,e;for(Jn&&(i=Jp.domain)&&i.exit();e=Fr.get();)try{e()}catch(t){throw Fr.head&&Xt(),t}i&&i.enter()},!rE&&!Jn&&!aE&&zp&&Kp?(Xn=!0,Zn=Kp.createTextNode(""),new zp(qr).observe(Zn,{characterData:!0}),Xt=function(){Zn.data=Xn=!Xn}):!iE&&ka&&ka.resolve?(Aa=ka.resolve(void 0),Aa.constructor=ka,Zp=Qp(Aa.then,Aa),Xt=function(){Zp(qr)}):Jn?Xt=function(){Jp.nextTick(qr)}:(Kn=Qp(Kn,It),Xt=function(){Kn(qr)}),eo=function(i){Fr.head||Xt(),Fr.add(i)});var Fr,qr;eh.exports=eo});var ih=f((gL,rh)=>{"use strict";rh.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch{}}});var wa=f((yL,ah)=>{"use strict";ah.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Et=f((TL,sh)=>{"use strict";var sE=j();sh.exports=sE.Promise});var to=f((IL,nh)=>{"use strict";nh.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var uh=f((EL,oh)=>{"use strict";var nE=to(),oE=Vr();oh.exports=!nE&&!oE&&typeof window=="object"&&typeof document=="object"});var Zt=f((xL,dh)=>{"use strict";var uE=j(),Ur=Et(),lE=F(),cE=pn(),dE=Vn(),pE=Q(),hE=uh(),fE=to(),mE=Ae(),ro=js(),lh=Ur&&Ur.prototype,bE=pE("species"),io=!1,ch=lE(uE.PromiseRejectionEvent),SE=cE("Promise",function(){var i=dE(Ur),e=i!==String(Ur);if(!e&&ro===66||mE&&!(lh.catch&&lh.finally))return!0;if(!ro||ro<51||!/native code/.test(i)){var t=new Ur(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[bE]=r,io=t.then(function(){})instanceof r,!io)return!0}return!e&&(hE||fE)&&!ch});dh.exports={CONSTRUCTOR:SE,REJECTION_EVENT:ch,SUBCLASSING:io}});var er=f((PL,hh)=>{"use strict";var ph=Fe(),vE=TypeError,gE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw vE("Bad Promise constructor");e=r,t=a}),this.resolve=ph(e),this.reject=ph(t)};hh.exports.f=function(i){return new gE(i)}});var Ch=f(()=>{"use strict";var yE=Se(),TE=Ae(),Ca=Vr(),Ze=j(),ar=te(),fh=Kt(),mh=wn(),IE=va(),EE=fp(),xE=Fe(),La=F(),PE=De(),kE=bp(),AE=_n(),yh=Qn().set,uo=th(),wE=ih(),RE=wa(),$E=zn(),Th=un(),Ma=Et(),lo=Zt(),Ih=er(),Da="Promise",Eh=lo.CONSTRUCTOR,LE=lo.REJECTION_EVENT,CE=lo.SUBCLASSING,ao=Th.getterFor(Da),ME=Th.set,tr=Ma&&Ma.prototype,xt=Ma,Ra=tr,xh=Ze.TypeError,so=Ze.document,co=Ze.process,no=Ih.f,DE=no,OE=!!(so&&so.createEvent&&Ze.dispatchEvent),Ph="unhandledrejection",VE="rejectionhandled",bh=0,kh=1,BE=2,po=1,Ah=2,$a,Sh,_E,vh,wh=function(i){var e;return PE(i)&&La(e=i.then)?e:!1},Rh=function(i,e){var t=e.value,r=e.state==kh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,d;try{a?(r||(e.rejection===Ah&&FE(e),e.rejection=po),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),d=!0)),l===i.promise?n(xh("Promise-chain cycle")):(u=wh(l))?ar(u,l,s,n):s(l)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},$h=function(i,e){i.notified||(i.notified=!0,uo(function(){for(var t=i.reactions,r;r=t.get();)Rh(r,i);i.notified=!1,e&&!i.rejection&&NE(i)}))},Lh=function(i,e,t){var r,a;OE?(r=so.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Ze.dispatchEvent(r)):r={promise:e,reason:t},!LE&&(a=Ze["on"+i])?a(r):i===Ph&&wE("Unhandled promise rejection",t)},NE=function(i){ar(yh,Ze,function(){var e=i.facade,t=i.value,r=gh(i),a;if(r&&(a=RE(function(){Ca?co.emit("unhandledRejection",t,e):Lh(Ph,e,t)}),i.rejection=Ca||gh(i)?Ah:po,a.error))throw a.value})},gh=function(i){return i.rejection!==po&&!i.parent},FE=function(i){ar(yh,Ze,function(){var e=i.facade;Ca?co.emit("rejectionHandled",e):Lh(VE,e,i.value)})},rr=function(i,e,t){return function(r){i(e,r,t)}},ir=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=BE,$h(i,!0))},oo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw xh("Promise can't be resolved itself");var r=wh(e);r?uo(function(){var a={done:!1};try{ar(r,e,rr(oo,a,i),rr(ir,a,i))}catch(s){ir(a,s,i)}}):(i.value=e,i.state=kh,$h(i,!1))}catch(a){ir({done:!1},a,i)}}};if(Eh&&(xt=function(e){kE(this,Ra),xE(e),ar($a,this);var t=ao(this);try{e(rr(oo,t),rr(ir,t))}catch(r){ir(t,r)}},Ra=xt.prototype,$a=function(e){ME(this,{type:Da,done:!1,notified:!1,parent:!1,reactions:new $E,rejection:!1,state:bh,value:void 0})},$a.prototype=fh(Ra,"then",function(e,t){var r=ao(this),a=no(AE(this,xt));return r.parent=!0,a.ok=La(e)?e:!0,a.fail=La(t)&&t,a.domain=Ca?co.domain:void 0,r.state==bh?r.reactions.add(a):uo(function(){Rh(a,r)}),a.promise}),Sh=function(){var i=new $a,e=ao(i);this.promise=i,this.resolve=rr(oo,e),this.reject=rr(ir,e)},Ih.f=no=function(i){return i===xt||i===_E?new Sh(i):DE(i)},!TE&&La(Ma)&&tr!==Object.prototype)){vh=tr.then,CE||fh(tr,"then",function(e,t){var r=this;return new xt(function(a,s){ar(vh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete tr.constructor}catch{}mh&&mh(tr,Ra)}yE({global:!0,constructor:!0,wrap:!0,forced:Eh},{Promise:xt});IE(xt,Da,!1,!0);EE(Da)});var Bh=f((wL,Vh)=>{"use strict";var qE=Q(),Dh=qE("iterator"),Oh=!1;try{Mh=0,ho={next:function(){return{done:!!Mh++}},return:function(){Oh=!0}},ho[Dh]=function(){return this},Array.from(ho,function(){throw 2})}catch{}var Mh,ho;Vh.exports=function(i,e){if(!e&&!Oh)return!1;var t=!1;try{var r={};r[Dh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var fo=f((RL,_h)=>{"use strict";var UE=Et(),HE=Bh(),jE=Zt().CONSTRUCTOR;_h.exports=jE||!HE(function(i){UE.all(i).then(void 0,function(){})})});var Nh=f(()=>{"use strict";var GE=Se(),YE=te(),WE=Fe(),QE=er(),zE=wa(),KE=Ea(),JE=fo();GE({target:"Promise",stat:!0,forced:JE},{all:function(e){var t=this,r=QE.f(t),a=r.resolve,s=r.reject,n=zE(function(){var o=WE(t.resolve),l=[],u=0,d=1;KE(e,function(c){var p=u++,h=!1;d++,YE(o,t,c).then(function(m){h||(h=!0,l[p]=m,--d||a(l))},s)}),--d||a(l)});return n.error&&s(n.value),r.promise}})});var qh=f(()=>{"use strict";var XE=Se(),ZE=Ae(),ex=Zt().CONSTRUCTOR,bo=Et(),tx=Ne(),rx=F(),ix=Kt(),Fh=bo&&bo.prototype;XE({target:"Promise",proto:!0,forced:ex,real:!0},{catch:function(i){return this.then(void 0,i)}});!ZE&&rx(bo)&&(mo=tx("Promise").prototype.catch,Fh.catch!==mo&&ix(Fh,"catch",mo,{unsafe:!0}));var mo});var Uh=f(()=>{"use strict";var ax=Se(),sx=te(),nx=Fe(),ox=er(),ux=wa(),lx=Ea(),cx=fo();ax({target:"Promise",stat:!0,forced:cx},{race:function(e){var t=this,r=ox.f(t),a=r.reject,s=ux(function(){var n=nx(t.resolve);lx(e,function(o){sx(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Hh=f(()=>{"use strict";var dx=Se(),px=te(),hx=er(),fx=Zt().CONSTRUCTOR;dx({target:"Promise",stat:!0,forced:fx},{reject:function(e){var t=hx.f(this);return px(t.reject,void 0,e),t.promise}})});var So=f((_L,jh)=>{"use strict";var mx=Pe(),bx=De(),Sx=er();jh.exports=function(i,e){if(mx(i),bx(e)&&e.constructor===i)return e;var t=Sx.f(i),r=t.resolve;return r(e),t.promise}});var Wh=f(()=>{"use strict";var vx=Se(),gx=Ne(),Gh=Ae(),yx=Et(),Yh=Zt().CONSTRUCTOR,Tx=So(),Ix=gx("Promise"),Ex=Gh&&!Yh;vx({target:"Promise",stat:!0,forced:Gh||Yh},{resolve:function(e){return Tx(Ex&&this===Ix?yx:this,e)}})});var Qh=f(()=>{"use strict";Ch();Nh();qh();Uh();Hh();Wh()});var Xh=f(()=>{"use strict";var xx=Se(),Px=Ae(),Oa=Et(),kx=pe(),Kh=Ne(),Jh=F(),Ax=_n(),zh=So(),wx=Kt(),go=Oa&&Oa.prototype,Rx=!!Oa&&kx(function(){go.finally.call({then:function(){}},function(){})});xx({target:"Promise",proto:!0,real:!0,forced:Rx},{finally:function(i){var e=Ax(this,Kh("Promise")),t=Jh(i);return this.then(t?function(r){return zh(e,i()).then(function(){return r})}:i,t?function(r){return zh(e,i()).then(function(){throw r})}:i)}});!Px&&Jh(Oa)&&(vo=Kh("Promise").prototype.finally,go.finally!==vo&&wx(go,"finally",vo,{unsafe:!0}));var vo});var Va=f((GL,Zh)=>{"use strict";var $x=Ne();Zh.exports=$x});var tf=f((YL,ef)=>{"use strict";up();Qh();Xh();var Lx=Va();ef.exports=Lx("Promise","finally")});var af=f((WL,rf)=>{"use strict";var Cx=tf();rf.exports=Cx});var Ba=f((QL,sf)=>{"use strict";var Mx=af();sf.exports=Mx});var Rf=f(()=>{"use strict";var sP=Se(),nP=Rr(),oP=ha(),uP=pa(),lP=Os();sP({target:"Array",proto:!0},{at:function(e){var t=nP(this),r=oP(t),a=uP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});lP("at")});var Lf=f((iM,$f)=>{"use strict";Rf();var cP=Va();$f.exports=cP("Array","at")});var Mf=f((aM,Cf)=>{"use strict";var dP=Lf();Cf.exports=dP});var Fa=f((sM,Df)=>{"use strict";var pP=Mf();Df.exports=pP});var Tm=f(()=>{"use strict"});var Im=f(()=>{"use strict"});var xm=f((iV,Em)=>{"use strict";var Pk=De(),kk=jt(),Ak=Q(),wk=Ak("match");Em.exports=function(i){var e;return Pk(i)&&((e=i[wk])!==void 0?!!e:kk(i)=="RegExp")}});var km=f((aV,Pm)=>{"use strict";var Rk=Jt(),$k=String;Pm.exports=function(i){if(Rk(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return $k(i)}});var wm=f((sV,Am)=>{"use strict";var Lk=Pe();Am.exports=function(){var i=Lk(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var Lm=f((nV,$m)=>{"use strict";var Ck=te(),Mk=we(),Dk=Pr(),Ok=wm(),Rm=RegExp.prototype;$m.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Rm)&&!Mk(i,"flags")&&Dk(Rm,i)?Ck(Ok,i):e}});var Mm=f((oV,Cm)=>{"use strict";var Wo=ee(),Vk=Rr(),Bk=Math.floor,Go=Wo("".charAt),_k=Wo("".replace),Yo=Wo("".slice),Nk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Fk=/\$([$&'`]|\d{1,2})/g;Cm.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=Fk;return a!==void 0&&(a=Vk(a),l=Nk),_k(s,l,function(u,d){var c;switch(Go(d,0)){case"$":return"$";case"&":return i;case"`":return Yo(e,0,t);case"'":return Yo(e,n);case"<":c=a[Yo(d,1,-1)];break;default:var p=+d;if(p===0)return u;if(p>o){var h=Bk(p/10);return h===0?u:h<=o?r[h-1]===void 0?Go(d,1):r[h-1]+Go(d,1):u}c=r[p-1]}return c===void 0?"":c})}});var _m=f(()=>{"use strict";var qk=Se(),Uk=te(),Qo=ee(),Dm=Xi(),Hk=F(),jk=Gt(),Gk=xm(),hr=km(),Yk=wr(),Wk=Lm(),Qk=Mm(),zk=Q(),Kk=Ae(),Jk=zk("replace"),Xk=TypeError,Bm=Qo("".indexOf),Zk=Qo("".replace),Om=Qo("".slice),eA=Math.max,Vm=function(i,e,t){return t>i.length?-1:e===""?t:Bm(i,e,t)};qk({target:"String",proto:!0},{replaceAll:function(e,t){var r=Dm(this),a,s,n,o,l,u,d,c,p,h=0,m=0,S="";if(!jk(e)){if(a=Gk(e),a&&(s=hr(Dm(Wk(e))),!~Bm(s,"g")))throw Xk("`.replaceAll` does not allow non-global regexes");if(n=Yk(e,Jk),n)return Uk(n,e,r,t);if(Kk&&a)return Zk(hr(r),e,t)}for(o=hr(r),l=hr(e),u=Hk(t),u||(t=hr(t)),d=l.length,c=eA(1,d),h=Vm(o,l,0);h!==-1;)p=u?hr(t(l,h,o)):Qk(l,o,h,[],void 0,t),S+=Om(o,m,h)+p,m=h+d,h=Vm(o,l,h+c);return m<o.length&&(S+=Om(o,m)),S}})});var Fm=f((cV,Nm)=>{"use strict";Tm();Im();_m();var tA=Va();Nm.exports=tA("String","replaceAll")});var Um=f((dV,qm)=>{"use strict";var rA=Fm();qm.exports=rA});var jm=f((pV,Hm)=>{"use strict";var iA=Um();Hm.exports=iA});var Pu="__VERSION__";var de=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(de||{}),bt=(A=>(A.MPEG="MPEG",A.DASH="DASH",A.DASH_SEP="DASH_SEP",A.DASH_SEP_VK="DASH_SEP",A.DASH_WEBM="DASH_WEBM",A.DASH_WEBM_AV1="DASH_WEBM_AV1",A.DASH_STREAMS="DASH_STREAMS",A.DASH_WEBM_VK="DASH_WEBM",A.DASH_ONDEMAND="DASH_ONDEMAND",A.DASH_ONDEMAND_VK="DASH_ONDEMAND",A.DASH_LIVE="DASH_LIVE",A.DASH_LIVE_CMAF="DASH_LIVE_CMAF",A.DASH_LIVE_WEBM="DASH_LIVE_WEBM",A.HLS="HLS",A.HLS_ONDEMAND="HLS_ONDEMAND",A.HLS_JS="HLS",A.HLS_LIVE="HLS_LIVE",A.HLS_LIVE_CMAF="HLS_LIVE_CMAF",A.WEB_RTC_LIVE="WEB_RTC_LIVE",A))(bt||{});var zi=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(zi||{}),Rs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Rs||{});var $s=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))($s||{});import{assertNever as Lu,assertNonNullable as mS,isNonNullable as Ki,ValueSubject as Ls,Subject as bS,Subscription as SS,merge as vS,observableFrom as gS,fromEvent as Au,map as wu,tap as Ru,filterChanged as yS,isNullable as Cs,ErrorCategory as $u}from"@vkontakte/videoplayer-shared";var ku=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Ji=class{constructor(e){this.connection$=new Ls(void 0);this.castState$=new Ls("NOT_AVAILABLE");this.errorEvent$=new bS;this.realCastState$=new Ls("NOT_AVAILABLE");this.subscription=new SS;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=Ki(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||ku("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:$u.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ki(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Cs(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Cs(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(Au(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Lu(a.sessionState)}})).add(vS(Au(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ru(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),wu(a=>a.castState)),gS([r.getCastState()])).pipe(yS(),wu(TS),Ru(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Ki(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();mS(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;(Cs(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?Ki(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:$u.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},TS=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Lu(i)}};var _b=_e(Dn(),1);var mf=_e(Ba(),1);import{assertNever as nf}from"@vkontakte/videoplayer-shared";var z=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:nf(t)}return i},yo=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:nf(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as Dx,Subject as _a,merge as of}from"@vkontakte/videoplayer-shared";var R=class{constructor(e){this.transitionStarted$=new _a;this.transitionEnded$=new _a;this.transitionUpdated$=new _a;this.forceChanged$=new _a;this.stateChangeStarted$=of(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=of(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||Dx(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}};import{assertNever as Ox}from"@vkontakte/videoplayer-shared";var uf=i=>{switch(i){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Ox(i)}};import{assertNever as sr,assertNonNullable as Pt,debounce as lf,ErrorCategory as cf,fromEvent as kt,isNonNullable as df,map as pf,merge as hf,observableFrom as Vx,Subject as Bx,Subscription as To,timeout as _x,getHighestQuality as Nx}from"@vkontakte/videoplayer-shared";var Fx=5,qx=5,Ux=500,ff=7e3,Hr=class{constructor(e){this.subscription=new To;this.loadMediaTimeoutSubscription=new To;this.videoState=new R("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:sr(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:sr(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:sr(e)}break}default:sr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(uf(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 To;this.subscription.add(e),this.subscription.add(hf(this.videoState.stateChangeStarted$.pipe(pf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(pf(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new Bx;e.add(a.pipe(lf(Ux)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(kt(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)>Fx)&&a.next(o),s=o})),e.add(kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<qx&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(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:sr(n)}}),t(kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(kt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=hf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Vx(["init"])).pipe(lf(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"),I(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];Pt(u);let d=Nx(Object.keys(u));Pt(d);let c=u[d];Pt(c),r=c,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];Pt(u),r=u.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let u=t[e];Pt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];Pt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];Pt(u),r=z(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",d=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:cf.VIDEO_PIPELINE,message:u,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return sr(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:l}=this.params.meta;return df(o)&&(n.metadata.title=o),df(l)&&(n.metadata.subtitle=l),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(_x(ff).subscribe(()=>s(`timeout(${ff})`)))});(0,mf.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:cf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var jr=i=>{i.removeAttribute("src"),i.load()};var bf=i=>{try{i.pause(),i.playbackRate=0,jr(i),i.remove()}catch(e){console.error(e)}};var Io=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)}},Eo=window.WeakMap?new WeakMap:new Io,re=i=>{let e=i.querySelector("video"),t=!!e;return e?jr(e):(e=document.createElement("video"),i.appendChild(e)),Eo.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ie=i=>{let e=Eo.get(i);Eo.delete(i),e?jr(i):bf(i)};import{assertNonNullable as Gr,isNonNullable as Be,isNullable as Gx,fromEvent as nr,merge as Sf,observableFrom as vf,filterChanged as gf,map as Yr,Subject as yf,Subscription as Yx,ValueSubject as Wx,ErrorCategory as Qx}from"@vkontakte/videoplayer-shared";import{isNonNullable as xo,isNullable as Hx,Subscription as jx}from"@vkontakte/videoplayer-shared";var Na=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=Hx(a),u=new jx;return a&&u.add(a.subscribe(d=>{let c=i.getState();r(d,c)&&i.setState(d)},s)),r(o,n)||(t(n),l&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),l&&i.setState(d.to)},s)),u},Ve=(i,e,t)=>Na(e,()=>i.loop,r=>{xo(r)&&(i.loop=r)},{onError:t}),ae=(i,e,t,r)=>Na(e,()=>({muted:i.muted,volume:i.volume}),a=>{xo(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),ve=(i,e,t,r)=>Na(e,()=>i.playbackRate,a=>{xo(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),et=Na;var zx=i=>["__",i.language,i.label].join("|"),Kx=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Po=class i{constructor(){this.available$=new yf;this.current$=new Wx(void 0);this.error$=new yf;this.subscription=new Yx;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:Qx.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(et(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Be(s)&&this.setInternal(s)},{equal:(s,n)=>Be(s)&&Be(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(Yr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(et(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Be(s)&&this.setExternal(s)},{equal:(s,n)=>Be(s)&&Be(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(Yr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(et(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:a})),this.subscription.add(et(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Gr(this.video);let{textTracks:e}=this.video;this.subscription.add(nr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Sf(nr(e,"addtrack"),nr(e,"removetrack"),vf(["init"])).pipe(Yr(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),gf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Sf(nr(e,"change"),vf(["init"])).pipe(Yr(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Yr(r=>r&&this.htmlTextTrackToITextTrack(r).id),gf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(nr(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add(nr(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;Be(t.align)&&(a.align=t.align),Be(t.position)&&(a.position=t.position),Be(t.size)&&(a.size=t.size),Be(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){Gr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:zx(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){Gr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Gx(e)||!Kx(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){Gr(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){Gr(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)}},ge=Po;var He=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 Tf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ko=i=>{let e=Tf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},If=i=>{let e=Tf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as ye,map as tt,merge as xf,filterChanged as Xx,isNonNullable as Pf,Subject as Zx,filter as kf,mapTo as Af,combine as eP,once as tP,ErrorCategory as rP,ValueSubject as wf,getCurrentBrowser as iP,CurrentClientBrowser as aP}from"@vkontakte/videoplayer-shared";var Jx=3,Ef=(i,e,t=Jx)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let l=s-1;l>=0;l--)i.end(l)+t>=r&&(r=i.start(l));for(let l=s+1;l<i.length;l++)i.start(l)-t<=a&&(a=i.end(l))}}return{from:r,to:a}};var se=i=>{let e=b=>ye(i,b).pipe(Af(void 0)),r=xf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(b=>ye(i,b))).pipe(tt(b=>b.type==="ended"?i.readyState<2:i.readyState<3),Xx()),a=xf(ye(i,"progress"),ye(i,"timeupdate")).pipe(tt(()=>Ef(i.buffered,i.currentTime))),n=iP().browser===aP.Safari?eP({play:e("play").pipe(tP()),playing:e("playing")}).pipe(Af(void 0)):e("playing"),o=ye(i,"volumechange").pipe(tt(()=>({muted:i.muted,volume:i.volume}))),l=ye(i,"ratechange").pipe(tt(()=>i.playbackRate)),u=ye(i,"error").pipe(kf(()=>!!(i.error||i.played.length)),tt(()=>{let b=i.error;return{id:b?`MediaError#${b.code}`:"HtmlVideoError",category:rP.VIDEO_PIPELINE,message:b?b.message:"Error event from HTML video element",thrown:i.error??void 0}})),d=ye(i,"timeupdate").pipe(tt(()=>i.currentTime)),c=new Zx,p=.3,h;d.subscribe(b=>{i.loop&&Pf(h)&&Pf(b)&&h>=i.duration-p&&b<=p&&c.next(h),h=b});let m=e("pause").pipe(kf(()=>!i.error&&h!==i.duration)),S=ye(i,"enterpictureinpicture"),v=ye(i,"leavepictureinpicture"),g=new wf(If(i));S.subscribe(()=>g.next(!0)),v.subscribe(()=>g.next(!1));let k=new wf(ko(i));return ye(i,"fullscreenchange").pipe(tt(()=>ko(i))).subscribe(k),{playing$:n,pause$:m,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$:d,durationChange$:ye(i,"durationchange").pipe(tt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:g,inFullscreen$:k}};import{VideoQuality as rt}from"@vkontakte/videoplayer-shared";var it=i=>{switch(i){case"mobile":return rt.Q_144P;case"lowest":return rt.Q_240P;case"low":return rt.Q_360P;case"sd":case"medium":return rt.Q_480P;case"hd":case"high":return rt.Q_720P;case"fullhd":case"full":return rt.Q_1080P;case"quadhd":case"quad":return rt.Q_1440P;case"ultrahd":case"ultra":return rt.Q_2160P}};var Lo=_e(Fa(),1);import{isNonNullable as at,isNullable as wo,now as Ff,isHigher as Ro,isHigherOrEqual as _f,isInvariantQuality as Nf,isLower as $o,isLowerOrEqual as hP,videoSizeToQuality as fP,assertNotEmptyArray as mP}from"@vkontakte/videoplayer-shared";var Ao=!1,je={},Of=i=>{Ao=i},Vf=()=>{je={}},Bf=i=>{i(je)},Wr=(i,e)=>{Ao&&(je.meta=je.meta??{},je.meta[i]=e)},X=class{constructor(e){this.name=e}next(e){if(!Ao)return;je.series=je.series??{};let t=je.series[this.name]??[];t.push([Date.now(),e]),je.series[this.name]=t}};var bP=new X("best_bitrate"),SP=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,qa=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ff()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},vP='Assertion "ABR Tracks is empty array" failed',gP=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:d,abrLogger:c})=>{mP(i,vP);let p=r.usePixelRatio?window.devicePixelRatio??1: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&&fP(h),S=r.considerPlaybackRate&&at(o)?o:1,v=i.filter(x=>!Nf(x.quality)).sort((x,_)=>Ro(x.quality,_.quality)?-1:1),g=(0,Lo.default)(v,-1)?.quality,k=(0,Lo.default)(v,0)?.quality,A=wo(a)||at(a.min)&&at(a.max)&&$o(a.max,a.min)||at(a.min)&&k&&Ro(a.min,k)||at(a.max)&&g&&$o(a.max,g),b=S*SP(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),T={},P=v.filter(x=>(m?$o(x.quality,m):!0)?(at(t)&&isFinite(t)&&at(x.bitrate)?t-s>=x.bitrate*b:!0)?r.lazyQualitySwitch&&at(r.minBufferToSwitchUp)&&l&&!Nf(l.quality)&&(n??0)<r.minBufferToSwitchUp&&Ro(x.quality,l.quality)?(T[x.quality]="Buffer",!1):!!d&&_f(x.quality,d)?(T[x.quality]="DroppedFramesLimit",!1):A||(wo(a.max)||hP(x.quality,a.max))&&(wo(a.min)||_f(x.quality,a.min))?!0:(T[x.quality]="FitsQualityLimits",!1):(T[x.quality]="FitsThroughput",!1):(T[x.quality]="FitsContainer",!1))[0];P&&P.bitrate&&bP.next(P.bitrate);let w=P??v[Math.ceil((v.length-1)/2)]??i[0];w.quality!==u?.last?.quality&&c({message:`
6
+ var Ta="2.0.105-dev.35548197.0";var q=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(q||{}),Ve=(S=>(S.MPEG="MPEG",S.DASH="DASH_SEP",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(Ve||{});var Li=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Li||{}),xr=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(xr||{});var kr=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(kr||{});import{assertNever as Aa,assertNonNullable as Zn,isNonNullable as Ri,ValueSubject as Pr,Subject as eo,Subscription as to,merge as io,observableFrom as ro,fromEvent as Ea,map as xa,tap as ka,filterChanged as ao,isNullable as Ar,ErrorCategory as Pa}from"@vkontakte/videoplayer-shared";var Ia=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Mi=class{constructor(e){this.connection$=new Pr(void 0);this.castState$=new Pr("NOT_AVAILABLE");this.errorEvent$=new eo;this.realCastState$=new Pr("NOT_AVAILABLE");this.subscription=new to;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Ri(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},r||Ia("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Pa.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ri(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ar(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ar(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Ea(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Aa(r.sessionState)}})).add(io(Ea(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ka(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),xa(r=>r.castState)),ro([i.getCastState()])).pipe(ao(),xa(so),ka(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=Ri(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();Zn(o);let d=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;(Ar(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:d}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Ri(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Pa.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},so=n=>{switch(n){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 Aa(n)}};import{assertNever as wa}from"@vkontakte/videoplayer-shared";var W=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:wa(t)}return n},wr=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:wa(e)}};var y=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as no,Subject as Di,merge as $a}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new Di;this.transitionEnded$=new Di;this.transitionUpdated$=new Di;this.forceChanged$=new Di;this.stateChangeStarted$=$a(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=$a(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||no(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as oo}from"@vkontakte/videoplayer-shared";var La=n=>{switch(n){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":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 oo(n)}};import{assertNever as lt,assertNonNullable as ze,debounce as Ra,ErrorCategory as Ma,fromEvent as Ke,isNonNullable as Da,map as Ca,merge as Ba,observableFrom as uo,Subject as lo,Subscription as $r,timeout as co,getHighestQuality as po}from"@vkontakte/videoplayer-shared";var ho=5,mo=5,fo=500,Va=7e3,xt=class{constructor(e){this.subscription=new $r;this.loadMediaTimeoutSubscription=new $r;this.videoState=new $("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:lt(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:lt(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:lt(e)}break}default:lt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(La(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;this.subscription.add(e),this.subscription.add(Ba(this.videoState.stateChangeStarted$.pipe(Ca(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Ca(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new lo;e.add(r.pipe(Ra(fo)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>ho)&&r.next(o),a=o})),e.add(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),d=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==d&&this.params.output.isBuffering$.next(d),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<mo&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),y(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:lt(s)}}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Ba(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,uo(["init"])).pipe(Ra(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&y(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let u=t[e];ze(u);let l=po(Object.keys(u));ze(l);let c=u[l];ze(c),i=c,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];ze(u),i=u.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let u=t[e];ze(u),i=u.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];ze(u),i=u.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];ze(u),i=W(u.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",l=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ma.VIDEO_PIPELINE,message:u,thrown:l}),l}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return lt(e)}let s=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:d}=this.params.meta;return Da(o)&&(s.metadata.title=o),Da(d)&&(s.metadata.subtitle=d),s}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(co(Va).subscribe(()=>a(`timeout(${Va})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Ma.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var kt=n=>{n.removeAttribute("src"),n.load()};var Oa=n=>{try{n.pause(),n.playbackRate=0,kt(n),n.remove()}catch(e){console.error(e)}};var Lr=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)}},Rr=window.WeakMap?new WeakMap:new Lr,z=n=>{let e=n.querySelector("video"),t=!!e;return e?kt(e):(e=document.createElement("video"),n.appendChild(e)),Rr.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},K=n=>{let e=Rr.get(n);Rr.delete(n),e?kt(n):Oa(n)};import{assertNonNullable as Pt,isNonNullable as Ie,isNullable as So,fromEvent as ct,merge as _a,observableFrom as Na,filterChanged as Fa,map as At,Subject as Ua,Subscription as vo,ValueSubject as yo,ErrorCategory as To}from"@vkontakte/videoplayer-shared";import{isNonNullable as Mr,isNullable as bo,Subscription as go}from"@vkontakte/videoplayer-shared";var Ci=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),d=bo(r),u=new go;return r&&u.add(r.subscribe(l=>{let c=n.getState();i(l,c)&&n.setState(l)},a)),i(o,s)||(t(s),d&&n.setState(s)),u.add(n.stateChangeStarted$.subscribe(l=>{t(l.to),d&&n.setState(l.to)},a)),u},Te=(n,e,t)=>Ci(e,()=>n.loop,i=>{Mr(i)&&(n.loop=i)},{onError:t}),J=(n,e,t,i)=>Ci(e,()=>({muted:n.muted,volume:n.volume}),r=>{Mr(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),ne=(n,e,t,i)=>Ci(e,()=>n.playbackRate,r=>{Mr(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Oe=Ci;var Io=n=>["__",n.language,n.label].join("|"),Eo=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Dr=class n{constructor(){this.available$=new Ua;this.current$=new yo(void 0);this.error$=new Ua;this.subscription=new vo;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:To.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Oe(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Ie(a)&&this.setInternal(a)},{equal:(a,s)=>Ie(a)&&Ie(s)&&a.length===s.length&&a.every(({id:o},d)=>o===s[d].id),changed$:this.available$.pipe(At(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(Oe(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Ie(a)&&this.setExternal(a)},{equal:(a,s)=>Ie(a)&&Ie(s)&&a.length===s.length&&a.every(({id:o},d)=>o===s[d].id),changed$:this.available$.pipe(At(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(Oe(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Oe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Pt(this.video);let{textTracks:e}=this.video;this.subscription.add(ct(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(_a(ct(e,"addtrack"),ct(e,"removetrack"),Na(["init"])).pipe(At(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Fa((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(_a(ct(e,"change"),Na(["init"])).pipe(At(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),At(i=>i&&this.htmlTextTrackToITextTrack(i).id),Fa()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ct(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let s=a.target?.cues??null;s&&s.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(ct(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Ie(t.align)&&(r.align=t.align),Ie(t.position)&&(r.position=t.position),Ie(t.size)&&(r.size=t.size),Ie(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Pt(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Io(e),a=this.externalTracks.has(r),s=r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:s,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,s])=>s.language===r&&s.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Pt(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(So(e)||!Eo(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){Pt(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){Pt(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},oe=Dr;var we=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 Ha=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Cr=n=>{let e=Ha(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Ga=n=>{let e=Ha(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as ue,map as _e,merge as ja,filterChanged as ko,isNonNullable as Wa,Subject as Po,filter as Ya,mapTo as qa,combine as Ao,once as wo,ErrorCategory as $o,ValueSubject as za,getCurrentBrowser as Lo,CurrentClientBrowser as Ro}from"@vkontakte/videoplayer-shared";var xo=3,Qa=(n,e,t=xo)=>{let i=0,r=0;for(let a=0;a<n.length;a++){let s=n.start(a),o=n.end(a);if(s<=e&&e<=o){if(i=s,r=o,!t)return{from:i,to:r};for(let d=a-1;d>=0;d--)n.end(d)+t>=i&&(i=n.start(d));for(let d=a+1;d<n.length;d++)n.start(d)-t<=r&&(r=n.end(d))}}return{from:i,to:r}};var X=n=>{let e=b=>ue(n,b).pipe(qa(void 0)),i=ja(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(b=>ue(n,b))).pipe(_e(b=>b.type==="ended"?n.readyState<2:n.readyState<3),ko()),r=ja(ue(n,"progress"),ue(n,"timeupdate")).pipe(_e(()=>Qa(n.buffered,n.currentTime))),s=Lo().browser===Ro.Safari?Ao({play:e("play").pipe(wo()),playing:e("playing")}).pipe(qa(void 0)):e("playing"),o=ue(n,"volumechange").pipe(_e(()=>({muted:n.muted,volume:n.volume}))),d=ue(n,"ratechange").pipe(_e(()=>n.playbackRate)),u=ue(n,"error").pipe(Ya(()=>!!(n.error||n.played.length)),_e(()=>{let b=n.error;return{id:b?`MediaError#${b.code}`:"HtmlVideoError",category:$o.VIDEO_PIPELINE,message:b?b.message:"Error event from HTML video element",thrown:n.error??void 0}})),l=ue(n,"timeupdate").pipe(_e(()=>n.currentTime)),c=new Po,p=.3,h;l.subscribe(b=>{n.loop&&Wa(h)&&Wa(b)&&h>=n.duration-p&&b<=p&&c.next(h),h=b});let m=e("pause").pipe(Ya(()=>!n.error&&h!==n.duration)),v=ue(n,"enterpictureinpicture"),f=ue(n,"leavepictureinpicture"),g=new za(Ga(n));v.subscribe(()=>g.next(!0)),f.subscribe(()=>g.next(!1));let S=new za(Cr(n));return ue(n,"fullscreenchange").pipe(_e(()=>Cr(n))).subscribe(S),{playing$:s,pause$:m,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$:ue(n,"durationchange").pipe(_e(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:d,inPiP$:g,inFullscreen$:S}};import{VideoQuality as Ne}from"@vkontakte/videoplayer-shared";var Fe=n=>{switch(n){case"mobile":return Ne.Q_144P;case"lowest":return Ne.Q_240P;case"low":return Ne.Q_360P;case"sd":case"medium":return Ne.Q_480P;case"hd":case"high":return Ne.Q_720P;case"fullhd":case"full":return Ne.Q_1080P;case"quadhd":case"quad":return Ne.Q_1440P;case"ultrahd":case"ultra":return Ne.Q_2160P}};import{isNonNullable as Ue,isNullable as Vr,now as ts,isHigher as Or,isHigherOrEqual as Za,isInvariantQuality as es,isLower as _r,isLowerOrEqual as Mo,videoSizeToQuality as Do,assertNotEmptyArray as Co}from"@vkontakte/videoplayer-shared";var Br=!1,$e={},Ka=n=>{Br=n},Ja=()=>{$e={}},Xa=n=>{n($e)},wt=(n,e)=>{Br&&($e.meta=$e.meta??{},$e.meta[n]=e)},Y=class{constructor(e){this.name=e}next(e){if(!Br)return;$e.series=$e.series??{};let t=$e.series[this.name]??[];t.push([Date.now(),e]),$e.series[this.name]=t}};var Bo=new Y("best_bitrate"),Vo=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t,Bi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ts()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Oo='Assertion "ABR Tracks is empty array" failed',_o=(n,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:d,history:u,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{Co(n,Oo);let p=i.usePixelRatio?window.devicePixelRatio??1:1,h=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},m=h&&Do(h),v=i.considerPlaybackRate&&Ue(o)?o:1,f=n.filter(T=>!es(T.quality)).sort((T,x)=>Or(T.quality,x.quality)?-1:1),g=f.at(-1)?.quality,S=f.at(0)?.quality,_=Vr(r)||Ue(r.min)&&Ue(r.max)&&_r(r.max,r.min)||Ue(r.min)&&S&&Or(r.min,S)||Ue(r.max)&&g&&_r(r.max,g),b=v*Vo(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),I={},V=f.filter(T=>(m?_r(T.quality,m):!0)?(Ue(t)&&isFinite(t)&&Ue(T.bitrate)?t-a>=T.bitrate*b:!0)?i.lazyQualitySwitch&&Ue(i.minBufferToSwitchUp)&&d&&!es(d.quality)&&(s??0)<i.minBufferToSwitchUp&&Or(T.quality,d.quality)?(I[T.quality]="Buffer",!1):!!l&&Za(T.quality,l)?(I[T.quality]="DroppedFramesLimit",!1):_||(Vr(r.max)||Mo(T.quality,r.max))&&(Vr(r.min)||Za(T.quality,r.min))?!0:(I[T.quality]="FitsQualityLimits",!1):(I[T.quality]="FitsThroughput",!1):(I[T.quality]="FitsContainer",!1))[0];V&&V.bitrate&&Bo.next(V.bitrate);let A=V??f[Math.ceil((f.length-1)/2)]??n[0];A.quality!==u?.last?.quality&&c({message:`
7
7
  [available tracks]
8
- ${i.map(x=>`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate} }`).join(`
8
+ ${n.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate} }`).join(`
9
9
  `)}
10
10
 
11
11
  [tuning]
12
- ${Object.entries(r??{}).map(([x,_])=>`${x}: ${_}`).join(`
12
+ ${Object.entries(i??{}).map(([T,x])=>`${T}: ${x}`).join(`
13
13
  `)}
14
14
 
15
15
  [limit params]
16
16
  containerQualityLimit: ${m},
17
17
  throughput: ${t},
18
- reserve: ${s},
18
+ reserve: ${a},
19
19
  playbackRate: ${o},
20
- playbackRateFactor: ${S},
21
- forwardBufferHealth: ${n},
20
+ playbackRateFactor: ${v},
21
+ forwardBufferHealth: ${s},
22
22
  bitrateFactor: ${b},
23
- minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
- droppedVideoMaxQualityLimit: ${d},
25
- limitsAreInvalid: ${A},
26
- maxQualityLimit: ${a?.max},
27
- minQualityLimit: ${a?.min},
23
+ minBufferToSwitchUp: ${i.minBufferToSwitchUp},
24
+ droppedVideoMaxQualityLimit: ${l},
25
+ limitsAreInvalid: ${_},
26
+ maxQualityLimit: ${r?.max},
27
+ minQualityLimit: ${r?.min},
28
28
 
29
29
  [limited tracks]
30
- ${Object.entries(T).map(([x,_])=>`${x}: ${_}`).join(`
30
+ ${Object.entries(I).map(([T,x])=>`${T}: ${x}`).join(`
31
31
  `)||"All tracks are available"}
32
32
 
33
- [best track] ${P?.quality}
34
- [selected track] ${w?.quality}
35
- `});let D=w&&u&&u.history[w.id]&&Ff()-u.history[w.id]<=r.trackCooldown&&(!u.last||w.id!==u.last.id);if(w?.id&&u&&!D&&u.recordSelection(w),D&&u?.last){let x=u.last;return u?.recordSwitch(x),c({message:`
36
- [last selected] ${x?.quality}
37
- `}),x}return u?.recordSwitch(w),w},st=gP;var G=i=>new URL(i).hostname;import{assertNever as Yf,assertNonNullable as Wf,combine as NP,debounce as FP,ErrorCategory as Qf,filter as zf,filterChanged as qP,isNonNullable as Vo,map as Ya,merge as Kf,observableFrom as UP,once as HP,Subscription as jP,ValueSubject as Bo,videoQualityToHeight as GP,videoSizeToQuality as YP}from"@vkontakte/videoplayer-shared";var qf=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},ne=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!qf(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return qf(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Ha,isNullable as IP,assertNonNullable as Kr}from"@vkontakte/videoplayer-shared";import{isNonNullable as Uf,assertNonNullable as Ua,now as yP}from"@vkontakte/videoplayer-shared";function Y(){return yP()}function Co(i){return Y()-i}function Mo(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,l=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return l&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Hf(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function or(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,d,c,p=!1,h="arraybuffer",m=7e3,S=2e3,v=()=>{if(l)return;Ua(d);let O=Co(d),H;if(O<S){H=S-O,setTimeout(v,H);return}S*=2,S>m&&(S=m),n&&n.abort(),n=new a,M()},g=O=>(s=O,_),k=O=>(c=O,_),A=()=>(h="json",_),b=()=>{if(!l){if(--u>=0){v(),r&&r();return}l=!0,c&&c(),t&&t()}},T=O=>(p=O,_),M=()=>{d=Y(),n=new a,n.open("get",i);let O=0,H,ce=0,Z=()=>(Ua(d),Math.max(d,Math.max(H||0,ce||0)));if(s&&n.addEventListener("progress",y=>{let B=Y();s.updateChunk&&y.loaded>O&&(s.updateChunk(Z(),y.loaded-O),O=y.loaded,H=B)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>b())),n.addEventListener("load",()=>{if(l)return;Ua(n);let y=n.status;if(y>=200&&y<300){if(n.response.byteLength&&s){let B=n.response.byteLength-O;B&&s.updateChunk&&s.updateChunk(Z(),B)}n.responseType==="json"&&!Object.values(n.response).length?b():(c&&c(),e(n.response))}else b()}),n.addEventListener("error",()=>{b()}),p){let y=()=>{Ua(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ce=Y(),n.removeEventListener("readystatechange",y))};n.addEventListener("readystatechange",y)}return n.responseType=h,n.send(),_},_={withBitrateReporting:g,withParallel:T,withJSONResponse:A,withRetryCount:O=>(u=O,_),withRetryInterval:(O,H)=>(Uf(O)&&(S=O),Uf(H)&&(m=H),_),withTimeout:O=>(o=O,_),withFinally:k,send:M,abort:()=>{n&&(n.abort(),n=void 0),l=!0,c&&c()}};return _}var Qr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let l=s.bytes*n/o;a+=l,s.start=t,s.bytes-=l}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var zr=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Y(),a=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=l=>{e._complete=1,e._responseData=l,e._downloadTime=Y()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=or(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Y()}_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=Y();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var ja=1e4,Do=3;var EP=6e4,xP=10,PP=1,kP=500,Jr=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 Qr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Mo(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=Mo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ha(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Hf(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zr(Do,ja,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,l=null,u=null,d=!1,c=()=>{let b=s&&(!d||d===this.rep);return b||t("Not running!"),b},p=(b,T,M)=>{l&&l.abort(),l=or(this.urlResolver.resolve(b,!1),T,M,()=>this._retryCallback()).withTimeout(ja).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Do).withFinally(()=>{l=null}).send()},h=(b,T,M)=>{Kr(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),T,M,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=b=>{let T=r.playbackRate;r.playbackRate!==b&&(t(`Playback rate switch: ${T}=>${b}`),r.playbackRate=b)},S=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let M=Y()-1e4,P=0;for(let D=0;D<this.bufferStates.length;D++){let x=this.bufferStates[D];b=Math.min(b,x.buf),x.ts<M&&P++}this.bufferStates.splice(0,P),t(`update playback rate; minBuffer=${b} drop=${P} jitter=${this.sourceJitter}`);let w=b-PP;this.sourceJitter>=0?w-=this.sourceJitter/2:this.sourceJitter-=1,w>3?m(1.15):w>1?m(1.1):w>.3?m(1.05):m(1)}},g=b=>{let T,M=()=>T&&T.start?T.start.length:0,P=y=>T.start[y]/1e3,w=y=>T.dur[y]/1e3,D=y=>T.fragIndex+y,x=(y,B)=>({chunkIdx:D(y),startTS:P(y),dur:w(y),discontinuity:B}),_=()=>{let y=0;if(T&&T.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,U=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=B;this.sourceJitter>1&&(W+=this.sourceJitter-1);let K=T.dur.length-1;for(;K>=0&&(W-=T.dur[K],!(W<=0));--K);y=Math.min(K,T.dur.length-1-U),y=Math.max(y,0)}return x(y,!0)},O=y=>{let B=M();if(!(B<=0)){if(Ha(y)){for(let U=0;U<B;U++)if(P(U)>y)return x(U)}return _()}},H=y=>{let B=M(),U=y?y.chunkIdx+1:0,W=U-T.fragIndex;if(!(B<=0)){if(!y||W<0||W-B>xP)return t(`Resync: offset=${W} bChunks=${B} chunk=`+JSON.stringify(y)),_();if(!(W>=B))return x(U-T.fragIndex,!1)}},ce=(y,B,U)=>{u&&u.abort(),u=or(this.urlResolver.resolve(y,!0,this.lowLatency),B,U,()=>this._retryCallback()).withTimeout(ja).withRetryCount(Do).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(y,B)=>{ce(b,U=>{if(!c())return;T=U;let W=!!T.lowLatency;W!==this.lowLatency&&S(W);let K=0;for(let Ee=0;Ee<T.dur.length;++Ee)K+=T.dur[Ee];K>0&&(Kr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(K/T.dur.length)),a({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,y(O(B))},()=>this._handleNetworkError())},nextChunk:H}},k=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),Kr(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:b=>{let{videoElement:T,logger:M}=this.params,P=g(e.jidxUrl),w,D,x,_,O=0,H,ce,Z,y=()=>{H&&(clearTimeout(H),H=void 0);let $=Math.max(kP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),J=O+$,me=Y(),be=Math.min(1e4,J-me);O=me;let Je=()=>{u||c()&&P.seek(()=>{c()&&(O=Y(),B(),y())})};be>0?H=window.setTimeout(()=>{this.paused?y():Je()},be):Je()},B=()=>{let $;for(;$=P.nextChunk(_);)_=$,yr($);let J=P.nextChunk(x);if(J){if(x&&J.discontinuity){M("Detected discontinuity; restarting playback"),this.paused?y():(k(),this._initPlayerWith(e));return}Ee(J)}else y()},U=($,J)=>{if(!c()||!this.sourceBuffer)return;let me,be,Je,Ft=dt=>{window.setTimeout(()=>{c()&&U($,J)},dt)};if(this.sourceBuffer.updating)M("Source buffer is updating; delaying appendBuffer"),Ft(100);else{let dt=Y(),qt=T.currentTime;!this.paused&&T.buffered.length>1&&ce===qt&&dt-Z>500&&(M("Stall suspected; trying to fix"),this._fixupStall()),ce!==qt&&(ce=qt,Z=dt);let Tr=this._getBufferSizeSec();if(Tr>30)M(`Buffered ${Tr} seconds; delaying appendBuffer`),Ft(2e3);else try{this.sourceBuffer.appendBuffer($),this.videoPlayStarted?(this.bufferStates.push({ts:dt,buf:Tr}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),J&&J()}catch(ji){if(ji.name==="QuotaExceededError")M("QuotaExceededError; delaying appendBuffer"),Je=this.sourceBuffer.buffered.length,Je!==0&&(me=this.sourceBuffer.buffered.start(0),be=qt,be-me>4&&this.sourceBuffer.remove(me,be-3)),Ft(1e3);else throw ji}}},W=()=>{D&&w&&(M([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(x)]),U(D,function(){D=null,B()}))},K=$=>e.fragUrlTemplate.replace("%%id%%",$.chunkIdx),Ee=$=>{c()&&h(K($),(J,me)=>{if(c()){if(me/=1e3,D=J,x=$,n=$.startTS,me){let be=Math.min(10,$.dur/me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*be:be}W()}},()=>this._handleNetworkError())},yr=$=>{c()&&(Kr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(K($),!1)))},Nt=$=>{c()&&(e.cachedHeader=$,U($,()=>{w=!0,W()}))};s=!0,P.seek($=>{if(c()){if(O=Y(),!$){y();return}_=$,!IP(b)||$.startTS>b?Ee($):(x=$,B())}},b),e.cachedHeader?Nt(e.cachedHeader):p(e.headerUrl,Nt,()=>this._handleNetworkError())},stop:k,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Ha(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Kr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ha(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s=(()=>({updateChunk:(p,h)=>{let m=Y();if(this.chunkRateEstimator.addInterval(p,m,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),n=-1/0,o,l=!0,u=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(l&&c>o&&Co(n)<3e4)return;r(c)}l=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&u(),h},notifySwitch:c=>{let p=Y();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=or(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ja).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;ne(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((l,u)=>{l.video&&a.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=u,o.push(l))}),o.sort(function(l,u){return l.video&&u.video?u.video.height-l.video.height:u.bitrate-l.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},EP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as AP,filter as jf,fromEvent as wP,interval as RP,isHigher as $P,isInvariantQuality as LP,isLower as CP,merge as MP,Subject as Gf,Subscription as DP}from"@vkontakte/videoplayer-shared";var Oo=class{constructor(){this.onDroopedVideoFramesLimit$=new Gf;this.subscription=new DP;this.playing=!1;this.tracks=[];this.forceChecker$=new Gf;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!LP(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&$P(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(wP(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=RP(this.droppedFramesChecker.checkTime).pipe(jf(()=>this.playing),jf(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(AP(this.droppedFramesChecker.checkTime)),r=MP(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>CP(r,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ga=Oo;import{map as OP,Observable as VP}from"@vkontakte/videoplayer-shared";import{fromEvent as BP}from"@vkontakte/videoplayer-shared";var Xr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var _P=(i,e)=>new VP(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||Xr()))},{...r,...e});a.observe(i);let s=BP(document,"visibilitychange").pipe(OP(n=>!document.hidden||Xr())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Te=_P;var WP=["paused","playing","ready"],QP=["paused","playing","ready"],Zr=class{constructor(e){this.subscription=new jP;this.videoState=new R("stopped");this.representations$=new Bo([]);this.textTracksManager=new ge;this.droppedFramesManager=new Ga;this.maxSeekBackTime$=new Bo(1/0);this.zeroTime$=new Bo(void 0);this.liveOffset=new He;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Qf.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=it(a.name)??YP(a.video),o=a.bitrate/1e3,l={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:l};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Vo(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(QP.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&WP.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(z(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let l=a?.from;l&&l==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.dash.reinit(z(this.params.source.url,l))}return;default:return Yf(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Qf.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Kf(this.videoState.stateChangeStarted$.pipe(Ya(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ya(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=re(e.container),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(G(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=se(this.video);this.subscription.add(this.representations$.pipe(Ya(a=>a.map(({track:s})=>s)),zf(a=>!!a.length),HP()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:a}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(qP(),Ya(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(NP({zeroTime:this.zeroTime$.pipe(zf(Vo)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Ve(this.video,this.params.desiredState.isLooped,t)).add(ae(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(ve(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).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(Te(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&GP(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Yf(a.to)}},t)).add(Kf(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,UP(["init"])).pipe(FP(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),ie(this.video)}createLiveDashPlayer(){let e=new Jr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Vo(t)?t:st(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let u=e.find(({track:d})=>d.id===s)?.representation;Wf(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;Wf(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(z(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Jf=Zr;var nt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as gA,assertNonNullable as yA,debounce as TA,ErrorCategory as ou,filter as mb,filterChanged as uu,fromEvent as IA,isLowerOrEqual as bb,isNonNullable as EA,isInvariantQuality as xA,map as PA,merge as us,observableFrom as kA,observeElementSize as AA,once as Sb,Subscription as wA,ValueSubject as RA}from"@vkontakte/videoplayer-shared";var Wa=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ur=class extends Wa{constructor(){super(),this.listeners||Wa.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)}},ei=class{constructor(){Object.defineProperty(this,"signal",{value:new ur,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(ei.prototype[Symbol.toStringTag]="AbortController",ur.prototype[Symbol.toStringTag]="AbortSignal");function Qa(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function _o(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Qa({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(u,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let d=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(c),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(l,u)])}return n(l,u)},Request:s}}var ti=Qa({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Xf=ti?_o({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ge=ti?Xf.fetch:window.fetch,AD=ti?Xf.Request:window.Request,Ye=ti?ei:window.AbortController,wD=ti?ur:window.AbortSignal;var We=()=>window.ManagedMediaSource||window.MediaSource,za=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Zf=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),em=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ja,isAndroid as JP}from"@vkontakte/videoplayer-shared";var tm=JP(),Ka=document.createElement("video"),XP='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ZP='video/mp4; codecs="hev1.1.6.L93.B0"',rm='video/webm; codecs="vp09.00.10.08"',im='video/webm; codecs="av01.0.00M.08"',ek='audio/mp4; codecs="mp4a.40.2"',tk='audio/webm; codecs="opus"',At={mms:za(),mse:Zf(),hls:!!(Ka.canPlayType?.("application/x-mpegurl")||Ka.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},oe={mp4:!!Ka.canPlayType?.("video/mp4"),webm:!!Ka.canPlayType?.("video/webm"),cmaf:!0},ue={h264:!!We()?.isTypeSupported?.(XP),h265:!!We()?.isTypeSupported?.(ZP),vp9:!!We()?.isTypeSupported?.(rm),av1:!!We()?.isTypeSupported?.(im),aac:!!We()?.isTypeSupported?.(ek),opus:!!We()?.isTypeSupported?.(tk)},lr=(ue.h264||ue.h265)&&ue.aac,wt,rk=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:im}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:rm}})]);wt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{rk()}catch(i){console.error(i)}var cr=At.hls&&oe.mp4,am=()=>Object.keys(ue).filter(i=>ue[i]),sm=(i,e=!1,t=!1)=>{let r=At.mse||At.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&oe.mp4&&lr;case"DASH_WEBM":return r&&oe.webm&&ue.vp9&&ue.opus;case"DASH_WEBM_AV1":return r&&oe.webm&&ue.av1&&ue.opus;case"DASH_STREAMS":return r&&(oe.mp4&&lr||oe.webm&&(ue.vp9||ue.av1)&&(ue.opus||ue.aac));case"DASH_LIVE":return At.mse&&oe.mp4&&lr;case"DASH_LIVE_CMAF":return r&&oe.mp4&&lr&&oe.cmaf;case"DASH_ONDEMAND":return r&&oe.mp4&&lr;case"HLS":case"HLS_ONDEMAND":return cr||e&&At.mse&&oe.mp4&&lr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return cr;case"MPEG":return oe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return At.webrtc&&At.ws&&ue.h264&&(oe.mp4||oe.webm);default:return Ja(a)}})},ri=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return wt?wt[t].smooth?[t,e]:wt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return wt?wt[t].powerEfficient?[t,e]:wt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ja(i)}return[e,t]},nm=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ri(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(tm)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...ri(i),"DASH_SEP","DASH_ONDEMAND","DASH_STREAMS","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...ri(i),"DASH_STREAMS","HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ri(i),"MPEG","DASH_SEP","DASH_ONDEMAND","DASH_STREAMS","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ri(i),"DASH_ONDEMAND","DASH_STREAMS","HLS","HLS_ONDEMAND"];default:Ja(e)}return cr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},om=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o;if(tm)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Ja(i)}else cr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},No=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],um=i=>{if(i.size!==0){if(i.size===1)return i.values().next().value;for(let e of i)if(e.toLowerCase().startsWith("opus")||e.toLowerCase().startsWith("vp09"))return e;return i.values().next().value}};var ii=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};import{abortable as au,assertNonNullable as Vt,combine as ub,ErrorCategory as ut,filter as is,filterChanged as pA,fromEvent as Sr,interval as su,isNonNullable as lb,map as nu,merge as vr,Subject as cb,Subscription as db,tap as hA,throttle as fA,ValueSubject as le}from"@vkontakte/videoplayer-shared";var br=_e(Fa(),1);var ik=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},ak=i=>window.clearTimeout(i),lm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Fo=lm?ik:window.requestIdleCallback,FD=lm?ak:window.cancelIdleCallback;var tb=_e(Ba(),1);import{assertNever as sk,CurrentClientBrowser as nk,ErrorCategory as cm,getCurrentBrowser as ok,Subject as dm}from"@vkontakte/videoplayer-shared";var uk=16,pm=!1;try{pm=ok().browser===nk.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=uk}catch(i){console.error(i)}var qo=class{constructor(e){this.bufferFull$=new dm;this.error$=new dm;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:cm.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;pm&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:cm.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:sk(t)}}},hm=qo;var Uo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as fr,assertNonNullable as Qe,ErrorCategory as mr,fromEvent as Zo,getExponentialDelay as eu,once as sA,isNonNullable as eb,isNullable as ze,Subject as nA,Subscription as oA,ValueSubject as ki}from"@vkontakte/videoplayer-shared";var V=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var dr=class extends V{};var ai=class extends V{};var si=class extends V{constructor(t,r){super(t,r);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let a=this.size-this.cursor;for(;a;){let s=this.readString(4);this.compatibleBrands.push(s),a-=4}}};var ni=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ui=class extends V{constructor(t,r){super(t,r);this.data=this.content}};var q=class extends V{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Rt=class extends q{constructor(t,r){super(t,r);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 a=0;a<this.referenceCount;a++){let s=this.readUint32(),n=s>>>31,o=s<<1>>>1,l=this.readUint32();s=this.readUint32();let u=s>>>28,d=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:l,SAPType:u,SAPDeltaTime:d})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var li=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ci=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var di=class extends q{constructor(t,r){super(t,r);switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var pi=class extends q{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var hi=class extends q{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var fi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends q{constructor(t,r){super(t,r);this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var bi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Si=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var vi=class extends q{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var gi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=class extends q{constructor(t,r){super(t,r);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 Ti=class extends q{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 Ii=class extends q{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ck={ftyp:si,moov:ni,moof:oi,mdat:ui,sidx:Rt,trak:li,mdia:fi,mfhd:vi,tkhd:mi,traf:gi,tfhd:yi,tfdt:Ti,trun:Ii,minf:bi,sv3d:ci,st3d:di,prhd:pi,proj:Si,equi:hi,uuid:ai,unknown:dr},$t=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=ck[e];return r?new r(t,new i):new dr(t,new i)}};var pr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var pk=new TextDecoder("ascii"),hk=i=>pk.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",fk=i=>{let e=new Rt(i,new $t),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},mk=(i,e)=>{let r=new $t().parse(i),a=new pr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],l=n[n.length-1],u=o.source.byteOffset,c=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(i.buffer,u,c)},bk=(i,e)=>{let r=new $t().parse(i),s=new pr(r).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),l=s[s.length-1].children.find(c=>c.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((c,p)=>c+p,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},Sk=i=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new $t().parse(i),a=new pr(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let l=a.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},fm={validateData:hk,parseInit:Sk,getIndexRange:()=>{},parseSegments:fk,parseFeedableSegmentChunk:mk,getSegmentEndTime:bk};import{assertNonNullable as jo,isNonNullable as vm,isNullable as gk}from"@vkontakte/videoplayer-shared";import{assertNever as vk}from"@vkontakte/videoplayer-shared";var mm={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"}},bm=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Ei(i,t),a=r in mm,s=a?mm[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let l=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,d=Ei(l),c=u*2**((o-1)*8)+d,p=t+o,h;return p+c>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,c),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Ei=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},$e=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Ei(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:vk(e)}},Lt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=bm(r);if(!e(a))return;a.type==="master"&&Lt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Sm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=bm(i);return Lt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=$e(o,n):s===17026?t=$e(o,n):s===17029&&(r=$e(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var gm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],yk=[231,22612,22743,167,171,163,160,175],Tk=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,d=!1,c=0;return Lt(i,({tag:p,type:h,value:m,valueSize:S})=>{if(p===21419){let v=$e(m,h);u=Ei(v)}else p!==21420&&(u=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+S):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=$e(m,h):p===17545?a=$e(m,h):p===21420&&u===475249515?l=$e(m,h):p===374648427?Lt(m,({tag:v,type:g,value:k})=>v===30321?(d=$e(k,g)===1,!1):!0):s&&n&&gm.includes(p)&&(o=!0),!o}),jo(e,"Failed to parse webm Segment start"),jo(t,"Failed to parse webm Segment end"),jo(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:l,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ik=i=>{if(gk(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Ek=(i,e)=>{let t=!1,r=!1,a=o=>vm(o.time)&&vm(o.position),s=[],n;return Lt(i,({tag:o,type:l,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=$e(u,l));break;case 183:break;case 241:n&&(n.position=$e(u,l));break;default:t&&gm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:d}=o,c=s[l+1];return{status:"none",time:{from:u,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},xk=i=>{let e=0,t=!1;try{Lt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):yk.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},ym={validateData:Sm,parseInit:Tk,getIndexRange:Ik,parseSegments:Ek,parseFeedableSegmentChunk:xk};var xi=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return ym;case"mp4":return fm}}throw new ReferenceError(`Unsupported mime type ${i}`)};var zo=_e(jm(),1);import{isNonNullable as Ym,isNullable as Wm}from"@vkontakte/videoplayer-shared";var Gm=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Qm=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Ct=(i,e)=>{let t=i;t=(0,zo.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,zo.default)(t,n,(o,l)=>Wm(s)?o:Wm(l)?s:s.padStart(parseInt(l,10),"0"))}return t},Km=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",l=n.children,u=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),c=d?new Date(d).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),v=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Qm(h);else if(m){let b=Qm(m);Ym(b)&&(p=b)}else v&&(p=parseInt(v,10));let g=0,k=s.getAttribute("profiles")?.split(",")??[];for(let b of l){let T=b.getAttribute("id")??"id"+(g++).toString(10),M=b.getAttribute("mimeType")??"",P=b.getAttribute("codecs")??"",w=b.getAttribute("contentType")??M?.split("/")[0],D=b.getAttribute("profiles")?.split(",")??[],x=b.getAttribute("lang")??void 0,_=b.getAttribute("label")??void 0,O=b.querySelectorAll("Representation"),H=b.querySelector("SegmentTemplate"),ce=w,Z={id:T,language:x,label:_,codecs:P,mime:M,representations:[]};for(let y of O){let B=y.getAttribute("lang")??void 0,U=y.getAttribute("label")??void 0,W=y.querySelector("BaseURL")?.textContent?.trim()??"",K=new URL(W||o,e).toString(),Ee=y.getAttribute("mimeType")??M,yr=y.getAttribute("codecs")??P??"",Nt;if(w==="text"){let $=y.getAttribute("id")||"",J=$.includes("_auto");Nt={id:$,isAuto:J,kind:"text",url:K}}else{let $=y.getAttribute("contentType")??Ee?.split("/")[0]??w,J=b.getAttribute("profiles")?.split(",")??[],me=parseInt(y.getAttribute("width")??"",10),be=parseInt(y.getAttribute("height")??"",10),Je=parseInt(y.getAttribute("bandwidth")??"",10)/1e3,Ft=y.getAttribute("frameRate")??"",dt=y.getAttribute("quality")??void 0,qt=Ft?Gm(Ft):void 0,Tr=y.getAttribute("id")??"id"+(g++).toString(10),ji=$==="video"?`${be}p`:$==="audio"?`${Je}Kbps`:yr,rS=`${Tr}@${ji}`,iS=[...k,...D,...J],Is,aS=y.querySelector("SegmentBase"),pt=y.querySelector("SegmentTemplate")??H;if(aS){let ht=y.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ft,xs]=ht.split("-").map(Ut=>parseInt(Ut,10)),Xe={from:ft,to:xs},Ir=y.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ps,Gi]=Ir?Ir.split("-").map(Ut=>parseInt(Ut,10)):[],Er=Ir?{from:Ps,to:Gi}:void 0;Is={type:"byteRange",url:K,initRange:Xe,indexRange:Er}}else if(pt){let ht={representationId:y.getAttribute("id")??void 0,bandwidth:y.getAttribute("bandwidth")??void 0},ft=parseInt(pt.getAttribute("timescale")??"",10),xs=pt.getAttribute("initialization")??"",Xe=pt.getAttribute("media"),Ir=parseInt(pt.getAttribute("startNumber")??"",10)??1,Ps=Ct(xs,ht);if(!Xe)throw new ReferenceError("No media attribute in SegmentTemplate");let Gi=pt.querySelectorAll("SegmentTimeline S")??[],Er=[],Ut=0,ks="",As=0;if(Gi.length){let Yi=Ir,xe=0;for(let Ht of Gi){let Me=parseInt(Ht.getAttribute("d")??"",10),mt=parseInt(Ht.getAttribute("r")??"",10)||0,Wi=parseInt(Ht.getAttribute("t")??"",10);xe=Number.isFinite(Wi)?Wi:xe;let ws=Me/ft*1e3,nS=xe/ft*1e3;for(let Qi=0;Qi<mt+1;Qi++){let oS=Ct(Xe,{...ht,segmentNumber:Yi.toString(10),segmentTime:(xe+Qi*Me).toString(10)}),Eu=(nS??0)+Qi*ws,uS=Eu+ws;Yi++,Er.push({time:{from:Eu,to:uS},url:oS})}xe+=(mt+1)*Me,Ut+=(mt+1)*ws}As=xe/ft*1e3,ks=Ct(Xe,{...ht,segmentNumber:Yi.toString(10),segmentTime:xe.toString(10)})}else if(Ym(p)){let xe=parseInt(pt.getAttribute("duration")??"",10)/ft*1e3,Ht=Math.ceil(p/xe),Me=0;for(let mt=1;mt<Ht;mt++){let Wi=Ct(Xe,{...ht,segmentNumber:mt.toString(10),segmentTime:Me.toString(10)});Er.push({time:{from:Me,to:Me+xe},url:Wi}),Me+=xe}As=Me,ks=Ct(Xe,{...ht,segmentNumber:Ht.toString(10),segmentTime:Me.toString(10)})}let sS={time:{from:As,to:1/0},url:ks};Is={type:"template",baseUrl:K,segmentTemplateUrl:Xe,initUrl:Ps,totalSegmentsDurationMs:Ut,segments:Er,nextSegmentBeyondManifest:sS,timescale:ft}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!$||!Ee)continue;let Es={video:"video",audio:"audio",text:"text"}[$];if(!Es)continue;ce||=Es,Nt={id:rS,kind:Es,segmentReference:Is,profiles:iS,duration:p,bitrate:Je,mime:Ee,codecs:yr,width:me,height:be,fps:qt,quality:dt}}Z.language||=B,Z.label||=U,Z.mime||=Ee,Z.codecs||=yr,Z.representations.push(Nt)}ce&&a[ce].push(Z)}return{dynamic:u,liveAvailabilityStartTime:c,duration:p,streams:a}};var Jo=_e(Fa(),1);import{videoSizeToQuality as aA}from"@vkontakte/videoplayer-shared";var Jm=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?it(s):void 0)??aA({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Xm=({id:i,bitrate:e})=>({id:i,bitrate:e}),Xa=(i,e,t)=>{let r=e.indexOf(i);return(0,Jo.default)(t,Math.round(t.length*r/e.length))??(0,Jo.default)(t,-1)},Zm=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Xo=i=>"url"in i,Mt=i=>i.type==="template",Pi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Ai=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:l=!1,manifest:u}){this.currentSegmentLength$=new ki(0);this.onLastSegment$=new ki(!1);this.fullyBuffered$=new ki(!1);this.playingRepresentation$=new ki(void 0);this.playingRepresentationInit$=new ki(void 0);this.error$=new nA;this.gaps=[];this.subscription=new oA;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ye;this.destroyAbortController=new Ye;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=fr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Qe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new hm(this.sourceBuffer),this.subscription.add(Zo(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:mr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(Zo(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:mr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,Uo(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Qe(r,"No init buffer for starting representation"),Qe(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=fr(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);Qe(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Qe(r,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);let s=this.getCurrentPosition();eb(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=fr(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(l=>l.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let u=t.find(p=>p.id===l);u&&this.representations.set(l,u);let d=this.representations.get(l);if(!d||!Mt(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);Qe(a);let s=this.segments.get(r);Qe(s,"No segments for starting representation");let n=this.initData.get(r);if(Qe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=l,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ye,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ze(e)||ze(this.downloadingRepresentationId)||ze(this.playingRepresentationId)||ze(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Qe(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=nt(this.sourceBuffer.buffered,e),c=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=c)}if(isFinite(this.bufferLimit)&&Uo(this.sourceBuffer.buffered)>=this.bufferLimit){let u=nt(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let d=(0,br.default)(o,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&nt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,br.default)(r,-1);l&&l.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===l))}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;eb(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(r=>r.representations)??[];for(let r of t){if(!r||!Mt(r.segmentReference))return;let a=r.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,br.default)(s,-1)?.time.to??0,o=a?.findIndex(l=>Math.floor(n)>=Math.floor(l.time.from)&&Math.floor(n)<=Math.floor(l.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,l)}else{let l=a.slice(o+1);this.segments.set(r.id,[...s,...l])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(let t of this.representations.values()){let r=t.segmentReference;if(!Mt(r))return;let a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),s=Ct(r.segmentTemplateUrl,{segmentTime:a}),n=this.segments.get(t.id)??[],o=n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.to))||n.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:s})}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:c,time:{from:p,to:h}},m)=>{let S=p<=r&&h>=r,v=p>r||S||m===0&&r===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),k=this.preloadOnly&&p<=r+g||h<=r+g;return(c==="none"||c==="partially_ejected"&&v&&k&&this.sourceBuffer&&!ii(this.sourceBuffer.buffered,r))&&v&&k});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=a;c<s.length&&(n<=u||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:l,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await fr(o,async function*(){let d=eu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:l,priority:r,isLowLatency:this.isActiveLowLatency()});if(!d)return;let c=new DataView(d);if(this.isActiveLowLatency()){let p=t.segmentReference.timescale,h=xi(t.mime);a.segment.time.to=h.getSegmentEndTime(c,p)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(c,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Pi(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let l of e)l.status="downloading",this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await fr(n,async function*(){let l=eu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),Zo(window,"online").pipe(sA()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(l){this.abortActiveSegments(e),Pi(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Mt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,br.default)(e,0).byte.from,to:(0,br.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,l)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:mr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Mt(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!s.aborted)try{let c=this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:mr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:a,signal:s,onProgress:l,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=xi(n.mime).parseFeedableSegmentChunk(u,this.isLive);d?.byteLength&&(l.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let l=o.segmentReference.type,u=e.byteLength;for(let d of this.activeSegments){let{segment:c}=d,p=l==="byteRange",h=p?c.byte.to-c.byte.from+1:u;if(d.representationId!==t||!(!p||c.byte.from>=r&&c.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let S=p?c.byte.from-r:0,v=p?c.byte.to-r:e.byteLength,g=S<a,k=v<=a;if(c.status==="downloading"&&g&&k){c.status="downloaded";let A=new DataView(e.buffer,e.byteOffset+S,h);this.sourceBufferTaskQueue.append(A,s).then(b=>b&&!s.aborted?this.onSegmentFullyAppended(d,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(d.loadedBytes=Math.min(h,a-S),d.loadedBytes>d.feedingBytes)){let A=new DataView(e.buffer,e.byteOffset+S+d.feedingBytes,d.loadedBytes-d.feedingBytes),b=d.loadedBytes===h?A:xi(o.mime).parseFeedableSegmentChunk(A);b?.byteLength&&(c.status="partially_fed",d.feedingBytes+=b.byteLength,this.sourceBufferTaskQueue.append(b,s).then(T=>{if(s.aborted)n();else if(T)d.fedBytes+=b.byteLength,d.fedBytes===h&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<h)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Xo(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Fo(()=>(0,tb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?fr(this.destroyAbortController.signal,async function*(){let o=eu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,xi(e.mime),a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:d}=o,c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&Mt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:mr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||ze(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,l=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let d=Xo(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status==="fed"&&l(d)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status==="fed"&&l(d)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(c)){s=d,n=c;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let c of d)c.time.from>e+u&&c.status==="fed"&&l(c)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Fo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:mr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(ze(this.sourceBuffer)||ze(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),l=e.some(d=>d.from-t<=n&&d.to+t>=o),u=e.filter(d=>n>=d.from-t&&n<=d.to+t||o>=d.from-t&&o<=d.to+t);l||(u.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var wi=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var rb=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as Ri,assertNever as ib,fromEvent as ab,merge as uA,now as tu,Subscription as lA,ValueSubject as ru}from"@vkontakte/videoplayer-shared";var Za=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new ru(void 0);this.lastConnectionReused$=new ru(void 0);this.lastRequestFirstBytes$=new ru(void 0);this.abortAllController=new Ye;this.subscription=new lA;this.fetchManifest=Ri(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=wi(t));let r=yield Ge(t,{signal:this.abortAllController.signal}).catch($i);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Ri(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:l=!1}={}){let u=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let w=new URL(u,location.href);w.searchParams.append("bytes",`${r.from}-${r.to}`),u=w.toString();break}default:ib(t)}this.requestQuic&&(u=wi(u));let c=this.abortAllController.signal,p;if(n){let w=new Ye;if(p=uA(ab(this.abortAllController.signal,"abort"),ab(n,"abort")).subscribe(()=>{try{w.abort()}catch(D){$i(D)}}),this.abortAllController.signal.aborted||n.aborted)try{w.abort()}catch(D){$i(D)}c=w.signal}let h=tu(),m=yield Ge(u,{priority:s,headers:d,signal:c}).catch($i),S=tu();if(!m)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-h),!m.ok||!m.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!a&&!o)return p?.unsubscribe(),m.arrayBuffer();let[v,g]=m.body.tee(),k=v.getReader();o&&this.throughputEstimator?.trackStream(g,l);let A=0,b=new Uint8Array(0),T=!1,M=w=>{p?.unsubscribe(),T=!0,$i(w)},P=Ri(c,async function*({done:w,value:D}){if(A===0&&this.lastRequestFirstBytes$.next(tu()-h),c.aborted){p?.unsubscribe();return}if(!w&&D){let x=new Uint8Array(b.length+D.length);x.set(b),x.set(D,b.length),b=x,A+=D.byteLength,a?.(new DataView(b.buffer),A),yield k?.read().then(P,M)}}.bind(this));return yield k?.read().then(P,M),p?.unsubscribe(),T?null:b.buffer}.bind(this));this.fetchByteRangeRepresentation=Ri(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,l=!1,u,d;e.indexRange&&(u=e.indexRange.from,d=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,a),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!c)return null;let p=new DataView(c,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let S;if(l)S=new DataView(c,m.from-n,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!g)return null;S=new DataView(g)}let v=t.parseSegments(S,h,m);return{init:h,dataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=Ri(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=rb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:ib(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},$i=i=>{if(!Pi(i))throw i};var Dt=(i,e,t)=>t*e+(1-t)*i,iu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,sb=(i,e,t,r)=>{let a=0,s=t,n=iu(i,e),o=e<r?e:r;for(let l=0;l<o;l++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as cA,ValueSubject as nb}from"@vkontakte/videoplayer-shared";var ot=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new nb(e.initial),this.debounced$=new nb(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new X(`raw_${t}`),this.smoothedSeries$=new X(`smoothed_${t}`),this.reportedSeries$=new X(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(cA(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(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Dt(this.slow,t,this.params.emaAlphaSlow),this.fast=Dt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var ts=class extends ot{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=iu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,t,this.params.emaAlpha);let a=sb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var rs=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?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Ot=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 ts({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 rs({initial:e,label:"liveEdgeDelay",...t})}};var ob=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var pb=["timeupdate","progress","play","seeked","stalled","waiting"];var as=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new db;this.representationSubscription=new db;this.state$=new R("none");this.currentVideoRepresentation$=new le(void 0);this.currentVideoRepresentationInit$=new le(void 0);this.currentAudioRepresentation$=new le(void 0);this.currentVideoSegmentLength$=new le(0);this.currentAudioSegmentLength$=new le(0);this.error$=new cb;this.lastConnectionType$=new le(void 0);this.lastConnectionReused$=new le(void 0);this.lastRequestFirstBytes$=new le(void 0);this.isLive$=new le(!1);this.liveDuration$=new le(0);this.liveAvailabilityStartTime$=new le(void 0);this.bufferLength$=new le(0);this.liveLoadBufferLength$=new le(0);this.livePositionFromPlayer$=new le(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new cb;this.gapWatchdogActive=!1;this.destroyController=new Ye;this.initManifest=au(this.destroyController.signal,async function*(e,t,r){this.element=e,this.manifestUrlString=z(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=au(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ut.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=Km(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:ut.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;let r=(s,n,o)=>!!(this.element?.canPlayType?.(n)&&We()?.isTypeSupported?.(`${n}; codecs="${o}"`)||s==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let s of["video","audio"]){let o=t.streams[s].filter(({mime:d,codecs:c})=>r(s,d,c)),l=new Set(o.map(({codecs:d})=>d)),u=um(l);u&&(a[s]=o.filter(({codecs:d})=>d===u))}return{...t,streams:a}}.bind(this));this.initRepresentations=au(this.destroyController.signal,async function*(e,t,r){Vt(this.manifest),Vt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=c=>{this.representationSubscription.add(Sr(c,"error").pipe(is(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?em():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&za())if(r){let c=document.createElement("source");a(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=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,manifest:this.manifest},o=this.manifest.streams.video.reduce((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new Ai("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],lb(t)){let c=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new Ai("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(su(1e3).subscribe(c=>{if(this.element?.paused){let p=yo(this.manifestUrlString,2);this.manifestUrlString=z(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(vr(...pb.filter(c=>c!=="waiting").map(c=>Sr(this.element,c))).pipe(nu(c=>this.element?nt(this.element.buffered,this.element.currentTime*1e3):0),pA(),is(c=>!!c),hA(c=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(is(p=>this.isActiveLowLatency&&!!p)).subscribe(p=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(p=>{if(!this.isActiveLowLatency||!p)return;let h=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,m=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-h,g=1;Math.abs(v)>m&&(g=1+Math.sign(v)*S),ob(this.element,g)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add(ub({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(fA(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(Vt(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,S=yo(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,g=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),k=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,b=this.isActiveLowLatency?h:p,T=3;if(this.isActiveLowLatency?T=0:b<g+A&&b>=g?T=1:S!==0&&b<g&&(T=2),isFinite(p)&&(c=p>c?p:c),T===2||T===1){let M=c-(g+k),P=this.normolizeLiveOffset(Math.trunc(S+M/m)),w=Math.abs(P-S),D;!p||w<=this.tuning.dashCmafLive.offsetCalculationError?D=S:P>0&&w>this.tuning.dashCmafLive.offsetCalculationError?D=P:D=0,this.manifestUrlString=z(this.manifestUrlString,D,2)}T!==3&&T!==0&&(c=0,this.updateLive())}))}let l=vr(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(nu(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),u=vr(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(nu(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue())));this.representationSubscription.add(vr(this.forceEnded$,ub({allBuffersFull:l,someBufferEnded:u}).pipe(is(({allBuffersFull:c,someBufferEnded:p})=>c&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(vr(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(c=>this.source?.addEventListener("sourceopen",c)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(c=>c.representations).flatMap(c=>c.duration??0)];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&lb(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=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=su(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ut.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Za({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ot.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){Vt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=z(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio))}initBuffer(){Vt(this.element),this.state$.setState("running"),this.subscription.add(vr(...pb.map(e=>Sr(this.element,e)),Sr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ut.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Sr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Sr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ii(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=su(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ut.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t)}seek(e,t){Vt(this.element),Vt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),ii(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],a=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-a<=t&&n.to+a>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 ss=class{constructor(e,t){this.fov=e,this.orientation=t}};var ns=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var hb=`attribute vec2 a_vertex;
33
+ [best track] ${V?.quality}
34
+ [selected track] ${A?.quality}
35
+ `});let w=A&&u&&u.history[A.id]&&ts()-u.history[A.id]<=i.trackCooldown&&(!u.last||A.id!==u.last.id);if(A?.id&&u&&!w&&u.recordSelection(A),w&&u?.last){let T=u.last;return u?.recordSwitch(T),c({message:`
36
+ [last selected] ${T?.quality}
37
+ `}),T}return u?.recordSwitch(A),A},He=_o;var G=n=>new URL(n).hostname;import{assertNever as os,assertNonNullable as us,combine as au,debounce as su,ErrorCategory as ds,filter as nu,filterChanged as ou,isNonNullable as Gr,map as Fi,merge as ls,observableFrom as uu,Subscription as du,ValueSubject as Qr,videoQualityToHeight as lu,videoSizeToQuality as cu}from"@vkontakte/videoplayer-shared";var is=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},Z=async n=>{let e=n.muted;try{await n.play()}catch(t){if(!is(t))return!1;if(e)return console.warn(t),!1;n.muted=!0;try{await n.play()}catch(i){return is(i)&&(n.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Oi,isNullable as Uo,assertNonNullable as Rt}from"@vkontakte/videoplayer-shared";import{isNonNullable as rs,assertNonNullable as Vi,now as No}from"@vkontakte/videoplayer-shared";function Q(){return No()}function Nr(n){return Q()-n}function Fr(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,d=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let u=s.indexOf("?")>-1?"&":"?";return d&&(s+=u+"lowLat=1",u="&"),o&&(s+=u+"_rnd="+Math.floor(999999999*Math.random())),s}}}function as(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function pt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,d=!1,u=0,l,c,p=!1,h="arraybuffer",m=7e3,v=2e3,f=()=>{if(d)return;Vi(l);let P=Nr(l),O;if(P<v){O=v-P,setTimeout(f,O);return}v*=2,v>m&&(v=m),s&&s.abort(),s=new r,B()},g=P=>(a=P,x),S=P=>(c=P,x),_=()=>(h="json",x),b=()=>{if(!d){if(--u>=0){f(),i&&i();return}d=!0,c&&c(),t&&t()}},I=P=>(p=P,x),B=()=>{l=Q(),s=new r,s.open("get",n);let P=0,O,j=0,he=()=>(Vi(l),Math.max(l,Math.max(O||0,j||0)));if(a&&s.addEventListener("progress",k=>{let M=Q();a.updateChunk&&k.loaded>P&&(a.updateChunk(he(),k.loaded-P),P=k.loaded,O=M)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>b())),s.addEventListener("load",()=>{if(d)return;Vi(s);let k=s.status;if(k>=200&&k<300){if(s.response.byteLength&&a){let M=s.response.byteLength-P;M&&a.updateChunk&&a.updateChunk(he(),M)}s.responseType==="json"&&!Object.values(s.response).length?b():(c&&c(),e(s.response))}else b()}),s.addEventListener("error",()=>{b()}),p){let k=()=>{Vi(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(j=Q(),s.removeEventListener("readystatechange",k))};s.addEventListener("readystatechange",k)}return s.responseType=h,s.send(),x},x={withBitrateReporting:g,withParallel:I,withJSONResponse:_,withRetryCount:P=>(u=P,x),withRetryInterval:(P,O)=>(rs(P)&&(v=P),rs(O)&&(m=O),x),withTimeout:P=>(o=P,x),withFinally:S,send:B,abort:()=>{s&&(s.abort(),s=void 0),d=!0,c&&c()}};return x}var $t=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let d=a.bytes*s/o;r+=d,a.start=t,a.bytes-=d}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Lt=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Q(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=d=>{e._complete=1,e._responseData=d,e._downloadTime=Q()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=pt(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Q()}_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=Q();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var _i=1e4,Ur=3;var Ho=6e4,Go=10,Qo=1,jo=500,Mt=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 $t(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Fr(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Fr(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Oi(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let s=()=>{as(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):s()})};s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Lt(Ur,_i,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,d=null,u=null,l=!1,c=()=>{let b=a&&(!l||l===this.rep);return b||t("Not running!"),b},p=(b,I,B)=>{d&&d.abort(),d=pt(this.urlResolver.resolve(b,!1),I,B,()=>this._retryCallback()).withTimeout(_i).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ur).withFinally(()=>{d=null}).send()},h=(b,I,B)=>{Rt(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),I,B,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=b=>{let I=i.playbackRate;i.playbackRate!==b&&(t(`Playback rate switch: ${I}=>${b}`),i.playbackRate=b)},v=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),f()},f=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let B=Q()-1e4,V=0;for(let w=0;w<this.bufferStates.length;w++){let T=this.bufferStates[w];b=Math.min(b,T.buf),T.ts<B&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${b} drop=${V} jitter=${this.sourceJitter}`);let A=b-Qo;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?m(1.15):A>1?m(1.1):A>.3?m(1.05):m(1)}},g=b=>{let I,B=()=>I&&I.start?I.start.length:0,V=k=>I.start[k]/1e3,A=k=>I.dur[k]/1e3,w=k=>I.fragIndex+k,T=(k,M)=>({chunkIdx:w(k),startTS:V(k),dur:A(k),discontinuity:M}),x=()=>{let k=0;if(I&&I.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,F=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,H=M;this.sourceJitter>1&&(H+=this.sourceJitter-1);let te=I.dur.length-1;for(;te>=0&&(H-=I.dur[te],!(H<=0));--te);k=Math.min(te,I.dur.length-1-F),k=Math.max(k,0)}return T(k,!0)},P=k=>{let M=B();if(!(M<=0)){if(Oi(k)){for(let F=0;F<M;F++)if(V(F)>k)return T(F)}return x()}},O=k=>{let M=B(),F=k?k.chunkIdx+1:0,H=F-I.fragIndex;if(!(M<=0)){if(!k||H<0||H-M>Go)return t(`Resync: offset=${H} bChunks=${M} chunk=`+JSON.stringify(k)),x();if(!(H>=M))return T(F-I.fragIndex,!1)}},j=(k,M,F)=>{u&&u.abort(),u=pt(this.urlResolver.resolve(k,!0,this.lowLatency),M,F,()=>this._retryCallback()).withTimeout(_i).withRetryCount(Ur).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(k,M)=>{j(b,F=>{if(!c())return;I=F;let H=!!I.lowLatency;H!==this.lowLatency&&v(H);let te=0;for(let De=0;De<I.dur.length;++De)te+=I.dur[De];te>0&&(Rt(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,k(P(M))},()=>this._handleNetworkError())},nextChunk:O}},S=()=>{a=!1,o&&o.abort(),d&&d.abort(),u&&u.abort(),Rt(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:b=>{let{videoElement:I,logger:B}=this.params,V=g(e.jidxUrl),A,w,T,x,P=0,O,j,he,k=()=>{O&&(clearTimeout(O),O=void 0);let C=Math.max(jo,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=P+C,re=Q(),me=Math.min(1e4,ie-re);P=re;let Pe=()=>{u||c()&&V.seek(()=>{c()&&(P=Q(),M(),k())})};me>0?O=window.setTimeout(()=>{this.paused?k():Pe()},me):Pe()},M=()=>{let C;for(;C=V.nextChunk(x);)x=C,Sr(C);let ie=V.nextChunk(T);if(ie){if(T&&ie.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?k():(S(),this._initPlayerWith(e));return}De(ie)}else k()},F=(C,ie)=>{if(!c()||!this.sourceBuffer)return;let re,me,Pe,Tt=ae=>{window.setTimeout(()=>{c()&&F(C,ie)},ae)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),Tt(100);else{let ae=Q(),Ce=I.currentTime;!this.paused&&I.buffered.length>1&&j===Ce&&ae-he>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),j!==Ce&&(j=Ce,he=ae);let fe=this._getBufferSizeSec();if(fe>30)B(`Buffered ${fe} seconds; delaying appendBuffer`),Tt(2e3);else try{this.sourceBuffer.appendBuffer(C),this.videoPlayStarted?(this.bufferStates.push({ts:ae,buf:fe}),f(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(ve){if(ve.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),Pe=this.sourceBuffer.buffered.length,Pe!==0&&(re=this.sourceBuffer.buffered.start(0),me=Ce,me-re>4&&this.sourceBuffer.remove(re,me-3)),Tt(1e3);else throw ve}}},H=()=>{w&&A&&(B([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(T)]),F(w,function(){w=null,M()}))},te=C=>e.fragUrlTemplate.replace("%%id%%",C.chunkIdx),De=C=>{c()&&h(te(C),(ie,re)=>{if(c()){if(re/=1e3,w=ie,T=C,s=C.startTS,re){let me=Math.min(10,C.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}H()}},()=>this._handleNetworkError())},Sr=C=>{c()&&(Rt(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(C),!1)))},ki=C=>{c()&&(e.cachedHeader=C,F(C,()=>{A=!0,H()}))};a=!0,V.seek(C=>{if(c()){if(P=Q(),!C){k();return}x=C,!Uo(b)||C.startTS>b?De(C):(T=C,M())}},b),e.cachedHeader?ki(e.cachedHeader):p(e.headerUrl,ki,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>s},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Oi(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Rt(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Oi(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(p,h)=>{let m=Q();if(this.chunkRateEstimator.addInterval(p,m,h)){let f=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:f}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),s=-1/0,o,d=!0,u=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(d&&c>o&&Nr(s)<3e4)return;i(c)}d=this.autoQuality};return{updateChunk:(c,p)=>{let h=a.updateChunk(c,p);return h&&u(),h},notifySwitch:c=>{let p=Q();c<o&&(s=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=pt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(_i).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;Z(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s?.length?(s.forEach((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,o.push(d))}),o.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Ho))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Wo,filter as ss,fromEvent as Yo,interval as qo,isHigher as zo,isInvariantQuality as Ko,isLower as Jo,merge as Xo,Subject as ns,Subscription as Zo}from"@vkontakte/videoplayer-shared";var Hr=class{constructor(){this.onDroopedVideoFramesLimit$=new ns;this.subscription=new Zo;this.playing=!1;this.tracks=[];this.forceChecker$=new ns;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Ko(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&zo(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Yo(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=qo(this.droppedFramesChecker.checkTime).pipe(ss(()=>this.playing),ss(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Wo(this.droppedFramesChecker.checkTime)),i=Xo(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>Jo(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ni=Hr;import{map as eu,Observable as tu}from"@vkontakte/videoplayer-shared";import{fromEvent as iu}from"@vkontakte/videoplayer-shared";var Dt=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var ru=(n,e)=>new tu(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(d=>t.next(d.isIntersecting||Dt()))},{...i,...e});r.observe(n);let a=iu(document,"visibilitychange").pipe(eu(s=>!document.hidden||Dt())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),de=ru;var pu=["paused","playing","ready"],hu=["paused","playing","ready"],Ct=class{constructor(e){this.subscription=new du;this.videoState=new $("stopped");this.representations$=new Qr([]);this.textTracksManager=new oe;this.droppedFramesManager=new Ni;this.maxSeekBackTime$=new Qr(1/0);this.zeroTime$=new Qr(void 0);this.liveOffset=new we;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:ds.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),s=Fe(r.name)??cu(r.video),o=r.bitrate/1e3,d={...r.video};if(!s)continue;let u={id:a,quality:s,bitrate:o,size:d};i.push({track:u,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Gr(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(hu.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&pu.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(W(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let d=r?.from;d&&d==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.dash.reinit(W(this.params.source.url,d))}return;default:return os(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:ds.WTF,message:"DashLiveProvider internal logic error",thrown:r})};ls(this.videoState.stateChangeStarted$.pipe(Fi(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Fi(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=z(e.container),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(G(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 i=X(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(Fi(r=>r.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ou(),Fi(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(au({zeroTime:this.zeroTime$.pipe(nu(Gr)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Te(this.video,this.params.desiredState.isLooped,t)).add(J(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ne(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(de(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&lu(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return os(r.to)}},t)).add(ls(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,uu(["init"])).pipe(su(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),K(this.video)}createLiveDashPlayer(){let e=new Mt({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Gr(t)?t:He(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r?.id,s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),d&&this.setAutoQuality(i),s||d||a!==o){let u=e.find(({track:l})=>l.id===a)?.representation;us(u,"Representations missing"),this.dash.startPlay(u,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;us(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(W(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var cs=Ct;var Le=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as Ku,assertNonNullable as zs,debounce as Ju,ErrorCategory as sa,filter as Xu,filterChanged as Ks,fromEvent as Zu,isLowerOrEqual as Js,isNonNullable as ed,videoSizeToQuality as Xs,map as Zi,merge as er,observableFrom as td,observeElementSize as id,once as rd,Subscription as ad,ValueSubject as Zs}from"@vkontakte/videoplayer-shared";var Bt=(n,e)=>{for(let t=0;t<n.length;t++)if(n.start(t)*1e3<=e&&n.end(t)*1e3>e)return!0;return!1};import{abortable as ia,assertNonNullable as at,combine as Yi,ErrorCategory as Qe,filter as qi,filterChanged as Hs,fromEvent as gt,interval as ra,isNonNullable as Gs,map as aa,merge as St,Subject as Qs,Subscription as js,tap as Qu,throttle as ju,ValueSubject as ee}from"@vkontakte/videoplayer-shared";import{assertNever as mu,CurrentClientBrowser as fu,ErrorCategory as ps,getCurrentBrowser as bu,Subject as hs}from"@vkontakte/videoplayer-shared";var gu=16,ms=!1;try{ms=bu().browser===fu.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=gu}catch(n){console.error(n)}var jr=class{constructor(e){this.bufferFull$=new hs;this.error$=new hs;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:ps.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;ms&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:ps.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:mu(t)}}},fs=jr;var Wr=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as ft,assertNever as Vu,assertNonNullable as Ee,ErrorCategory as bt,fromEvent as Kr,getExponentialDelay as Jr,isNonNullable as Ds,isNullable as xe,once as Ou,Subject as _u,Subscription as Nu,ValueSubject as ri}from"@vkontakte/videoplayer-shared";var D=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),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 r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ht=class extends D{};var Vt=class extends D{};var Ot=class extends D{constructor(t,i){super(t,i);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var _t=class extends D{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Nt=class extends D{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ft=class extends D{constructor(t,i){super(t,i);this.data=this.content}};var U=class extends D{constructor(t,i){super(t,i);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Je=class extends U{constructor(t,i){super(t,i);this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,o=a<<1>>>1,d=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:o,subsegmentDuration:d,SAPType:u,SAPDeltaTime:l})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var Ut=class extends D{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ht=class extends D{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gt=class extends U{constructor(t,i){super(t,i);switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Qt=class extends U{constructor(t,i){super(t,i);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var jt=class extends U{constructor(t,i){super(t,i);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Wt=class extends D{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yt=class extends U{constructor(t,i){super(t,i);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 qt=class extends D{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zt=class extends D{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Kt=class extends U{constructor(t,i){super(t,i);this.sequenceNumber=this.readUint32()}};var Jt=class extends D{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xt=class extends U{constructor(t,i){super(t,i);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 Zt=class extends U{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ei=class extends U{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var vu={ftyp:Ot,moov:_t,moof:Nt,mdat:Ft,sidx:Je,trak:Ut,mdia:Wt,mfhd:Kt,tkhd:Yt,traf:Jt,tfhd:Xt,tfdt:Zt,trun:ei,minf:qt,sv3d:Ht,st3d:Gt,prhd:Qt,proj:zt,equi:jt,uuid:Vt,unknown:ht},Xe=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),s=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!s.size)break;t.push(s),i+=s.size}catch{break}return t}createBox(e,t){let i=vu[e];return i?new i(t,new n):new ht(t,new n)}};var mt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Tu=new TextDecoder("ascii"),Iu=n=>Tu.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",Eu=n=>{let e=new Je(n,new Xe),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},xu=(n,e)=>{let i=new Xe().parse(n),r=new mt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],d=s[s.length-1],u=o.source.byteOffset,c=d.source.byteOffset-o.source.byteOffset+d.size;return new DataView(n.buffer,u,c)},ku=(n,e)=>{let i=new Xe().parse(n),a=new mt(i).findAll("traf"),s=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),d=a[a.length-1].children.find(c=>c.type==="trun"),u=0;return d.sampleDuration.length?u=d.sampleDuration.reduce((c,p)=>c+p,0):u=s.defaultSampleDuration*d.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},Pu=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Xe().parse(n),r=new mt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let d=r.find("equi");d&&(e.projectionData.bounds.top=d.projectionBoundsTop,e.projectionData.bounds.right=d.projectionBoundsRight,e.projectionData.bounds.bottom=d.projectionBoundsBottom,e.projectionData.bounds.left=d.projectionBoundsLeft)}return e},bs={validateData:Iu,parseInit:Pu,getIndexRange:()=>{},parseSegments:Eu,parseFeedableSegmentChunk:xu,getSegmentEndTime:ku};import{assertNonNullable as qr,isNonNullable as ys,isNullable as wu}from"@vkontakte/videoplayer-shared";import{assertNever as Au}from"@vkontakte/videoplayer-shared";var gs={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"}},Ss=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ti(n,t),r=i in gs,a=r?gs[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let d=new DataView(n.buffer,n.byteOffset+t+1,o-1),u=s&255>>o,l=ti(d),c=u*2**((o-1)*8)+l,p=t+o,h;return p+c>n.byteLength?h=new DataView(n.buffer,n.byteOffset+p):h=new DataView(n.buffer,n.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},ti=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ge=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return ti(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:Au(e)}},Ze=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Ss(i);if(!e(r))return;r.type==="master"&&Ze(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},vs=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Ss(n);return Ze(r.value,({tag:a,type:s,value:o})=>(a===17143?e=ge(o,s):a===17026?t=ge(o,s):a===17029&&(i=ge(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ts=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],$u=[231,22612,22743,167,171,163,160,175],Lu=n=>{let e,t,i,r,a=!1,s=!1,o=!1,d,u,l=!1,c=0;return Ze(n,({tag:p,type:h,value:m,valueSize:v})=>{if(p===21419){let f=ge(m,h);u=ti(f)}else p!==21420&&(u=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+v):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=ge(m,h):p===17545?r=ge(m,h):p===21420&&u===475249515?d=ge(m,h):p===374648427?Ze(m,({tag:f,type:g,value:S})=>f===30321?(l=ge(S,g)===1,!1):!0):a&&s&&Ts.includes(p)&&(o=!0),!o}),qr(e,"Failed to parse webm Segment start"),qr(t,"Failed to parse webm Segment end"),qr(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:l,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ru=n=>{if(wu(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Mu=(n,e)=>{let t=!1,i=!1,r=o=>ys(o.time)&&ys(o.position),a=[],s;return Ze(n,({tag:o,type:d,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=ge(u,d));break;case 183:break;case 241:s&&(s.position=ge(u,d));break;default:t&&Ts.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,d)=>{let{time:u,position:l}=o,c=a[d+1];return{status:"none",time:{from:u,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Du=n=>{let e=0,t=!1;try{Ze(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):$u.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},Is={validateData:vs,parseInit:Lu,getIndexRange:Ru,parseSegments:Mu,parseFeedableSegmentChunk:Du};import{isNonNullable as xs,isNullable as ks}from"@vkontakte/videoplayer-shared";var Es=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var Ps=n=>{if(!n.startsWith("P"))return;let e=(s,o)=>{let d=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(d)?0:d)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},et=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,d)=>ks(a)?o:ks(d)?a:a.padStart(parseInt(d,10),"0"))}return t},ws=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=a.querySelector("BaseURL")?.textContent?.trim()??"",d=s.children,u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,p,h=a.getAttribute("mediaPresentationDuration"),m=s.getAttribute("duration"),f=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Ps(h);else if(m){let b=Ps(m);xs(b)&&(p=b)}else f&&(p=parseInt(f,10));let g=0,S=a.getAttribute("profiles")?.split(",")??[],_=S.includes("urn:webm:dash:profile:webm-on-demand:2012")||S.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let b of d){let I=b.getAttribute("mimeType"),B=b.getAttribute("codecs"),V=b.getAttribute("contentType")??I?.split("/")[0],A=b.getAttribute("profiles")?.split(",")??[],w=b.querySelectorAll("Representation"),T=b.querySelector("SegmentTemplate");if(V==="text"){for(let x of w){let P=x.getAttribute("id")||"",O=b.getAttribute("lang"),j=b.getAttribute("label"),he=x.querySelector("BaseURL")?.textContent?.trim()??"",k=new URL(he||o,e).toString(),M=P.includes("_auto");r.text.push({id:P,lang:O,label:j,isAuto:M,kind:"text",url:k})}continue}for(let x of w){let P=x.getAttribute("mimeType")??I,O=x.getAttribute("codecs")??B??"",j=x.getAttribute("contentType")??P?.split("/")[0]??V,he=b.getAttribute("profiles")?.split(",")??[],k=parseInt(x.getAttribute("width")??"",10),M=parseInt(x.getAttribute("height")??"",10),F=parseInt(x.getAttribute("bandwidth")??"",10)/1e3,H=x.getAttribute("frameRate")??"",te=x.getAttribute("quality")??void 0,De=H?Es(H):void 0,Sr=x.getAttribute("id")??(g++).toString(10),ki=j==="video"?`${M}p`:j==="audio"?`${F}Kbps`:O,C=`${Sr}@${ki}`,ie=x.querySelector("BaseURL")?.textContent?.trim()??"",re=new URL(ie||o,e).toString(),me=[...S,...A,...he],Pe,Tt=x.querySelector("SegmentBase"),ae=x.querySelector("SegmentTemplate")??T;if(Tt){let fe=x.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ve,vr]=fe.split("-").map(ut=>parseInt(ut,10)),Be={from:ve,to:vr},It=x.querySelector("SegmentBase")?.getAttribute("indexRange"),[yr,Pi]=It?It.split("-").map(ut=>parseInt(ut,10)):[],Et=It?{from:yr,to:Pi}:void 0;Pe={type:"byteRange",url:re,initRange:Be,indexRange:Et}}else if(ae){let fe={representationId:x.getAttribute("id")??void 0,bandwidth:x.getAttribute("bandwidth")??void 0},ve=parseInt(ae.getAttribute("timescale")??"",10),vr=ae.getAttribute("initialization")??"",Be=ae.getAttribute("media"),It=parseInt(ae.getAttribute("startNumber")??"",10)??1,yr=et(vr,fe);if(!Be)throw new ReferenceError("No media attribute in SegmentTemplate");let Pi=ae.querySelectorAll("SegmentTimeline S")??[],Et=[],ut=0,Tr="",Ir=0;if(Pi.length){let Ai=It,be=0;for(let dt of Pi){let ye=parseInt(dt.getAttribute("d")??"",10),qe=parseInt(dt.getAttribute("r")??"",10)||0,wi=parseInt(dt.getAttribute("t")??"",10);be=Number.isFinite(wi)?wi:be;let Er=ye/ve*1e3,Kn=be/ve*1e3;for(let $i=0;$i<qe+1;$i++){let Jn=et(Be,{...fe,segmentNumber:Ai.toString(10),segmentTime:(be+$i*ye).toString(10)}),ya=(Kn??0)+$i*Er,Xn=ya+Er;Ai++,Et.push({time:{from:ya,to:Xn},url:Jn})}be+=(qe+1)*ye,ut+=(qe+1)*Er}Ir=be/ve*1e3,Tr=et(Be,{...fe,segmentNumber:Ai.toString(10),segmentTime:be.toString(10)})}else if(xs(p)){let be=parseInt(ae.getAttribute("duration")??"",10)/ve*1e3,dt=Math.ceil(p/be),ye=0;for(let qe=1;qe<dt;qe++){let wi=et(Be,{...fe,segmentNumber:qe.toString(10),segmentTime:ye.toString(10)});Et.push({time:{from:ye,to:ye+be},url:wi}),ye+=be}Ir=ye,Tr=et(Be,{...fe,segmentNumber:dt.toString(10),segmentTime:ye.toString(10)})}let zn={time:{from:Ir,to:1/0},url:Tr};Pe={type:"template",baseUrl:re,segmentTemplateUrl:Be,initUrl:yr,totalSegmentsDurationMs:ut,segments:Et,nextSegmentBeyondManifest:zn,timescale:ve}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!P)continue;let Ce={video:"video",audio:"audio",text:"text"}[j];Ce&&r[Ce].push({id:C,kind:Ce,segmentReference:Pe,profiles:me,duration:p,bitrate:F,mime:P,codecs:O,width:k,height:M,fps:De,quality:te})}}return{dynamic:u,liveAvailabilityStartTime:c,duration:p,container:_,representations:r}};import{videoSizeToQuality as Bu}from"@vkontakte/videoplayer-shared";var $s=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a})=>{let s=(a?Fe(a):void 0)??Bu({width:e,height:t});return s&&{id:n,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},Ls=({id:n,bitrate:e})=>({id:n,bitrate:e}),Rs=(n,e,t)=>{let i=e.indexOf(t);return n.at(Math.round(n.length*i/e.length))??n.at(-1)},Ms=({id:n,lang:e,label:t,url:i,isAuto:r})=>({id:n,url:i,isAuto:r,type:"internal",language:e,label:t}),Ui=n=>"url"in n,tt=n=>n.type==="template",ii=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var ai=class{constructor(e,t,i,r,{fetcher:a,tuning:s,getCurrentPosition:o,isActiveLowLatency:d,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new ri(0);this.onLastSegment$=new ri(!1);this.fullyBuffered$=new ri(!1);this.playingRepresentation$=new ri(void 0);this.playingRepresentationInit$=new ri(void 0);this.error$=new _u;this.gaps=[];this.subscription=new Nu;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.destroyAbortController=new AbortController;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=ft(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ee(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new fs(this.sourceBuffer),this.subscription.add(Kr(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>this.error$.next({id:"SegmentEjection",category:bt.WTF,message:"Error when trying to clear segments ejected by browser",thrown:s}))),this.subscription.add(Kr(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:bt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let d=Math.min(this.bufferLimit,Wr(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=d,this.tuning.useNewPruneBufferStrategy){let u=Le(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,s*2,u<l)}else this.pruneBufferOld(o,s)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(s=>this.error$.next(s))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Ee(i,"No init buffer for starting representation"),Ee(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=ft(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);Ee(t,`No such representation ${e}`);let i=this.segments.get(e),r=this.initData.get(e);if(xe(r)||xe(i)?yield this.loadInit(t,"high",!1):r instanceof Promise&&(yield r),i=this.segments.get(e),Ee(i,"No segments for starting representation"),r=this.initData.get(e),!r||!(r instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(r,this.downloadAbortController.signal);let a=this.getCurrentPosition();Ds(a)&&(this.isLive||(i.forEach(s=>s.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(a,1/0,!0)),this.maintain(a))}.bind(this));this.seekLive=ft(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let o of this.representations.keys()){let d=e.find(c=>c.id===o);d&&this.representations.set(o,d);let u=this.representations.get(o);if(!u||!tt(u.segmentReference))return;let l=this.getActualLiveStartingSegments(u.segmentReference);this.segments.set(u.id,l)}let t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);Ee(i);let r=this.segments.get(t);Ee(r,"No segments for starting representation");let a=this.initData.get(t);if(Ee(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let s=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),s&&(yield this.sourceBufferTaskQueue.remove(s.from*1e3,s.to*1e3,this.destroyAbortController.signal)),this.searchGaps(r,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));switch(this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=d,this.isLive=!!l?.dynamic,this.container=i,i){case"mp4":this.containerParser=bs;break;case"webm":this.containerParser=Is;break;default:Vu(i)}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 AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(xe(e)||xe(this.downloadingRepresentationId)||xe(this.playingRepresentationId)||xe(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ee(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((r?.time.to??0)-(r?.time.from??0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=Le(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Wr(this.sourceBuffer.buffered)>=this.bufferLimit){let u=Le(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))u="high";else{let l=o.at(0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&Le(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=i.at(-1);d&&d.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;Ds(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){for(let t of e?.representations[this.kind].values()??[]){if(!t||!tt(t.segmentReference))return;let i=t.segmentReference.segments.map(o=>({...o,status:"none",size:void 0})),r=this.segments.get(t.id)??[],a=r.at(-1)?.time.to??0,s=i?.findIndex(o=>Math.floor(a)>=Math.floor(o.time.from)&&Math.floor(a)<=Math.floor(o.time.to));if(s===-1){this.liveUpdateSegmentIndex=0;let o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{let o=i.slice(s+1);this.segments.set(t.id,[...r,...o])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ee(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLive(i)}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(let t of this.representations.values()){let i=t.segmentReference;if(!tt(i))return;let r=Math.round(e.time.to*i.timescale/1e3).toString(10),a=et(i.segmentTemplateUrl,{segmentTime:r}),s=this.segments.get(t.id)??[],o=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));o&&(o.time.to=e.time.to),!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))||s.push({status:"none",time:{from:e.time.to,to:1/0},url:a})}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:p,to:h}},m)=>{let v=p<=i&&h>=i,f=p>i||v||m===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=i+g||h<=i+g;return(c==="none"||c==="partially_ejected"&&f&&S&&this.sourceBuffer&&!Bt(this.sourceBuffer.buffered,i))&&f&&S});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(s<=u||o<=l);c++){let p=a[c];if(s+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")d.push(p);else break}return d}async loadSegments(e,t,i="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:s,signal:o,onProgress:d,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ft(o,async function*(){let l=Jr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!l)return;let c=new DataView(l);if(this.isActiveLowLatency()){let p=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,p)}d&&r.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(c,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),ii(l)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let d of e)d.status="downloading",this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await ft(s,async function*(){let d=Jr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,d),Kr(window,"online").pipe(Ou()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.failedDownloads=0}catch(d){this.abortActiveSegments(e),ii(d)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(tt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!tt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,s=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,l)=>{if(!a.aborted)try{let c=this.onSomeTemplateDataLoaded({dataView:u,loaded:l,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:d,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let o of this.activeSegments){let{segment:d}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(u,this.isLive);l?.byteLength&&(d.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let d of this.activeSegments){let{segment:u}=d;if(d.representationId!==t)continue;if(a.aborted){s();continue}let l=u.byte.from-i,c=u.byte.to-i,p=c-l+1,h=l<r,m=c<=r;if(h){if(u.status==="downloading"&&m){u.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+l,p);this.sourceBufferTaskQueue.append(v,a).then(f=>f&&!a.aborted?this.onSegmentFullyAppended(d,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.loadedBytes=Math.min(p,r-l),d.loadedBytes>d.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+l+d.feedingBytes,d.loadedBytes-d.feedingBytes),f=d.loadedBytes===p?v:this.containerParser.parseFeedableSegmentChunk(v);f?.byteLength&&(u.status="partially_fed",d.feedingBytes+=f.byteLength,this.sourceBufferTaskQueue.append(f,a).then(g=>{if(a.aborted)s();else if(g)d.fedBytes+=f.byteLength,d.fedBytes===p&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<p)return;s()}}))}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ui(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&r.time.from===e.segment.time.from&&r.time.to===e.segment.time.to&&(r.status="none");this.isActiveLowLatency()&&this.updateLowLatencyLive(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 i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let s=a instanceof Promise;t||=s,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=(!i&&this.failedDownloads>0?ft(this.destroyAbortController.signal,async function*(){let o=Jr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{if(!o)return;let{init:d,dataView:u,segments:l}=o,c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,c);let p=l;this.isLive&&tt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:bt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||xe(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=o=>{let d=!0;for(let l of r)Math.round(l.from)===Math.round(o.time.to)?(l.from=o.time.from,d=!1):Math.round(l.to)===Math.round(o.time.from)&&(l.to=o.time.to,d=!1);d&&r.push(o.time);let u=Ui(o)?o.size??0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let d of o){if(a>=t)break;let u=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(u||l)&&d.status==="fed"&&s(d)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let d=this.sourceBuffer.buffered.start(o)*1e3,u=this.sourceBuffer.buffered.end(o)*1e3;for(let l of this.segments.values())for(let c of l)if(c.status==="none"&&Math.round(c.time.from)<=Math.round(d)&&Math.round(c.time.to)>=Math.round(u)){r.push({from:d,to:u});break}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let u of d)u.time.from>=e+o&&u.status==="fed"&&s(u)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,u)=>d||u,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||xe(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,o=!1,d=u=>{a=Math.min(a,u.time.from),s=Math.max(s,u.time.to);let l=Ui(u)?u.size??0:u.byte.to-u.byte.from;r+=l};for(let u of this.segments.values())for(let l of u){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status==="fed"&&d(l)}if(o=isFinite(a)&&isFinite(s),!o){r=0,a=1/0,s=-1/0;for(let u of this.segments.values())for(let l of u){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status==="fed"&&d(l)}}if(o=isFinite(a)&&isFinite(s),!o)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;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)){a=l,s=c;break}}if(o=isFinite(a)&&isFinite(s),!o&&i){r=0,a=1/0,s=-1/0;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"&&d(c)}return o=isFinite(a)&&isFinite(s),o?this.sourceBufferTaskQueue.remove(a,s):!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 i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:bt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(xe(this.sourceBuffer)||xe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=1;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let s=Math.floor(r.time.from),o=Math.ceil(r.time.to),d=e.some(l=>l.from-t<=s&&l.to+t>=o),u=e.filter(l=>s>=l.from-t&&s<=l.to+t||o>=l.from-t&&o<=l.to+t);d||(u.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var si=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var Cs=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ni,assertNever as Bs,fromEvent as Vs,merge as Fu,now as Xr,Subscription as Uu,ValueSubject as Zr}from"@vkontakte/videoplayer-shared";var Hi=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new Zr(void 0);this.lastConnectionReused$=new Zr(void 0);this.lastRequestFirstBytes$=new Zr(void 0);this.abortAllController=new AbortController;this.subscription=new Uu;this.fetchManifest=ni(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=si(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(oi);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));this.fetch=ni(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:d=!1}={}){let u=e,l=new Headers;if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let A=new URL(u,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),u=A.toString();break}default:Bs(t)}this.requestQuic&&(u=si(u));let c=this.abortAllController.signal,p;if(s){let A=new AbortController;if(p=Fu(Vs(this.abortAllController.signal,"abort"),Vs(s,"abort")).subscribe(()=>{try{A.abort()}catch(w){oi(w)}}),this.abortAllController.signal.aborted||s.aborted)try{A.abort()}catch(w){oi(w)}c=A.signal}let h=Xr(),m=yield fetch(u,{priority:a,headers:l,signal:c}).catch(oi),v=Xr();if(!m)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-h),!m.ok||!m.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!r&&!o)return p?.unsubscribe(),m.arrayBuffer();let[f,g]=m.body.tee(),S=f.getReader();o&&this.throughputEstimator?.trackStream(g,d);let _=0,b=new Uint8Array(0),I=!1,B=A=>{p?.unsubscribe(),I=!0,oi(A)},V=ni(c,async function*({done:A,value:w}){if(_===0&&this.lastRequestFirstBytes$.next(Xr()-h),c.aborted){p?.unsubscribe();return}if(!A&&w){let T=new Uint8Array(b.length+w.length);T.set(b),T.set(w,b.length),b=T,_+=w.byteLength,r?.(new DataView(b.buffer),_),yield S?.read().then(V,B)}}.bind(this));return yield S?.read().then(V,B),p?.unsubscribe(),I?null:b.buffer}.bind(this));this.fetchByteRangeRepresentation=ni(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,d=!1,u,l;e.indexRange&&(u=e.indexRange.from,l=e.indexRange.to,d=a+1===u,d&&(s=Math.min(u,r),o=Math.max(l,a))),s=Math.min(s,0);let c=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let v;if(d)v=new DataView(c,m.from-s,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;v=new DataView(g)}let f=t.parseSegments(v,h,m);return{init:h,dataView:new DataView(c),segments:f}}.bind(this));this.fetchTemplateRepresentation=ni(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(s=>({...s,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){let{type:t,reused:i}=Cs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Bs(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},oi=n=>{if(!ii(n))throw n};var it=(n,e,t)=>t*e+(1-t)*n,ea=(n,e)=>n.reduce((t,i)=>t+i,0)/e,Os=(n,e,t,i)=>{let r=0,a=t,s=ea(n,e),o=e<i?e:i;for(let d=0;d<o;d++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};import{isNullable as Hu,ValueSubject as _s}from"@vkontakte/videoplayer-shared";var Ge=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new _s(e.initial),this.debounced$=new _s(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Y(`raw_${t}`),this.smoothedSeries$=new Y(`smoothed_${t}`),this.reportedSeries$=new Y(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&(Hu(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 Gi=class extends Ge{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=it(this.slow,t,this.params.emaAlphaSlow),this.fast=it(this.fast,t,this.params.emaAlphaFast);let i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast)}};var Qi=class extends Ge{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let i=ea(this.pastMeasures,this.takenMeasures);this.emaSmoothed=it(this.emaSmoothed,t,this.params.emaAlpha);let r=Os(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:i}};var ji=class extends Ge{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?it(this.smoothed,t,this.params.emaAlpha):t}};var rt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Gi({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Qi({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ji({initial:e,label:"liveEdgeDelay",...t})}};var ta=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};var Re=()=>window.ManagedMediaSource||window.MediaSource,Wi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Ns=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Fs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Ws=["timeupdate","progress","play","seeked","stalled","waiting"];var zi=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new js;this.representationSubscription=new js;this.state$=new $("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Qs;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.isLive$=new ee(!1);this.liveDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.timeInWaiting=0;this.isActiveLowLatency$=new ee(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Qs;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=ia(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=W(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Qe.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=ia(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(r=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Qe.NETWORK,message:"Failed to load manifest",thrown:r})});if(!e)return null;let t;try{t=ws(e??"",this.manifestUrlString)}catch(r){this.error$.next({id:"ManifestParsing",category:Qe.PARSER,message:"Failed to parse MPD manifest",thrown:r})}if(!t)return null;let i=({kind:r,mime:a,codecs:s})=>!!(this.element?.canPlayType?.(a)&&Re()?.isTypeSupported?.(`${a}; codecs="${s}"`)||r==="text");return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([r,a])=>[r,a.filter(i)]))}}.bind(this));this.initRepresentations=ia(this.destroyController.signal,async function*(e,t,i){at(this.manifest),at(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add(gt(h,"error").pipe(qi(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:Qe.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Fs():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Wi())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest};if(this.videoBufferManager=new ai("video",this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],Gs(t)&&(this.audioBufferManager=new ai("audio",this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),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(ra(1e3).subscribe(h=>{if(this.element?.paused){let m=wr(this.manifestUrlString,2);this.manifestUrlString=W(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add(St(...Ws.filter(h=>h!=="waiting").map(h=>gt(this.element,h))).pipe(aa(h=>this.element?Le(this.element.buffered,this.element.currentTime*1e3):0),Hs(),qi(h=>!!h),Qu(h=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Hs()).subscribe(m=>ta(this.element,1))),this.representationSubscription.add(Yi({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(qi(({bufferLength:m,isActiveLowLatency:v})=>v&&!!m)).subscribe(({bufferLength:m})=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add(Yi({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:m,isActiveLowLatency:v})=>{if(!v)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,_=m-f,b=1;Math.abs(_)>g&&(b=1+Math.sign(_)*S),ta(this.element,b)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let v=0;if(m){let f=(this.element?.currentTime??0)*1e3;v=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==v&&this.liveLoadBufferLength$.next(v)}));let h=0;this.representationSubscription.add(Yi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ju(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:v})=>{if(at(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,g=wr(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,_=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),b=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,B=isFinite(m)?m:v,V=this.isActiveLowLatency$.getValue(),A=S<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(V&&A);let w="none";if(V?w="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&A?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(T=>T.proceedLowLatencyLive()),w="active_low_latency"):g!==0&&B<_?w="live_forward_buffering":B<_+I&&(w="live_with_target_offset"),isFinite(m)&&(h=m>h?m:h),w==="live_forward_buffering"||w==="live_with_target_offset"){let T=h-(_+b),x=this.normolizeLiveOffset(Math.trunc(g+T/f)),P=Math.abs(x-g),O;!m||P<=this.tuning.dashCmafLive.offsetCalculationError?O=g:x>0&&P>this.tuning.dashCmafLive.offsetCalculationError?O=x:O=0,this.manifestUrlString=W(this.manifestUrlString,O,2)}w!=="none"&&w!=="active_low_latency"&&(h=0,this.updateLive())}))}let o=St(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(aa(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=St(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(aa(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add(St(this.forceEnded$,Yi({allBuffersFull:o,someBufferEnded:d}).pipe(qi(({allBuffersFull:h,someBufferEnded:m})=>h&&m))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{this.source?.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Qe.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(St(...this.bufferManagers.map(h=>h.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.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(h=>this.source?.addEventListener("sourceopen",h)));let u=this.manifest.duration??0,l=(h,m)=>Math.max(h,m.duration??0),c=this.manifest.representations.audio.reduce(l,u),p=this.manifest.representations.video.reduce(l,u);(c||p)&&(this.source.duration=Math.max(c,p)/1e3),this.audioBufferManager&&Gs(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=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ra(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Qe.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Hi({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=rt.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){at(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=W(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initBuffer(){at(this.element),this.state$.setState("running"),this.subscription.add(St(...Ws.map(e=>gt(this.element,e)),gt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Qe.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(gt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(gt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Bt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=5e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=ra(5e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Qe.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t)}seek(e,t){at(this.element),at(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Bt(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,i=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let a of this.bufferManagers)for(let s of a.gaps)a.playingRepresentation$.getValue()===s.representation&&s.from-r<=t&&s.to+r>t&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?i.push(1/0):i.push(s.to));if(i.length){let a=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,a===1/0?this.forceEnded$.next():this.element.currentTime=a/1e3}}};var Ki=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ji=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,s=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:s},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Ys=`attribute vec2 a_vertex;
38
38
  attribute vec2 a_texel;
39
39
 
40
40
  varying vec2 v_texel;
@@ -45,7 +45,7 @@ void main(void) {
45
45
  // save texel vector to pass to fragment shader
46
46
  v_texel = a_texel;
47
47
  }
48
- `;var fb=`#ifdef GL_ES
48
+ `;var qs=`#ifdef GL_ES
49
49
  precision highp float;
50
50
  precision highp int;
51
51
  #else
@@ -88,5 +88,5 @@ void main(void) {
88
88
  // sample using new coordinates
89
89
  gl_FragColor = texture2D(u_texture, tc);
90
90
  }
91
- `;var os=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new ss(this.params.fov,this.params.orientation),this.cameraRotationManager=new ns(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(hb,this.gl.VERTEX_SHADER),r=this.createShader(fb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,l=t-a,u=e+r,d=t+a,c=e-r,p=t+a;return[s,n,o,l,u,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var _t=class{constructor(e){this.subscription=new wA;this.videoState=new R("stopped");this.elementSize$=new RA(void 0);this.textTracksManager=new ge;this.droppedFramesManager=new Ga;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new qa;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(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"),I(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return gA(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new os(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=re(e.container),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(G(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new as({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=se(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:ou.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,l)=>this.subscription.add(o.subscribe(l,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(mb(u=>!!u.length),Sb()).subscribe(u=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:u})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(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(mb(EA),Sb()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Ve(this.video,t.isLooped,a)),this.subscription.add(ae(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(ve(this.video,t.playbackRate,r.playbackRateState$,a)),s(AA(this.video),this.elementSize$),s(Te(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(yA(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push({id:h.id,language:h.language,label:h.label});let m=[];for(let S of h.representations){let v=Xm(S);m.push(v),this.audioTracksMap.set(v,{stream:h,representation:S})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of d.video){c.push({id:p.id,language:p.language,hdr:p.hdr,label:p.label});let h=[];for(let m of p.representations){let S=Jm(m);S&&(h.push(S),this.videoTracksMap.set(S,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(c);for(let p of d.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 u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:ou.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(us(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$,IA(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[p,h]=c,m=this.params.desiredState.autoVideoTrackLimits.getTransition();m&&this.params.output.autoVideoTrackLimits$.next(m.to),u==="manifest_ready"?this.player.initRepresentations(p.id,h.id,this.params.sourceHls):(this.player.switchRepresentation("video",p.id).catch(n),this.player.switchRepresentation("audio",h.id).catch(n))},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(uu()).subscribe(u=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:c}])=>c.id===u);if(d){let[c,{stream:p}]=d;e.currentVideoTrack$.next(c),e.currentVideoStream$.next(p)}else e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0)},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(uu()).subscribe(u=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:c}])=>c.id===u);if(d){let[,{stream:c}]=d;e.currentAudioStream$.next(c)}else e.currentAudioStream$.next(void 0)},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(PA(({to:u})=>u==="ready"),uu());this.subscription.add(us(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(us(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=us(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,kA(["init"])).pipe(TA(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:P})=>P===a),o=t.currentVideoTrack$.getValue(),l=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let u=[...this.videoStreamsMap.keys()].find(({id:P})=>P===l.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let c=nt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:P})=>P===m?.id),v=0;if(S){if(n&&!r){let P=Xa(n,d,this.audioStreamsMap.get(S)??[]);v=Math.max(v,P?.bitrate??-1/0)}if(o){let P=Xa(o,d,this.audioStreamsMap.get(S)??[]);v=Math.max(v,P?.bitrate??-1/0)}}let g=st(d,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:k}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(g=d.filter(P=>!xA(P.quality)).sort((P,w)=>(w.bitrate??0)-(P.bitrate??0)).filter(P=>bb(P.quality,g.quality)&&bb(P.quality,k))[0]??g);let A=r?g??n:n??g,b=S&&Xa(A,d,this.audioStreamsMap.get(S)??[]),T=this.videoTracksMap.get(A)?.representation,M=b&&this.audioTracksMap.get(b)?.representation;if(T&&M)return[T,M]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ne(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ou.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),ie(this.video)}};var Li=class extends _t{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)}};import{combine as vb,interval as $A,map as LA}from"@vkontakte/videoplayer-shared";var Ci=class extends _t{constructor(e){super(e),this.liveOffset=new He}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(vb({interval:$A(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let s=e.position$.getValue()+(a-1);e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add(vb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(LA(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var yb=_e(Ba(),1);import{assertNever as Mi,assertNonNullable as gb,debounce as CA,ErrorCategory as ls,filter as MA,isNonNullable as DA,isNullable as OA,map as lu,merge as VA,Observable as BA,observableFrom as _A,Subscription as NA,videoSizeToQuality as FA}from"@vkontakte/videoplayer-shared";var Le={};var gr=(i,e)=>new BA(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Di=class{constructor(e){this.subscription=new NA;this.videoState=new R("initializing");this.textTracksManager=new ge;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Mi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Mi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Mi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Mi(e)}break;default:Mi(t)}};this.video=re(e.container),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(G(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),ie(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:ls.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,yb.default)(import("hls.js").then(a=>{e||(Le.Hls=a.default,Le.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){gb(Le.Hls,"hls.js not loaded"),this.hls=new Le.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){gb(Le.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:ls.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=se(this.video),s=(u,d)=>this.subscription.add(u.subscribe(d,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Ve(this.video,e.isLooped,r)),this.subscription.add(ae(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ve(this.video,e.playbackRate,a.playbackRateState$,r)),s(Te(this.video),t.elementVisible$),this.subscription.add(gr(this.hls,Le.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:ls.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(gr(this.hls,Le.Events.MANIFEST_PARSED).pipe(lu(({levels:u})=>u.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:h,height:m}=c,S=it(c.attrs.QUALITY??"")??FA({width:h,height:m});if(!S)return d;let v=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,g={id:p.toString(),quality:S,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:v};return this.trackLevels.set(p,{track:g,level:c}),d.push(g),d},[]))),t.availableVideoTracks$),s(gr(this.hls,Le.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let d=[];for(let c of u.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang,S="internal";d.push({id:p,url:h,language:m,type:S})}e.internalTextTracks.startTransitionTo(d)}}),s(gr(this.hls,Le.Events.LEVEL_LOADING).pipe(lu(({url:u})=>G(u))),t.hostname$),s(gr(this.hls,Le.Events.FRAG_CHANGED),u=>{let{video:d,audio:c}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(et(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:d})=>d===u)?.track,o=gr(this.hls,Le.Events.LEVEL_SWITCHED).pipe(lu(({level:u})=>n(this.hls.levels[u])));o.pipe(MA(DA)).subscribe(t.currentVideoTrack$,r),this.subscription.add(et(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(OA(u))return;let d=this.trackLevels.get(u.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=VA(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_A(["init"])).pipe(CA(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ne(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ls.DOM,thrown:t}))||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("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"),I(this.params.desiredState.playbackState,"stopped",!0)}};var Tb="X-Playback-Duration",cu=async i=>{let e=await Ge(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(Tb)?parseInt(e.headers.get(Tb),10):void 0};import{assertNever as YA,combine as WA,debounce as QA,ErrorCategory as ds,filter as zA,filterChanged as KA,isNonNullable as Eb,isNullable as ps,map as xb,merge as JA,observableFrom as XA,Subscription as ZA,ValueSubject as hu,VideoQuality as ew}from"@vkontakte/videoplayer-shared";var pu=_e(Dn(),1);import{videoSizeToQuality as qA,getExponentialDelay as UA}from"@vkontakte/videoplayer-shared";var HA=i=>{let e=null;if(i.QUALITY&&(e=it(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=qA({width:t,height:r})}return e??null},jA=(i,e)=>{let t=i.split(`
92
- `),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),l=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!l)){if(o){let u=(0,pu.default)(o[1].split(",").map(v=>v.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,c=HA(u),p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[v,g]=u.RESOLUTION.split("x").map(k=>parseInt(k,10));v&&g&&(m={width:v,height:g})}let S=new URL(t[++s],e).toString();c&&r.push({id:d,quality:c,url:S,bandwidth:p,size:m,fps:h})}if(l){let u=(0,pu.default)(l[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),d=u.URI?.replace(/playlist$/,"subtitles.vtt"),c=u.LANGUAGE,p=u.NAME;d&&c&&a.push({type:"internal",id:c,label:p,language:c,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},GA=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),du=0,Ib=async(i,e=i,t)=>{let a=await(await Ge(i)).text();du+=1;try{let{qualityManifests:s,textTracks:n}=jA(a,e);return{qualityManifests:s,textTracks:n}}catch{if(du<=t.manifestRetryMaxCount)return await GA(UA(du-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ib(i,e,t)}return{qualityManifests:[],textTracks:[]}},cs=Ib;var Oi=class{constructor(e){this.subscription=new ZA;this.videoState=new R("stopped");this.textTracksManager=new ge;this.manifests$=new hu([]);this.liveOffset=new He;this.manifestStartTime$=new hu(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(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.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to==="paused"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return YA(t)}};this.params=e,this.video=re(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ew.INVARIANT,url:this.params.source.url},cs(z(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ds.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:ds.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.maxSeekBackTime$=new hu(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:ds.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ae(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),s(Te(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(KA(),xb(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&Eb(u.to)){let c=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(WA({startTime:this.manifestStartTime$.pipe(zA(Eb)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe(xb(o=>o.map(({id:l,quality:u,size:d,bandwidth:c,fps:p})=>({id:l,quality:u,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r));let n=JA(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,XA(["init"])).pipe(QA(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ie(this.video)}prepare(){let e=this.selectManifest();if(ps(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:l}=t?.to??r??{};for(let[u,d]of[[o,"mq"],[l,"lq"]]){let c=String(parseFloat(u||""));d&&u&&a.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=z(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),cu(n).then(o=>{if(!ps(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(ps(l)||!isFinite(l))try{Ge(n).then(u=>u.text()).then(u=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(d){let c=new URL(d,n).toString();cu(c).then(p=>{ps(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){ne(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ds.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()}};import{assertNever as tw,debounce as rw,ErrorCategory as fu,fromEvent as mu,isNonNullable as iw,isNullable as aw,map as sw,merge as Pb,observableFrom as kb,Subscription as nw,ValueSubject as ow,VideoQuality as uw,isIOS as lw}from"@vkontakte/videoplayer-shared";var Vi=class{constructor(e){this.subscription=new nw;this.videoState=new R("stopped");this.textTracksManager=new ge;this.manifests$=new ow([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return tw(t)}};this.params=e,this.video=re(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:uw.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(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),cs(z(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:fu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:fu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Ve(this.video,t.isLooped,r)),this.subscription.add(ae(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&iw(u.to)){let c=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===c);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(h),S.playbackRate=h)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(sw(o=>o.map(({id:l,quality:u,size:d,bandwidth:c,fps:p})=>({id:l,quality:u,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r)),!lw()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Pb(mu(o,"addtrack"),mu(o,"removetrack"),mu(o,"change"),kb(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=Pb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,kb(["init"])).pipe(rw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ie(this.video)}prepare(){let e=this.selectManifest();if(aw(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,l]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));l&&o&&a.searchParams.set(l,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ne(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as cw,assertNonNullable as Ab,debounce as dw,ErrorCategory as wb,isHigher as pw,isHigherOrEqual as hw,isInvariantQuality as Rb,isLowerOrEqual as fw,isNonNullable as mw,merge as bw,observableFrom as Sw,Subscription as vw}from"@vkontakte/videoplayer-shared";var Bi=class{constructor(e){this.subscription=new vw;this.videoState=new R("stopped");this.trackUrls={};this.textTracksManager=new ge;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:l}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?I(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return cw(e)}};this.params=e,this.video=re(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:wb.WTF,message:"MpegProvider internal logic error",thrown:o})},a=se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Ve(this.video,t.isLooped,r)),this.subscription.add(ae(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),s(Te(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&mw(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(l!==u){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(l),d.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=bw(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Sw(["init"])).pipe(dw(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),ie(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Ab(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Ab(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=wi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(G(t))}playIfAllowed(){ne(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wb.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!Rb(o.track.quality)&&fw(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&hw(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!Rb(u.track.quality)&&pw(u.track.quality,e)),l=o.length;l&&(t=o[l-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=st(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Lb,debounce as Iw,merge as Cb,observableFrom as Ew,Subscription as xw,map as Mb,ValueSubject as Pw,ErrorCategory as Su,VideoQuality as kw}from"@vkontakte/videoplayer-shared";import{ErrorCategory as gw}from"@vkontakte/videoplayer-shared";var $b=["stun:videostun.mycdn.me:80"],yw=1e3,Tw=3,bu=()=>null,hs=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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:$b}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:gw.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),yw)}normalizeOptions(e={}){let t={stunServerList:$b,maxRetryNumber:Tw,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var _i=class{constructor(e){this.videoState=new R("stopped");this.maxSeekBackTime$=new Pw(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"),I(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"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Lb(e)}};this.subscription=new xw,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=re(e.container),this.liveStreamClient=new hs(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),ie(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Su.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Cb(this.videoState.stateChangeStarted$.pipe(Mb(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Mb(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=se(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Te(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ae(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Lb(n.to)}},r)).add(Cb(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ew(["init"])).pipe(Iw(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(G(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:kw.INVARIANT}),this.video.srcObject=e,I(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:Su.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ne(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Su.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ni=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Fi,assertNonNullable as lt,ErrorCategory as fs,filter as $w,isNonNullable as Vb,isNullable as Lw,map as Cw,merge as Mw,once as Dw,Subject as Ce,Subscription as Bb,ValueSubject as L}from"@vkontakte/videoplayer-shared";import{Observable as Aw,map as Db,Subscription as ww,Subject as Rw}from"@vkontakte/videoplayer-shared";var Ob=i=>new Aw(e=>{let t=new ww,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Db(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Db(({type:u})=>u!==void 0)),n=new Rw,o=0,l="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),l=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Ow={chunkDuration:5e3,maxParallelRequests:5},qi=class{constructor(e){this.current$=new L({type:void 0});this.providerError$=new Ce;this.noAvailableProvidersError$=new Ce;this.providerOutput={position$:new L(0),duration$:new L(1/0),volume$:new L({muted:!1,volume:1}),availableVideoStreams$:new L([]),currentVideoStream$:new L(void 0),availableVideoTracks$:new L([]),currentVideoTrack$:new L(void 0),availableAudioStreams$:new L([]),currentAudioStream$:new L(void 0),availableAudioTracks$:new L([]),currentVideoSegmentLength$:new L(0),currentAudioSegmentLength$:new L(0),isAudioAvailable$:new L(!0),autoVideoTrackLimitingAvailable$:new L(!1),autoVideoTrackLimits$:new L(void 0),currentBuffer$:new L(void 0),isBuffering$:new L(!0),error$:new Ce,warning$:new Ce,willSeekEvent$:new Ce,seekedEvent$:new Ce,loopedEvent$:new Ce,endedEvent$:new Ce,firstBytesEvent$:new Ce,firstFrameEvent$:new Ce,canplay$:new Ce,isLive$:new L(void 0),isLowLatency$:new L(!1),canChangePlaybackSpeed$:new L(!0),liveTime$:new L(void 0),liveBufferTime$:new L(void 0),availableTextTracks$:new L([]),currentTextTrack$:new L(void 0),hostname$:new L(void 0),httpConnectionType$:new L(void 0),httpConnectionReused$:new L(void 0),inPiP$:new L(!1),inFullscreen$:new L(!1),element$:new L(void 0),elementVisible$:new L(!0),availableSources$:new L(void 0),is3DVideo$:new L(!1)};this.subscription=new Bb;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=sm([...om(this.params.tuning),...nm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>Vb(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new Ni(s);let n=[...No(!0),...No(!1)];this.chromecastFormatsIterator=new Ni(n.filter(o=>Vb(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}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()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Lw(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:fs.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.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(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Fi(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return lt(o),new Li({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return lt(o),new Ci({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return lt(o),cr||!this.params.tuning.useHlsJs?new Vi({...n,source:o}):new Di({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return lt(o),new Oi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return lt(o),new Bi({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return lt(o),new Jf({...n,source:o,config:{...Ow,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return lt(o),new _i({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Fi(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return lt(o),new Hr({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Fi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Fi(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 Fi(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,_b.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Bb,t=!1,r=0;return e.add(Mw(this.providerOutput.error$,Ob({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Cw(a=>({id:`ProviderHangup:${a}`,category:fs.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe($w(({to:s})=>s==="playing"),Dw()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{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=a.category===fs.NETWORK,o=a.category===fs.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=r<this.params.tuning.providerErrorLimit&&!o;l&&!o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}})),e}};import{fromEvent as ms,once as Vw,combine as Bw,Subscription as Nb,ValueSubject as vu,map as _w,filter as Nw,isNonNullable as bs,now as fe,safeStorage as gu}from"@vkontakte/videoplayer-shared";var Fw=5e3,Fb="one_video_throughput",qb="one_video_rtt",Ui=window.navigator.connection,Ub=()=>{let i=Ui?.downlink;if(bs(i)&&i!==10)return i*1e3},Hb=()=>{let i=Ui?.rtt;if(bs(i)&&i!==3e3)return i},jb=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},yu=class i{constructor(e){this.subscription=new Nb;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Fb)||(e.useBrowserEstimation?Ub():void 0)||Fw,r=i.load(qb)??(e.useBrowserEstimation?Hb():void 0)??0;if(this.throughput$=new vu(t),this.rtt$=new vu(r),this.rttAdjustedThroughput$=new vu(jb(t,r,e.rttPenaltyRequestSize)),this.throughput=Ot.getSmoothedValue(t,-1,e),this.rtt=Ot.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Ub();n&&this.throughput.next(n);let o=Hb();bs(o)&&this.rtt.next(o)};Ui&&"onchange"in Ui&&this.subscription.add(ms(Ui,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{gu.set(Fb,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{gu.set(qb,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Bw({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_w(({throughput:a,rtt:s})=>jb(a,s,e.rttPenaltyRequestSize)),Nw(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=fe(),a=new Nb;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(ms(e,"progress").pipe(Vw()).subscribe(s=>{t=s.loaded,r=fe()}));break;case 1:case 0:a.add(ms(e,"loadstart").subscribe(()=>{t=0,r=fe()}));break}a.add(ms(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=fe(),l=n-t,u=o-r;this.addRawSpeed(l,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=fe(),n=0,o=fe(),l=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(a,fe()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(fe()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=c.byteLength,s=fe()}o=fe()}else a+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&fe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,fe()-o,this.concurrentDownloads.size),n=0,o=fe());await r?.read().then(u,l)}};this.concurrentDownloads.add(e),r?.read().then(u,l)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=gu.get(e);if(bs(t))return parseInt(t,10)??void 0}},Gb=yu;import{fillWithDefault as qw,VideoQuality as Yb}from"@vkontakte/videoplayer-shared";var Wb={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:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Yb.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Yb.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:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:200,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:!0,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:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Qb=i=>({...qw(i,Wb),configName:[...i.configName??[],...Wb.configName]});import{assertNonNullable as Ss,combine as vs,ErrorCategory as gs,filter as Hi,filterChanged as Ie,fromEvent as Iu,isNonNullable as Qw,isNullable as zw,Logger as Kw,map as C,mapTo as Xb,merge as ct,now as ys,once as Ke,Subject as N,Subscription as Zb,tap as eS,ValueSubject as E,isHigher as Jw,isInvariantQuality as tS}from"@vkontakte/videoplayer-shared";import{merge as Uw,map as Hw,filter as zb,isNonNullable as jw}from"@vkontakte/videoplayer-shared";var Tu=({seekState:i,position$:e})=>Uw(i.stateChangeEnded$.pipe(Hw(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),zb(jw)),e.pipe(zb(()=>i.getState().state==="none")));import{assertNonNullable as Gw}from"@vkontakte/videoplayer-shared";var Kb=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return Gw(e,`Wrong container or containerId {${i.container}}`),e};import{filter as Yw,once as Ww}from"@vkontakte/videoplayer-shared";var Jb=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Yw(a=>a.length>0),Ww()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Ts=class{constructor(e={configName:[]}){this.subscription=new Zb;this.logger=new Kw;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new R("stopped"),seekState:new R({state:"none"}),volume:new R({volume:1,muted:!1}),videoTrack:new R(void 0),videoStream:new R(void 0),audioStream:new R(void 0),autoVideoTrackSwitching:new R(!0),autoVideoTrackLimits:new R({}),isLooped:new R(!1),playbackRate:new R(1),externalTextTracks:new R([]),internalTextTracks:new R([]),currentTextTrack:new R(void 0),textTrackCuesSettings:new R({}),cameraOrientation:new R({x:0,y:0})};this.info={playbackState$:new E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(0)};this.events={inited$:new N,ready$:new N,started$:new N,playing$:new N,paused$:new N,stopped$:new N,willStart$:new N,willResume$:new N,willPause$:new N,willStop$:new N,willDestruct$:new N,watchCoverageRecord$:new N,watchCoverageLive$:new N,managedError$:new N,fatalError$:new N,ended$:new N,looped$:new N,seeked$:new N,willSeek$:new N,firstBytes$:new N,firstFrame$:new N,canplay$:new N,log$:new N};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:Bf};if(this.initLogs(),this.tuning=Qb(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ji({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Gb(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,a)=>{let s=Reflect.get(t,r,a);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let l=n.map(c=>JSON.stringify(c,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),u=`Player.${String(r)}`,d=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:gs.WTF,message:d,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Kb(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new qi({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.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&&!Xr()?Iu(document,"visibilitychange").pipe(Ke()).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(),a=this.info.isLive$.getValue();return e>=r&&!a&&(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){Ss(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(Hi(r=>r.length>0),Ke()).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){Ss(this.providerContainer);let t=this.providerContainer?.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){return Jb(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.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 a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(zw(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return Qw(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Hi(({from:e})=>e==="stopped"),Ke()).subscribe(()=>{this.initedAt=ys(),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({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:gs.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(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),Ie()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,l)=>tS(o)?1:tS(l)?-1:Jw(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let l of n)l.fps&&(o[l.quality]=l.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Ie()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Ie()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Ie()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(C(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(vs({hasLiveOffsetByPaused:ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),Ie(),C(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(vs({atLiveEdge:vs({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Tu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),Ie(),eS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(vs({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Ie(),eS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),Ie()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),Ie()).subscribe(this.info.volume$)).add(Tu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ct(e.providerOutput.endedEvent$.pipe(Xb(!0)),e.providerOutput.seekedEvent$.pipe(Xb(!1))).pipe(Ie()).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.noAvailableProvidersError$.pipe(C(n=>({id:n?`No${n}`:"NoProviders",category:gs.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(Ke(),C(n=>n??ys()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ke(),C(()=>ys()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ke(),C(()=>ys()-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 E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new E(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Hi(({to:n})=>n==="playing"),Ke()).subscribe(()=>r.next(!1)));let a=0,s=ct(e.providerOutput.isBuffering$,t,r).pipe(C(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),Ie());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(ct(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ct(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":l?u?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Zb;this.subscription.add(t),this.subscription.add(e.current$.pipe(Ie((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Hi(r=>r.length>0),Ke()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=st(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(ct(this.desiredState.videoTrack.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(C(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Ss(this.providerContainer),Ss(e),Vf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Of(t)),this.providerContainer.current$.subscribe(({type:t})=>Wr("provider",t)),e.duration$.subscribe(t=>Wr("duration",t)),e.availableVideoTracks$.pipe(Hi(t=>!!t.length),Ke()).subscribe(t=>Wr("tracks",t)),this.events.fatalError$.subscribe(new X("fatalError")),this.events.managedError$.subscribe(new X("managedError")),e.position$.subscribe(new X("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new X("quality")),this.info.currentBuffer$.subscribe(new X("buffer")),e.isBuffering$.subscribe(new X("isBuffering"))].forEach(t=>this.subscription.add(t)),Wr("codecs",am())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:gs.DOM,message:String(a)})})};this.subscription.add(ct(Iu(document,"visibilitychange"),Iu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as dH,Observable as pH,Subject as hH,ValueSubject as fH,VideoQuality as mH}from"@vkontakte/videoplayer-shared";var bH=`@vkontakte/videoplayer-core@${Pu}`;export{zi as ChromecastState,Rs as HttpConnectionType,pH as Observable,de as PlaybackState,Ts as Player,bH as SDK_VERSION,hH as Subject,dH as Subscription,$s as Surface,Pu as VERSION,fH as ValueSubject,bt as VideoFormat,mH as VideoQuality};
91
+ `;var Xi=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Ki(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ji(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Ys,this.gl.VERTEX_SHADER),i=this.createShader(qs,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,d=t-r,u=e+i,l=t+r,c=e-i,p=t+r;return[a,s,o,d,u,l,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var st=class{constructor(e){this.subscription=new ad;this.videoState=new $("stopped");this.elementSize$=new Zs(void 0);this.textTracksManager=new oe;this.droppedFramesManager=new Ni;this.videoTracks$=new Zs([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new Bi;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let s=this.liveOffset?.getTotalPausedTime()??0;this.seek(r.position-s,r.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"),y(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"),y(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&y(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Ku(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Xi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=z(e.container),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(G(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new zi({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=X(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:sa.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,d)=>this.subscription.add(o.subscribe(d,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(Zi(u=>u.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Xu(ed),rd()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(Zi(u=>u.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Te(this.video,t.isLooped,r)),this.subscription.add(J(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ne(this.video,t.playbackRate,i.playbackRateState$,r)),a(id(this.video),this.elementSize$),a(de(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){let l=[];this.audioTracks=[],this.textTracks=[];let c=this.player.getRepresentations();zs(c,"Manifest not loaded or empty");let p=Array.from(c.audio).sort((f,g)=>g.bitrate-f.bitrate),h=Array.from(c.video).sort((f,g)=>g.bitrate-f.bitrate),m=Array.from(c.text);if(!this.params.tuning.isAudioDisabled)for(let f of p){let g=Ls(f);g&&this.audioTracks.push({track:g,representation:f})}for(let f of h){let g=$s(f);if(g){l.push({track:g,representation:f});let S=!this.params.tuning.isAudioDisabled&&Rs(p,h,f);S&&this.audioRepresentations.set(f.id,S)}}this.videoTracks$.next(l);for(let f of m){let g=Ms(f);g&&this.textTracks.push({track:g,representation:f})}this.params.output.availableVideoTracks$.next(l.map(({track:f})=>f)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:f})=>f)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:f})=>f));let v=this.selectVideoRepresentation();zs(v),this.player.initRepresentations(v.id,this.audioRepresentations.get(v.id)?.id,this.params.sourceHls)}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=u=>e.error$.next({id:"RepresentationSwitch",category:sa.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(er(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Zu(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),l=this.player.state$.getTransition();if(u!=="running"||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);let h=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let v=c.id;!this.params.output.elementVisible$.getValue()&&h&&(v=this.videoTracks$.getValue().map(g=>g.representation).sort((g,S)=>S.bitrate-g.bitrate).filter(g=>{let S=Xs(g),_=Xs(c);if(S&&_)return Js(S,_)&&Js(S,m)}).map(g=>g.id)[0]),this.player.switchRepresentation("video",v).catch(s);let f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation("audio",f.id).catch(s)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ks(),Zi(u=>u&&this.videoTracks$.getValue().find(({representation:{id:l}})=>l===u)?.track)).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Zi(({to:u})=>u==="ready"),Ks());this.subscription.add(er(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(er(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=er(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,td(["init"])).pipe(Ju(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:c}})=>c===t)?.track,r=this.params.output.currentVideoTrack$.getValue(),a=Le(this.video.buffered,this.video.currentTime*1e3),s=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(s,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,r?this.audioRepresentations.get(r.id)?.bitrate??0:0),u=He(this.videoTracks$.getValue().map(({track:c})=>c),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:o,current:r,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),l=e?u??i:i??u;return l&&this.videoTracks$.getValue().find(({track:c})=>c===l)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Z(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sa.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),K(this.video)}};var di=class extends st{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as en,interval as sd,map as nd}from"@vkontakte/videoplayer-shared";var li=class extends st{constructor(e){super(e),this.liveOffset=new we}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(en({interval:sd(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{if(this.videoState.getState()==="playing"){let a=e.position$.getValue()+(r-1);a<=0&&e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(en({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(nd(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(s).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(s,r)})}};import{assertNever as ci,assertNonNullable as tn,debounce as od,ErrorCategory as tr,filter as ud,isNonNullable as dd,isNullable as ld,map as ir,merge as cd,Observable as pd,observableFrom as hd,Subscription as md,videoSizeToQuality as fd}from"@vkontakte/videoplayer-shared";var Se={};var vt=(n,e)=>new pd(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),pi=class{constructor(e){this.subscription=new md;this.videoState=new $("initializing");this.textTracksManager=new oe;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.to!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ci(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ci(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ci(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ci(e)}break;default:ci(t)}};this.video=z(e.container),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(G(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),K(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:tr.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(Se.Hls=r.default,Se.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){tn(Se.Hls,"hls.js not loaded"),this.hls=new Se.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){tn(Se.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:tr.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=X(this.video),a=(u,l)=>this.subscription.add(u.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Te(this.video,e.isLooped,i)),this.subscription.add(J(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ne(this.video,e.playbackRate,r.playbackRateState$,i)),a(de(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(ir(u=>u.to)),this.params.output.playbackState$),this.subscription.add(vt(this.hls,Se.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:tr.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(vt(this.hls,Se.Events.MANIFEST_PARSED).pipe(ir(({levels:u})=>u.reduce((l,c)=>{let p=c.name||c.height.toString(10),{width:h,height:m}=c,v=Fe(c.attrs.QUALITY??"")??fd({width:h,height:m});if(!v)return l;let f=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,g={id:p.toString(),quality:v,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:f};return this.trackLevels.set(p,{track:g,level:c}),l.push(g),l},[]))),t.availableVideoTracks$),a(vt(this.hls,Se.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let l=[];for(let c of u.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang,v="internal";l.push({id:p,url:h,language:m,type:v})}e.internalTextTracks.startTransitionTo(l)}}),a(vt(this.hls,Se.Events.LEVEL_LOADING).pipe(ir(({url:u})=>G(u))),t.hostname$),a(vt(this.hls,Se.Events.FRAG_CHANGED),u=>{let{video:l,audio:c}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(Oe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));let s=u=>Array.from(this.trackLevels.values()).find(({level:l})=>l===u)?.track,o=vt(this.hls,Se.Events.LEVEL_SWITCHED).pipe(ir(({level:u})=>s(this.hls.levels[u])));o.pipe(ud(dd)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Oe(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),u=>{if(ld(u))return;let l=this.trackLevels.get(u.id)?.level;if(!l)return;let c=this.hls.levels.indexOf(l),p=this.hls.currentLevel,h=this.hls.levels[p];!h||l.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let d=cd(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,hd(["init"])).pipe(od(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Z(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tr.DOM,thrown:t}))||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("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"),y(this.params.desiredState.playbackState,"stopped",!0)}};var rn="X-Playback-Duration",na=async n=>{let e=await fetch(n),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(rn)?parseInt(e.headers.get(rn),10):void 0};import{assertNever as Td,combine as Id,debounce as Ed,ErrorCategory as ar,filter as xd,filterChanged as kd,isNonNullable as sn,isNullable as sr,map as nn,merge as Pd,observableFrom as Ad,Subscription as wd,ValueSubject as ua,VideoQuality as $d}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as bd,getExponentialDelay as gd}from"@vkontakte/videoplayer-shared";var Sd=n=>{let e=null;if(n.QUALITY&&(e=Fe(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=bd({width:t,height:i})}return e??null},vd=(n,e)=>{let t=n.split(`
92
+ `),i=[],r=[];for(let a=0;a<t.length;a++){let s=t[a],o=s.match(/^#EXT-X-STREAM-INF:(.+)/),d=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!d)){if(o){let u=Object.fromEntries(o[1].split(",").map(f=>f.split("="))),l=u.QUALITY??`stream-${u.BANDWIDTH}`,c=Sd(u),p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[f,g]=u.RESOLUTION.split("x").map(S=>parseInt(S,10));f&&g&&(m={width:f,height:g})}let v=new URL(t[++a],e).toString();c&&i.push({id:l,quality:c,url:v,bandwidth:p,size:m,fps:h})}if(d){let u=Object.fromEntries(d[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),l=u.URI?.replace(/playlist$/,"subtitles.vtt"),c=u.LANGUAGE,p=u.NAME;l&&c&&r.push({type:"internal",id:c,label:p,language:c,url:l,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},yd=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),oa=0,an=async(n,e=n,t)=>{let r=await(await fetch(n)).text();oa+=1;try{let{qualityManifests:a,textTracks:s}=vd(r,e);return{qualityManifests:a,textTracks:s}}catch{if(oa<=t.manifestRetryMaxCount)return await yd(gd(oa-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),an(n,e,t)}return{qualityManifests:[],textTracks:[]}},rr=an;var hi=class{constructor(e){this.subscription=new wd;this.videoState=new $("stopped");this.textTracksManager=new oe;this.manifests$=new ua([]);this.liveOffset=new we;this.manifestStartTime$=new ua(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):r?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else r?.to==="paused"&&(y(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Td(t)}};this.params=e,this.video=z(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:$d.INVARIANT,url:this.params.source.url},rr(W(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ar.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:ar.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.maxSeekBackTime$=new ua(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:ar.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=X(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(J(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ne(this.video,t.playbackRate,r.playbackRateState$,i)),a(de(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(kd(),nn(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&sn(u.to)){let c=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from==="changing_manifest"&&this.videoState.setState(d.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Id({startTime:this.manifestStartTime$.pipe(xd(sn)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:d})=>this.params.output.liveTime$.next(o+d*1e3),i)),this.subscription.add(this.manifests$.pipe(nn(o=>o.map(({id:d,quality:u,size:l,bandwidth:c,fps:p})=>({id:d,quality:u,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let s=Pd(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ad(["init"])).pipe(Ed(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),K(this.video)}prepare(){let e=this.selectManifest();if(sr(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:d}=t?.to??i??{};for(let[u,l]of[[o,"mq"],[d,"lq"]]){let c=String(parseFloat(u||""));l&&u&&r.searchParams.set(l,c)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=W(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),na(s).then(o=>{if(!sr(o))this.maxSeekBackTime$.next(o);else{let d=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(sr(d)||!isFinite(d))try{fetch(s).then(u=>u.text()).then(u=>{let l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(l){let c=new URL(l,s).toString();na(c).then(p=>{sr(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){Z(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ar.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as Ld,debounce as Rd,ErrorCategory as da,fromEvent as la,isNonNullable as Md,isNullable as Dd,map as on,merge as un,observableFrom as dn,Subscription as Cd,ValueSubject as Bd,VideoQuality as Vd,isIOS as Od}from"@vkontakte/videoplayer-shared";var mi=class{constructor(e){this.subscription=new Cd;this.videoState=new $("stopped");this.textTracksManager=new oe;this.manifests$=new Bd([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Ld(t)}};this.params=e,this.video=z(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Vd.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(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),rr(W(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:da.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:da.WTF,message:"HlsProvider internal logic error",thrown:o})},r=X(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(on(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Te(this.video,t.isLooped,i)),this.subscription.add(J(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ne(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&Md(u.to)){let c=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===c);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(h),v.playbackRate=h)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from==="changing_manifest"&&this.videoState.setState(d.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(on(o=>o.map(({id:d,quality:u,size:l,bandwidth:c,fps:p})=>({id:d,quality:u,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!Od()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(un(la(o,"addtrack"),la(o,"removetrack"),la(o,"change"),dn(["init"])).subscribe(()=>{for(let d=0;d<o.length;d++)o[d].mode="hidden"},i))}let s=un(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,dn(["init"])).pipe(Rd(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),K(this.video)}prepare(){let e=this.selectManifest();if(Dd(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:a,min:s}=t?.to??i??{};for(let[o,d]of[[a,"mq"],[s,"lq"]]){let u=String(parseFloat(o||""));d&&o&&r.searchParams.set(d,u)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Z(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:da.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as _d,assertNonNullable as ln,debounce as Nd,ErrorCategory as cn,isHigher as Fd,isHigherOrEqual as Ud,isInvariantQuality as pn,isLowerOrEqual as Hd,isNonNullable as Gd,merge as Qd,observableFrom as jd,Subscription as Wd,map as Yd}from"@vkontakte/videoplayer-shared";var fi=class{constructor(e){this.subscription=new Wd;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new oe;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),s.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[s.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?y(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return _d(e)}};this.params=e,this.video=z(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:cn.WTF,message:"MpegProvider internal logic error",thrown:o})},r=X(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(Yd(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Te(this.video,t.isLooped,i)),this.subscription.add(J(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ne(this.video,t.playbackRate,r.playbackRateState$,i)),a(de(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&Gd(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(d!==u){let l=this.params.output.element$.getValue();l&&(this.params.desiredState.playbackRate.setState(d),l.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=Qd(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,jd(["init"])).pipe(Nd(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),K(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;ln(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];ln(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=si(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(G(t))}playIfAllowed(){Z(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let r=Object.values(this.trackUrls).find(o=>!pn(o.track.quality)&&Hd(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,s=this.trackUrls[a??"0"]?.track;if(r&&s&&Ud(s.quality,r.quality)&&(t=r),!t){let o=Object.values(this.trackUrls).filter(u=>!pn(u.track.quality)&&Fd(u.track.quality,e)),d=o.length;d&&(t=o[d-1].track)}t&&(i=t.quality)}else if(!e){let r=Object.values(this.trackUrls).map(a=>a.track);t=He(r,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};import{assertNever as mn,debounce as Jd,merge as fn,observableFrom as Xd,Subscription as Zd,map as bn,ValueSubject as el,ErrorCategory as pa,VideoQuality as tl}from"@vkontakte/videoplayer-shared";import{ErrorCategory as qd}from"@vkontakte/videoplayer-shared";var hn=["stun:videostun.mycdn.me:80"],zd=1e3,Kd=3,ca=()=>null,nr=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=ca;this.externalStopCallback=ca;this.externalErrorCallback=ca;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:hn}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:qd.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),zd)}normalizeOptions(e={}){let t={stunServerList:hn,maxRetryNumber:Kd,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var bi=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new el(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return mn(e)}};this.subscription=new Zd,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=z(e.container),this.liveStreamClient=new nr(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),K(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:pa.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};fn(this.videoState.stateChangeStarted$.pipe(bn(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(bn(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=X(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(de(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(J(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.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 mn(s.to)}},i)).add(fn(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Xd(["init"])).pipe(Jd(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(G(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:tl.INVARIANT}),this.video.srcObject=e,y(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:pa.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Z(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pa.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var gi=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ti,assertNonNullable as We,ErrorCategory as lr,filter as vl,isNonNullable as Ln,isNullable as yl,map as Tl,merge as Il,once as El,Subject as ce,Subscription as Rn,ValueSubject as R}from"@vkontakte/videoplayer-shared";import{assertNever as ur,CurrentClientBrowser as al,CurrentClientDevice as sl,getCurrentBrowser as gn,isAndroid as nl}from"@vkontakte/videoplayer-shared";var Sn=nl(),or=document.createElement("video"),ol='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ul='video/mp4; codecs="hev1.1.6.L93.B0"',vn='video/webm; codecs="vp09.00.10.08"',yn='video/webm; codecs="av01.0.00M.08"',dl='audio/mp4; codecs="mp4a.40.2"',ll='audio/webm; codecs="opus"',nt={mms:Wi(),mse:Ns(),hls:!!(or.canPlayType?.("application/x-mpegurl")||or.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},le={mp4:!!or.canPlayType?.("video/mp4"),webm:!!or.canPlayType?.("video/webm"),cmaf:!0},ke={h264:!!Re()?.isTypeSupported?.(ol),h265:!!Re()?.isTypeSupported?.(ul),vp9:!!Re()?.isTypeSupported?.(vn),av1:!!Re()?.isTypeSupported?.(yn),aac:!!Re()?.isTypeSupported?.(dl),opus:!!Re()?.isTypeSupported?.(ll)},Si=(ke.h264||ke.h265)&&ke.aac,ot,cl=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:yn}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:vn}})]);ot={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{cl()}catch(n){console.error(n)}var yt=nt.hls&&le.mp4,Tn=()=>Object.keys(ke).filter(n=>ke[n]),In=(n,e=!1,t=!1)=>{let i=nt.mse||nt.mms&&t;return n.filter(r=>{switch(r){case"DASH_SEP":return i&&le.mp4&&Si;case"DASH_WEBM":return i&&le.webm&&ke.vp9&&ke.opus;case"DASH_WEBM_AV1":return i&&le.webm&&ke.av1&&ke.opus;case"DASH_LIVE":return nt.mse&&le.mp4&&Si;case"DASH_LIVE_CMAF":return i&&le.mp4&&Si&&le.cmaf;case"DASH_ONDEMAND":return i&&le.mp4&&Si;case"HLS":case"HLS_ONDEMAND":return yt||e&&nt.mse&&le.mp4&&Si;case"HLS_LIVE":case"HLS_LIVE_CMAF":return yt;case"MPEG":return le.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return nt.webrtc&&nt.ws&&ke.h264&&(le.mp4||le.webm);default:return ur(r)}})},je=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return ot?ot[t].smooth?[t,e]:ot[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ot?ot[t].powerEfficient?[t,e]:ot[e].powerEfficient?[e,t]:[t,e]:[e,t];default:ur(n)}return[e,t]},En=({webmCodec:n,androidPreferredFormat:e})=>{if(Sn)switch(e){case"mpeg":return["MPEG",...je(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...je(n),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...je(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...je(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...je(n),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...je(n),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:ur(e)}return yt?[...je(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...je(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},xn=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,d=gn().device===sl.Mac&&gn().browser===al.Safari;if(Sn)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:ur(n)}else yt&&!d?o=s:d?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},ha=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];import{Observable as pl,map as kn,Subscription as hl,Subject as ml}from"@vkontakte/videoplayer-shared";var Pn=n=>new pl(e=>{let t=new hl,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(kn(({from:u,to:l})=>`${u}-${l}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(kn(({type:u})=>u!==void 0)),s=new ml,o=0,d="unknown";return t.add(i.subscribe(u=>{o&&window.clearTimeout(o),d=u,o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),d="unknown",o=0})),t.add(a.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as An,Subscription as fl,combine as bl,filter as wn,once as $n}from"@vkontakte/videoplayer-shared";var vi=null,dr=null;function ma(){return vi||(vi=new(window.AudioContext||window.webkitAudioContext)),dr||(dr=new GainNode(vi,{gain:1}),dr.connect(vi.destination)),{audioCtx:vi,gainNode:dr}}import{getCurrentBrowser as gl,CurrentClientBrowser as Sl}from"@vkontakte/videoplayer-shared";var yi=class n{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new fl;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe(wn(s=>!!s.type),$n()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){let{browser:t}=gl();t===Sl.Safari&&e!=="MPEG"||this.subscriptions.add(bl({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(wn(({playbackState:i,video:r,volume:{muted:a,volume:s}})=>i==="playing"&&!!r&&!a&&!!s),$n()).subscribe(({video:i})=>this.initAudioContextOnce(i)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=ma(),a=(Math.random()+1)*999999;this.lastAudioContextResumeId=a,i.resume().then(()=>{if(a!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${n.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(s){this.volumeMultiplierError$.next({id:n.errorId,category:An.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:s})}}).catch(s=>{this.volumeMultiplierError$.next({id:n.errorId,category:An.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=ma();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var xl={chunkDuration:5e3,maxParallelRequests:5},Ii=class{constructor(e){this.current$=new R({type:void 0});this.providerError$=new ce;this.noAvailableProvidersError$=new ce;this.volumeMultiplierError$=new ce;this.providerOutput={position$:new R(0),duration$:new R(1/0),volume$:new R({muted:!1,volume:1}),currentVideoTrack$:new R(void 0),currentVideoSegmentLength$:new R(0),currentAudioSegmentLength$:new R(0),availableVideoTracks$:new R([]),availableAudioTracks$:new R([]),isAudioAvailable$:new R(!0),autoVideoTrackLimitingAvailable$:new R(!1),autoVideoTrackLimits$:new R(void 0),currentBuffer$:new R(void 0),isBuffering$:new R(!0),error$:new ce,warning$:new ce,willSeekEvent$:new ce,seekedEvent$:new ce,loopedEvent$:new ce,endedEvent$:new ce,firstBytesEvent$:new ce,firstFrameEvent$:new ce,canplay$:new ce,isLive$:new R(void 0),isLowLatency$:new R(!1),canChangePlaybackSpeed$:new R(!0),liveTime$:new R(void 0),liveBufferTime$:new R(void 0),availableTextTracks$:new R([]),currentTextTrack$:new R(void 0),hostname$:new R(void 0),httpConnectionType$:new R(void 0),httpConnectionReused$:new R(void 0),inPiP$:new R(!1),inFullscreen$:new R(!1),element$:new R(void 0),elementVisible$:new R(!0),availableSources$:new R(void 0),is3DVideo$:new R(!1),playbackState$:new R("")};this.subscription=new Rn;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=In([...xn(this.params.tuning),...En(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>Ln(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new gi(a);let s=[...ha(!0),...ha(!1)];this.chromecastFormatsIterator=new gi(s.filter(o=>Ln(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new yi(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(yl(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:lr.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.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,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let s=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:s.x,y:s.y})}e.destroy();let a=this.providerOutput.isBuffering$;a.getValue()||a.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 Ti(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":{let o=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return We(o),new di({...s,source:o,sourceHls:d})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return We(o),new li({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return We(o),yt||!this.params.tuning.useHlsJs?new mi({...s,source:o}):new pi({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return We(o),new hi({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return We(o),new fi({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return We(o),new cs({...s,source:o,config:{...xl,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return We(o),new bi({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return Ti(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return We(o),new xt({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,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 Ti(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ti(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 Ti(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new Rn,t=!1,i=0;return e.add(Il(this.providerOutput.error$,Pn({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Tl(r=>({id:`ProviderHangup:${r}`,category:lr.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(vl(({to:a})=>a==="playing"),El()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination;if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let s=r.category===lr.NETWORK,o=r.category===lr.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<this.params.tuning.providerErrorLimit&&!o;d&&!o&&(s&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(i++,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}})),e}};import{fromEvent as cr,once as kl,combine as Pl,Subscription as Mn,ValueSubject as fa,map as Al,filter as wl,isNonNullable as pr,now as se,safeStorage as ba}from"@vkontakte/videoplayer-shared";var $l=5e3,Dn="one_video_throughput",Cn="one_video_rtt",Ei=window.navigator.connection,Bn=()=>{let n=Ei?.downlink;if(pr(n)&&n!==10)return n*1e3},Vn=()=>{let n=Ei?.rtt;if(pr(n)&&n!==3e3)return n},On=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},ga=class n{constructor(e){this.subscription=new Mn;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(Dn)||(e.useBrowserEstimation?Bn():void 0)||$l,i=n.load(Cn)??(e.useBrowserEstimation?Vn():void 0)??0;if(this.throughput$=new fa(t),this.rtt$=new fa(i),this.rttAdjustedThroughput$=new fa(On(t,i,e.rttPenaltyRequestSize)),this.throughput=rt.getSmoothedValue(t,-1,e),this.rtt=rt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=Bn();s&&this.throughput.next(s);let o=Vn();pr(o)&&this.rtt.next(o)};Ei&&"onchange"in Ei&&this.subscription.add(cr(Ei,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{ba.set(Dn,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{ba.set(Cn,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Pl({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Al(({throughput:r,rtt:a})=>On(r,a,e.rttPenaltyRequestSize)),wl(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=se(),r=new Mn;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(cr(e,"progress").pipe(kl()).subscribe(a=>{t=a.loaded,i=se()}));break;case 1:case 0:r.add(cr(e,"loadstart").subscribe(()=>{t=0,i=se()}));break}r.add(cr(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=se(),d=s-t,u=o-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=se(),s=0,o=se(),d=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},u=async({done:l,value:c})=>{if(l)!t&&this.addRawSpeed(r,se()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=se();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(s,m,1,t),s=c.byteLength,a=se()}else s+=c.byteLength;o=se()}else r+=c.byteLength,s+=c.byteLength,s>=this.tuningConfig.streamMinSampleSize&&se()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,se()-o,this.concurrentDownloads.size),s=0,o=se());await i?.read().then(u,d)}};this.concurrentDownloads.add(e),i?.read().then(u,d)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=ba.get(e);if(pr(t))return parseInt(t,10)??void 0}},_n=ga;import{fillWithDefault as Ll,VideoQuality as Nn}from"@vkontakte/videoplayer-shared";var Fn={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:Nn.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Nn.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:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:200,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,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:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,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},Un=n=>({...Ll(n,Fn),configName:[...n.configName??[],...Fn.configName]});import{assertNonNullable as hr,combine as mr,ErrorCategory as fr,filter as xi,filterChanged as pe,fromEvent as va,isNonNullable as Ol,isNullable as _l,Logger as Nl,map as L,mapTo as jn,merge as Ye,now as br,once as Me,Subject as N,Subscription as Wn,tap as Yn,ValueSubject as E,isHigher as Fl,isInvariantQuality as qn}from"@vkontakte/videoplayer-shared";import{merge as Rl,map as Ml,filter as Hn,isNonNullable as Dl}from"@vkontakte/videoplayer-shared";var Sa=({seekState:n,position$:e})=>Rl(n.stateChangeEnded$.pipe(Ml(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Hn(Dl)),e.pipe(Hn(()=>n.getState().state==="none")));import{assertNonNullable as Cl}from"@vkontakte/videoplayer-shared";var Gn=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return Cl(e,`Wrong container or containerId {${n.container}}`),e};import{filter as Bl,once as Vl}from"@vkontakte/videoplayer-shared";var Qn=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Bl(r=>r.length>0),Vl()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var gr=class{constructor(e={configName:[]}){this.subscription=new Wn;this.logger=new Nl;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableQualities$:new E([]),availableQualitiesFps$:new E({}),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(0)};this.events={inited$:new N,ready$:new N,started$:new N,playing$:new N,paused$:new N,stopped$:new N,willStart$:new N,willResume$:new N,willPause$:new N,willStop$:new N,willDestruct$:new N,watchCoverageRecord$:new N,watchCoverageLive$:new N,managedError$:new N,fatalError$:new N,ended$:new N,looped$:new N,seeked$:new N,willSeek$:new N,firstBytes$:new N,firstFrame$:new N,canplay$:new N,log$:new N};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:Xa};if(this.initLogs(),this.tuning=Un(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Mi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new _n(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{let a=Reflect.get(t,i,r);return typeof a!="function"?a:(...s)=>{try{return a.apply(t,s)}catch(o){let d=s.map(c=>JSON.stringify(c,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),u=`Player.${String(i)}`,l=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:fr.WTF,message:l,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Gn(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ii({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.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&&!Dt()?va(document,"visibilitychange").pipe(Me()).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 i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.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}setQuality(e){hr(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(xi(i=>i.length>0),Me()).subscribe(i=>{this.setVideoTrackIdByQuality(i,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){hr(this.providerContainer);let t=this.providerContainer?.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){return Qn(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.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 i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}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(_l(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Ol(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ye(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(L(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(L(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(L(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(L(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(L(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(xi(({from:e})=>e==="stopped"),Me()).subscribe(()=>{this.initedAt=br(),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 s=this.desiredState.seekState.getState();s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:fr.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(L(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(L(s=>s.destination),pe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(L(s=>s.map(({quality:o})=>o).sort((o,d)=>qn(o)?1:qn(d)?-1:Fl(d,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let d of s)d.fps&&(o[d.quality]=d.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s?.quality),this.info.videoBitrate$.next(s?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(pe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(pe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(pe()).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(s=>{this.desiredState.autoVideoTrackLimits.setState(s??{})})).add(e.providerOutput.currentBuffer$.pipe(L(s=>s?{start:s.from,end:s.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(mr({hasLiveOffsetByPaused:Ye(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(L(s=>s.to),pe(),L(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(mr({atLiveEdge:mr({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Sa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(L(({isLive:s,position:o,isLowLatency:d})=>{let u=this.getActiveLiveDelay(d);return s&&Math.abs(o)<u/1e3}),pe(),Yn(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(L(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(mr({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(L(({isLive:s,position:o,duration:d})=>s&&(Math.abs(d)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),pe(),Yn(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(L(s=>s.muted),pe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(L(s=>s.volume),pe()).subscribe(this.info.volume$)).add(Sa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ye(e.providerOutput.endedEvent$.pipe(jn(!0)),e.providerOutput.seekedEvent$.pipe(jn(!1))).pipe(pe()).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(L(s=>({id:s?`No${s}`:"NoProviders",category:fr.VIDEO_PIPELINE,message:s?`${s} 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(Me(),L(s=>s??br()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Me(),L(()=>br()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Me(),L(()=>br()-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 E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new E(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(xi(({to:s})=>s==="playing"),Me()).subscribe(()=>i.next(!1)));let r=0,a=Ye(e.providerOutput.isBuffering$,t,i).pipe(L(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),pe());this.subscription.add(a.subscribe(s=>{s?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Ye(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.videoWidth,height:s?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.size?.width,height:s?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ye(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),c;l==="CONNECTED"?c="second_screen":d?u?s?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(L(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Wn;this.subscription.add(t),this.subscription.add(e.current$.pipe(pe((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(xi(i=>i.length>0),Me()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t,i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=He(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(Ye(this.desiredState.videoTrack.stateChangeStarted$.pipe(L(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(L(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(L(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(L(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(L(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(L(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(L(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(L(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(L(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;hr(this.providerContainer),hr(e),Ja(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ka(t)),this.providerContainer.current$.subscribe(({type:t})=>wt("provider",t)),e.duration$.subscribe(t=>wt("duration",t)),e.availableVideoTracks$.pipe(xi(t=>!!t.length),Me()).subscribe(t=>wt("tracks",t)),this.events.fatalError$.subscribe(new Y("fatalError")),this.events.managedError$.subscribe(new Y("managedError")),e.position$.subscribe(new Y("position")),e.currentVideoTrack$.pipe(L(t=>t?.quality)).subscribe(new Y("quality")),this.info.currentBuffer$.subscribe(new Y("buffer")),e.isBuffering$.subscribe(new Y("isBuffering"))].forEach(t=>this.subscription.add(t)),wt("codecs",Tn())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:fr.DOM,message:String(r)})})};this.subscription.add(Ye(va(document,"visibilitychange"),va(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!e?.released;r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as RE,Observable as ME,Subject as DE,ValueSubject as CE,VideoQuality as BE}from"@vkontakte/videoplayer-shared";var VE=`@vkontakte/videoplayer-core@${Ta}`;export{Li as ChromecastState,xr as HttpConnectionType,ME as Observable,q as PlaybackState,gr as Player,VE as SDK_VERSION,DE as Subject,RE as Subscription,kr as Surface,Ta as VERSION,CE as ValueSubject,Ve as VideoFormat,BE as VideoQuality};