@vkontakte/videoplayer-core 2.0.106-beta.1 → 2.0.106-dev.1a114cd2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +23 -23
- package/es2015.esm.js +25 -25
- package/es2018.cjs.js +24 -24
- package/es2018.esm.js +23 -23
- package/esnext.cjs.js +23 -23
- package/esnext.esm.js +21 -21
- package/evergreen.esm.js +3 -3
- package/package.json +2 -2
package/esnext.cjs.js
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.106-
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.106-dev.1a114cd2.0
|
|
3
|
+
* Wed, 21 Aug 2024 08:39:23 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-106/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Rm=Object.create;var Zi=Object.defineProperty;var Lm=Object.getOwnPropertyDescriptor;var $m=Object.getOwnPropertyNames;var Cm=Object.getPrototypeOf,Mm=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Dm=(i,e)=>{for(var t in e)Zi(i,t,{get:e[t],enumerable:!0})},Ko=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of $m(e))!Mm.call(i,a)&&a!==t&&Zi(i,a,{get:()=>e[a],enumerable:!(r=Lm(e,a))||r.enumerable});return i};var Ne=(i,e,t)=>(t=i!=null?Rm(Cm(i)):{},Ko(e||!i||!i.__esModule?Zi(t,"default",{value:i,enumerable:!0}):t,i)),Om=i=>Ko(Zi({},"__esModule",{value:!0}),i);var Ae=m((Zx,Xo)=>{"use strict";Xo.exports=function(i){try{return!!i()}catch{return!0}}});var $r=m((eP,Zo)=>{"use strict";var Vm=Ae();Zo.exports=!Vm(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var me=m((tP,ru)=>{"use strict";var eu=$r(),tu=Function.prototype,xs=tu.call,_m=eu&&tu.bind.bind(xs,xs);ru.exports=eu?_m:function(i){return function(){return xs.apply(i,arguments)}}});var er=m((rP,au)=>{"use strict";var iu=me(),Nm=iu({}.toString),Fm=iu("".slice);au.exports=function(i){return Fm(Nm(i),8,-1)}});var nu=m((iP,su)=>{"use strict";var qm=me(),Um=Ae(),Hm=er(),Ps=Object,jm=qm("".split);su.exports=Um(function(){return!Ps("z").propertyIsEnumerable(0)})?function(i){return Hm(i)=="String"?jm(i,""):Ps(i)}:Ps});var tr=m((aP,ou)=>{"use strict";ou.exports=function(i){return i==null}});var ia=m((sP,uu)=>{"use strict";var Gm=tr(),Ym=TypeError;uu.exports=function(i){if(Gm(i))throw Ym("Can't call method on "+i);return i}});var rr=m((nP,lu)=>{"use strict";var Wm=nu(),Qm=ia();lu.exports=function(i){return Wm(Qm(i))}});var ws=m((oP,cu)=>{"use strict";cu.exports=function(){}});var Lt=m((uP,du)=>{"use strict";du.exports={}});var ne=m((pu,hu)=>{"use strict";var aa=function(i){return i&&i.Math==Math&&i};hu.exports=aa(typeof globalThis=="object"&&globalThis)||aa(typeof window=="object"&&window)||aa(typeof self=="object"&&self)||aa(typeof global=="object"&&global)||function(){return this}()||pu||Function("return this")()});var ks=m((lP,fu)=>{"use strict";var As=typeof document=="object"&&document.all,zm=typeof As>"u"&&As!==void 0;fu.exports={all:As,IS_HTMLDDA:zm}});var ee=m((cP,bu)=>{"use strict";var mu=ks(),Km=mu.all;bu.exports=mu.IS_HTMLDDA?function(i){return typeof i=="function"||i===Km}:function(i){return typeof i=="function"}});var vu=m((dP,gu)=>{"use strict";var Jm=ne(),Xm=ee(),Su=Jm.WeakMap;gu.exports=Xm(Su)&&/native code/.test(String(Su))});var ze=m((pP,Iu)=>{"use strict";var yu=ee(),Tu=ks(),Zm=Tu.all;Iu.exports=Tu.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:yu(i)||i===Zm}:function(i){return typeof i=="object"?i!==null:yu(i)}});var Ke=m((hP,Eu)=>{"use strict";var eb=Ae();Eu.exports=!eb(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var sa=m((fP,Pu)=>{"use strict";var tb=ne(),xu=ze(),Rs=tb.document,rb=xu(Rs)&&xu(Rs.createElement);Pu.exports=function(i){return rb?Rs.createElement(i):{}}});var Ls=m((mP,wu)=>{"use strict";var ib=Ke(),ab=Ae(),sb=sa();wu.exports=!ib&&!ab(function(){return Object.defineProperty(sb("div"),"a",{get:function(){return 7}}).a!=7})});var $s=m((bP,Au)=>{"use strict";var nb=Ke(),ob=Ae();Au.exports=nb&&ob(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Fe=m((SP,ku)=>{"use strict";var ub=ze(),lb=String,cb=TypeError;ku.exports=function(i){if(ub(i))return i;throw cb(lb(i)+" is not an object")}});var be=m((gP,Ru)=>{"use strict";var db=$r(),na=Function.prototype.call;Ru.exports=db?na.bind(na):function(){return na.apply(na,arguments)}});var oa=m((vP,Lu)=>{"use strict";Lu.exports={}});var rt=m((yP,Cu)=>{"use strict";var Cs=oa(),Ms=ne(),pb=ee(),$u=function(i){return pb(i)?i:void 0};Cu.exports=function(i,e){return arguments.length<2?$u(Cs[i])||$u(Ms[i]):Cs[i]&&Cs[i][e]||Ms[i]&&Ms[i][e]}});var Cr=m((TP,Mu)=>{"use strict";var hb=me();Mu.exports=hb({}.isPrototypeOf)});var Mr=m((IP,Du)=>{"use strict";Du.exports=typeof navigator<"u"&&String(navigator.userAgent)||""});var Os=m((EP,Fu)=>{"use strict";var Nu=ne(),Ds=Mr(),Ou=Nu.process,Bu=Nu.Deno,Vu=Ou&&Ou.versions||Bu&&Bu.version,_u=Vu&&Vu.v8,qe,ua;_u&&(qe=_u.split("."),ua=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!ua&&Ds&&(qe=Ds.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=Ds.match(/Chrome\/(\d+)/),qe&&(ua=+qe[1])));Fu.exports=ua});var Bs=m((xP,Uu)=>{"use strict";var qu=Os(),fb=Ae(),mb=ne(),bb=mb.String;Uu.exports=!!Object.getOwnPropertySymbols&&!fb(function(){var i=Symbol();return!bb(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&qu&&qu<41})});var Vs=m((PP,Hu)=>{"use strict";var Sb=Bs();Hu.exports=Sb&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var _s=m((wP,ju)=>{"use strict";var gb=rt(),vb=ee(),yb=Cr(),Tb=Vs(),Ib=Object;ju.exports=Tb?function(i){return typeof i=="symbol"}:function(i){var e=gb("Symbol");return vb(e)&&yb(e.prototype,Ib(i))}});var Dr=m((AP,Gu)=>{"use strict";var Eb=String;Gu.exports=function(i){try{return Eb(i)}catch{return"Object"}}});var it=m((kP,Yu)=>{"use strict";var xb=ee(),Pb=Dr(),wb=TypeError;Yu.exports=function(i){if(xb(i))return i;throw wb(Pb(i)+" is not a function")}});var Or=m((RP,Wu)=>{"use strict";var Ab=it(),kb=tr();Wu.exports=function(i,e){var t=i[e];return kb(t)?void 0:Ab(t)}});var zu=m((LP,Qu)=>{"use strict";var Ns=be(),Fs=ee(),qs=ze(),Rb=TypeError;Qu.exports=function(i,e){var t,r;if(e==="string"&&Fs(t=i.toString)&&!qs(r=Ns(t,i))||Fs(t=i.valueOf)&&!qs(r=Ns(t,i))||e!=="string"&&Fs(t=i.toString)&&!qs(r=Ns(t,i)))return r;throw Rb("Can't convert object to primitive value")}});var Ue=m(($P,Ku)=>{"use strict";Ku.exports=!0});var Zu=m((CP,Xu)=>{"use strict";var Ju=ne(),Lb=Object.defineProperty;Xu.exports=function(i,e){try{Lb(Ju,i,{value:e,configurable:!0,writable:!0})}catch{Ju[i]=e}return e}});var la=m((MP,tl)=>{"use strict";var $b=ne(),Cb=Zu(),el="__core-js_shared__",Mb=$b[el]||Cb(el,{});tl.exports=Mb});var Us=m((DP,il)=>{"use strict";var Db=Ue(),rl=la();(il.exports=function(i,e){return rl[i]||(rl[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:Db?"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 Br=m((OP,al)=>{"use strict";var Ob=ia(),Bb=Object;al.exports=function(i){return Bb(Ob(i))}});var He=m((BP,sl)=>{"use strict";var Vb=me(),_b=Br(),Nb=Vb({}.hasOwnProperty);sl.exports=Object.hasOwn||function(e,t){return Nb(_b(e),t)}});var Hs=m((VP,nl)=>{"use strict";var Fb=me(),qb=0,Ub=Math.random(),Hb=Fb(1 .toString);nl.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Hb(++qb+Ub,36)}});var ce=m((_P,ul)=>{"use strict";var jb=ne(),Gb=Us(),ol=He(),Yb=Hs(),Wb=Bs(),Qb=Vs(),ir=jb.Symbol,js=Gb("wks"),zb=Qb?ir.for||ir:ir&&ir.withoutSetter||Yb;ul.exports=function(i){return ol(js,i)||(js[i]=Wb&&ol(ir,i)?ir[i]:zb("Symbol."+i)),js[i]}});var pl=m((NP,dl)=>{"use strict";var Kb=be(),ll=ze(),cl=_s(),Jb=Or(),Xb=zu(),Zb=ce(),eS=TypeError,tS=Zb("toPrimitive");dl.exports=function(i,e){if(!ll(i)||cl(i))return i;var t=Jb(i,tS),r;if(t){if(e===void 0&&(e="default"),r=Kb(t,i,e),!ll(r)||cl(r))return r;throw eS("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xb(i,e)}});var ca=m((FP,hl)=>{"use strict";var rS=pl(),iS=_s();hl.exports=function(i){var e=rS(i,"string");return iS(e)?e:e+""}});var $t=m(ml=>{"use strict";var aS=Ke(),sS=Ls(),nS=$s(),da=Fe(),fl=ca(),oS=TypeError,Gs=Object.defineProperty,uS=Object.getOwnPropertyDescriptor,Ys="enumerable",Ws="configurable",Qs="writable";ml.f=aS?nS?function(e,t,r){if(da(e),t=fl(t),da(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Qs in r&&!r[Qs]){var a=uS(e,t);a&&a[Qs]&&(e[t]=r.value,r={configurable:Ws in r?r[Ws]:a[Ws],enumerable:Ys in r?r[Ys]:a[Ys],writable:!1})}return Gs(e,t,r)}:Gs:function(e,t,r){if(da(e),t=fl(t),da(r),sS)try{return Gs(e,t,r)}catch{}if("get"in r||"set"in r)throw oS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Vr=m((UP,bl)=>{"use strict";bl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Ct=m((HP,Sl)=>{"use strict";var lS=Ke(),cS=$t(),dS=Vr();Sl.exports=lS?function(i,e,t){return cS.f(i,e,dS(1,t))}:function(i,e,t){return i[e]=t,i}});var pa=m((jP,vl)=>{"use strict";var pS=Us(),hS=Hs(),gl=pS("keys");vl.exports=function(i){return gl[i]||(gl[i]=hS(i))}});var ha=m((GP,yl)=>{"use strict";yl.exports={}});var Xs=m((YP,El)=>{"use strict";var fS=vu(),Il=ne(),mS=ze(),bS=Ct(),zs=He(),Ks=la(),SS=pa(),gS=ha(),Tl="Object already initialized",Js=Il.TypeError,vS=Il.WeakMap,fa,_r,ma,yS=function(i){return ma(i)?_r(i):fa(i,{})},TS=function(i){return function(e){var t;if(!mS(e)||(t=_r(e)).type!==i)throw Js("Incompatible receiver, "+i+" required");return t}};fS||Ks.state?(je=Ks.state||(Ks.state=new vS),je.get=je.get,je.has=je.has,je.set=je.set,fa=function(i,e){if(je.has(i))throw Js(Tl);return e.facade=i,je.set(i,e),e},_r=function(i){return je.get(i)||{}},ma=function(i){return je.has(i)}):(Mt=SS("state"),gS[Mt]=!0,fa=function(i,e){if(zs(i,Mt))throw Js(Tl);return e.facade=i,bS(i,Mt,e),e},_r=function(i){return zs(i,Mt)?i[Mt]:{}},ma=function(i){return zs(i,Mt)});var je,Mt;El.exports={set:fa,get:_r,has:ma,enforce:yS,getterFor:TS}});var Zs=m((WP,Al)=>{"use strict";var IS=$r(),wl=Function.prototype,xl=wl.apply,Pl=wl.call;Al.exports=typeof Reflect=="object"&&Reflect.apply||(IS?Pl.bind(xl):function(){return Pl.apply(xl,arguments)})});var en=m((QP,kl)=>{"use strict";var ES=er(),xS=me();kl.exports=function(i){if(ES(i)==="Function")return xS(i)}});var Cl=m($l=>{"use strict";var Rl={}.propertyIsEnumerable,Ll=Object.getOwnPropertyDescriptor,PS=Ll&&!Rl.call({1:2},1);$l.f=PS?function(e){var t=Ll(this,e);return!!t&&t.enumerable}:Rl});var tn=m(Dl=>{"use strict";var wS=Ke(),AS=be(),kS=Cl(),RS=Vr(),LS=rr(),$S=ca(),CS=He(),MS=Ls(),Ml=Object.getOwnPropertyDescriptor;Dl.f=wS?Ml:function(e,t){if(e=LS(e),t=$S(t),MS)try{return Ml(e,t)}catch{}if(CS(e,t))return RS(!AS(kS.f,e,t),e[t])}});var rn=m((JP,Ol)=>{"use strict";var DS=Ae(),OS=ee(),BS=/#|\.prototype\./,Nr=function(i,e){var t=_S[VS(i)];return t==FS?!0:t==NS?!1:OS(e)?DS(e):!!e},VS=Nr.normalize=function(i){return String(i).replace(BS,".").toLowerCase()},_S=Nr.data={},NS=Nr.NATIVE="N",FS=Nr.POLYFILL="P";Ol.exports=Nr});var Fr=m((XP,Vl)=>{"use strict";var Bl=en(),qS=it(),US=$r(),HS=Bl(Bl.bind);Vl.exports=function(i,e){return qS(i),e===void 0?i:US?HS(i,e):function(){return i.apply(e,arguments)}}});var $e=m((ZP,Nl)=>{"use strict";var ba=ne(),jS=Zs(),GS=en(),YS=ee(),WS=tn().f,QS=rn(),ar=oa(),zS=Fr(),sr=Ct(),_l=He(),KS=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 jS(i,this,arguments)};return e.prototype=i.prototype,e};Nl.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?ba:a?ba[t]:(ba[t]||{}).prototype,o=r?ar:ar[t]||sr(ar,t,{})[t],l=o.prototype,u,c,d,p,f,b,S,T,I;for(p in e)u=QS(r?p:t+(a?".":"#")+p,i.forced),c=!u&&n&&_l(n,p),b=o[p],c&&(i.dontCallGetSet?(I=WS(n,p),S=I&&I.value):S=n[p]),f=c&&S?S:e[p],!(c&&typeof b==typeof f)&&(i.bind&&c?T=zS(f,ba):i.wrap&&c?T=KS(f):s&&YS(f)?T=GS(f):T=f,(i.sham||f&&f.sham||b&&b.sham)&&sr(T,"sham",!0),sr(o,p,T),s&&(d=t+"Prototype",_l(ar,d)||sr(ar,d,{}),sr(ar[d],p,f),i.real&&l&&(u||!l[p])&&sr(l,p,f)))}});var Ul=m((ew,ql)=>{"use strict";var an=Ke(),JS=He(),Fl=Function.prototype,XS=an&&Object.getOwnPropertyDescriptor,sn=JS(Fl,"name"),ZS=sn&&function(){}.name==="something",eg=sn&&(!an||an&&XS(Fl,"name").configurable);ql.exports={EXISTS:sn,PROPER:ZS,CONFIGURABLE:eg}});var jl=m((tw,Hl)=>{"use strict";var tg=Math.ceil,rg=Math.floor;Hl.exports=Math.trunc||function(e){var t=+e;return(t>0?rg:tg)(t)}});var Sa=m((rw,Gl)=>{"use strict";var ig=jl();Gl.exports=function(i){var e=+i;return e!==e||e===0?0:ig(e)}});var Wl=m((iw,Yl)=>{"use strict";var ag=Sa(),sg=Math.max,ng=Math.min;Yl.exports=function(i,e){var t=ag(i);return t<0?sg(t+e,0):ng(t,e)}});var zl=m((aw,Ql)=>{"use strict";var og=Sa(),ug=Math.min;Ql.exports=function(i){return i>0?ug(og(i),9007199254740991):0}});var ga=m((sw,Kl)=>{"use strict";var lg=zl();Kl.exports=function(i){return lg(i.length)}});var Zl=m((nw,Xl)=>{"use strict";var cg=rr(),dg=Wl(),pg=ga(),Jl=function(i){return function(e,t,r){var a=cg(e),s=pg(a),n=dg(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}};Xl.exports={includes:Jl(!0),indexOf:Jl(!1)}});var rc=m((ow,tc)=>{"use strict";var hg=me(),nn=He(),fg=rr(),mg=Zl().indexOf,bg=ha(),ec=hg([].push);tc.exports=function(i,e){var t=fg(i),r=0,a=[],s;for(s in t)!nn(bg,s)&&nn(t,s)&&ec(a,s);for(;e.length>r;)nn(t,s=e[r++])&&(~mg(a,s)||ec(a,s));return a}});var on=m((uw,ic)=>{"use strict";ic.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var sc=m((lw,ac)=>{"use strict";var Sg=rc(),gg=on();ac.exports=Object.keys||function(e){return Sg(e,gg)}});var oc=m(nc=>{"use strict";var vg=Ke(),yg=$s(),Tg=$t(),Ig=Fe(),Eg=rr(),xg=sc();nc.f=vg&&!yg?Object.defineProperties:function(e,t){Ig(e);for(var r=Eg(t),a=xg(t),s=a.length,n=0,o;s>n;)Tg.f(e,o=a[n++],r[o]);return e}});var un=m((dw,uc)=>{"use strict";var Pg=rt();uc.exports=Pg("document","documentElement")});var pn=m((pw,mc)=>{"use strict";var wg=Fe(),Ag=oc(),lc=on(),kg=ha(),Rg=un(),Lg=sa(),$g=pa(),cc=">",dc="<",cn="prototype",dn="script",hc=$g("IE_PROTO"),ln=function(){},fc=function(i){return dc+dn+cc+i+dc+"/"+dn+cc},pc=function(i){i.write(fc("")),i.close();var e=i.parentWindow.Object;return i=null,e},Cg=function(){var i=Lg("iframe"),e="java"+dn+":",t;return i.style.display="none",Rg.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(fc("document.F=Object")),t.close(),t.F},va,ya=function(){try{va=new ActiveXObject("htmlfile")}catch{}ya=typeof document<"u"?document.domain&&va?pc(va):Cg():pc(va);for(var i=lc.length;i--;)delete ya[cn][lc[i]];return ya()};kg[hc]=!0;mc.exports=Object.create||function(e,t){var r;return e!==null?(ln[cn]=wg(e),r=new ln,ln[cn]=null,r[hc]=e):r=ya(),t===void 0?r:Ag.f(r,t)}});var Sc=m((hw,bc)=>{"use strict";var Mg=Ae();bc.exports=!Mg(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var fn=m((fw,vc)=>{"use strict";var Dg=He(),Og=ee(),Bg=Br(),Vg=pa(),_g=Sc(),gc=Vg("IE_PROTO"),hn=Object,Ng=hn.prototype;vc.exports=_g?hn.getPrototypeOf:function(i){var e=Bg(i);if(Dg(e,gc))return e[gc];var t=e.constructor;return Og(t)&&e instanceof t?t.prototype:e instanceof hn?Ng:null}});var nr=m((mw,yc)=>{"use strict";var Fg=Ct();yc.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Fg(i,e,t),i}});var gn=m((bw,Ec)=>{"use strict";var qg=Ae(),Ug=ee(),Hg=ze(),jg=pn(),Tc=fn(),Gg=nr(),Yg=ce(),Wg=Ue(),Sn=Yg("iterator"),Ic=!1,at,mn,bn;[].keys&&(bn=[].keys(),"next"in bn?(mn=Tc(Tc(bn)),mn!==Object.prototype&&(at=mn)):Ic=!0);var Qg=!Hg(at)||qg(function(){var i={};return at[Sn].call(i)!==i});Qg?at={}:Wg&&(at=jg(at));Ug(at[Sn])||Gg(at,Sn,function(){return this});Ec.exports={IteratorPrototype:at,BUGGY_SAFARI_ITERATORS:Ic}});var Ta=m((Sw,Pc)=>{"use strict";var zg=ce(),Kg=zg("toStringTag"),xc={};xc[Kg]="z";Pc.exports=String(xc)==="[object z]"});var or=m((gw,wc)=>{"use strict";var Jg=Ta(),Xg=ee(),Ia=er(),Zg=ce(),ev=Zg("toStringTag"),tv=Object,rv=Ia(function(){return arguments}())=="Arguments",iv=function(i,e){try{return i[e]}catch{}};wc.exports=Jg?Ia:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=iv(e=tv(i),ev))=="string"?t:rv?Ia(e):(r=Ia(e))=="Object"&&Xg(e.callee)?"Arguments":r}});var kc=m((vw,Ac)=>{"use strict";var av=Ta(),sv=or();Ac.exports=av?{}.toString:function(){return"[object "+sv(this)+"]"}});var Ea=m((yw,Lc)=>{"use strict";var nv=Ta(),ov=$t().f,uv=Ct(),lv=He(),cv=kc(),dv=ce(),Rc=dv("toStringTag");Lc.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;lv(a,Rc)||ov(a,Rc,{configurable:!0,value:e}),r&&!nv&&uv(a,"toString",cv)}}});var Cc=m((Tw,$c)=>{"use strict";var pv=gn().IteratorPrototype,hv=pn(),fv=Vr(),mv=Ea(),bv=Lt(),Sv=function(){return this};$c.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=hv(pv,{next:fv(+!r,t)}),mv(i,a,!1,!0),bv[a]=Sv,i}});var Dc=m((Iw,Mc)=>{"use strict";var gv=me(),vv=it();Mc.exports=function(i,e,t){try{return gv(vv(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Bc=m((Ew,Oc)=>{"use strict";var yv=ee(),Tv=String,Iv=TypeError;Oc.exports=function(i){if(typeof i=="object"||yv(i))return i;throw Iv("Can't set "+Tv(i)+" as a prototype")}});var vn=m((xw,Vc)=>{"use strict";var Ev=Dc(),xv=Fe(),Pv=Bc();Vc.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Ev(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return xv(a),Pv(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var Qc=m((Pw,Wc)=>{"use strict";var wv=$e(),Av=be(),xa=Ue(),Gc=Ul(),kv=ee(),Rv=Cc(),_c=fn(),Nc=vn(),Lv=Ea(),$v=Ct(),yn=nr(),Cv=ce(),Fc=Lt(),Yc=gn(),Mv=Gc.PROPER,Dv=Gc.CONFIGURABLE,qc=Yc.IteratorPrototype,Pa=Yc.BUGGY_SAFARI_ITERATORS,qr=Cv("iterator"),Uc="keys",Ur="values",Hc="entries",jc=function(){return this};Wc.exports=function(i,e,t,r,a,s,n){Rv(t,e,r);var o=function(I){if(I===a&&p)return p;if(!Pa&&I in c)return c[I];switch(I){case Uc:return function(){return new t(this,I)};case Ur:return function(){return new t(this,I)};case Hc:return function(){return new t(this,I)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[qr]||c["@@iterator"]||a&&c[a],p=!Pa&&d||o(a),f=e=="Array"&&c.entries||d,b,S,T;if(f&&(b=_c(f.call(new i)),b!==Object.prototype&&b.next&&(!xa&&_c(b)!==qc&&(Nc?Nc(b,qc):kv(b[qr])||yn(b,qr,jc)),Lv(b,l,!0,!0),xa&&(Fc[l]=jc))),Mv&&a==Ur&&d&&d.name!==Ur&&(!xa&&Dv?$v(c,"name",Ur):(u=!0,p=function(){return Av(d,this)})),a)if(S={values:o(Ur),keys:s?p:o(Uc),entries:o(Hc)},n)for(T in S)(Pa||u||!(T in c))&&yn(c,T,S[T]);else wv({target:e,proto:!0,forced:Pa||u},S);return(!xa||n)&&c[qr]!==p&&yn(c,qr,p,{name:a}),Fc[e]=p,S}});var Kc=m((ww,zc)=>{"use strict";zc.exports=function(i,e){return{value:i,done:e}}});var In=m((Aw,td)=>{"use strict";var Ov=rr(),Tn=ws(),Jc=Lt(),Zc=Xs(),Bv=$t().f,Vv=Qc(),wa=Kc(),_v=Ue(),Nv=Ke(),ed="Array Iterator",Fv=Zc.set,qv=Zc.getterFor(ed);td.exports=Vv(Array,"Array",function(i,e){Fv(this,{type:ed,target:Ov(i),index:0,kind:e})},function(){var i=qv(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,wa(void 0,!0)):t=="keys"?wa(r,!1):t=="values"?wa(e[r],!1):wa([r,e[r]],!1)},"values");var Xc=Jc.Arguments=Jc.Array;Tn("keys");Tn("values");Tn("entries");if(!_v&&Nv&&Xc.name!=="values")try{Bv(Xc,"name",{value:"values"})}catch{}});var id=m((kw,rd)=>{"use strict";var Uv=ce(),Hv=Lt(),jv=Uv("iterator"),Gv=Array.prototype;rd.exports=function(i){return i!==void 0&&(Hv.Array===i||Gv[jv]===i)}});var En=m((Rw,sd)=>{"use strict";var Yv=or(),ad=Or(),Wv=tr(),Qv=Lt(),zv=ce(),Kv=zv("iterator");sd.exports=function(i){if(!Wv(i))return ad(i,Kv)||ad(i,"@@iterator")||Qv[Yv(i)]}});var od=m((Lw,nd)=>{"use strict";var Jv=be(),Xv=it(),Zv=Fe(),ey=Dr(),ty=En(),ry=TypeError;nd.exports=function(i,e){var t=arguments.length<2?ty(i):e;if(Xv(t))return Zv(Jv(t,i));throw ry(ey(i)+" is not iterable")}});var cd=m(($w,ld)=>{"use strict";var iy=be(),ud=Fe(),ay=Or();ld.exports=function(i,e,t){var r,a;ud(i);try{if(r=ay(i,"return"),!r){if(e==="throw")throw t;return t}r=iy(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return ud(r),t}});var ka=m((Cw,fd)=>{"use strict";var sy=Fr(),ny=be(),oy=Fe(),uy=Dr(),ly=id(),cy=ga(),dd=Cr(),dy=od(),py=En(),pd=cd(),hy=TypeError,Aa=function(i,e){this.stopped=i,this.result=e},hd=Aa.prototype;fd.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),l=sy(e,r),u,c,d,p,f,b,S,T=function(C){return u&&pd(u,"normal",C),new Aa(!0,C)},I=function(C){return a?(oy(C),o?l(C[0],C[1],T):l(C[0],C[1])):o?l(C,T):l(C)};if(s)u=i.iterator;else if(n)u=i;else{if(c=py(i),!c)throw hy(uy(i)+" is not iterable");if(ly(c)){for(d=0,p=cy(i);p>d;d++)if(f=I(i[d]),f&&dd(hd,f))return f;return new Aa(!1)}u=dy(i,c)}for(b=s?i.next:u.next;!(S=ny(b,u)).done;){try{f=I(S.value)}catch(C){pd(u,"throw",C)}if(typeof f=="object"&&f&&dd(hd,f))return f}return new Aa(!1)}});var bd=m((Mw,md)=>{"use strict";var fy=ca(),my=$t(),by=Vr();md.exports=function(i,e,t){var r=fy(e);r in i?my.f(i,r,by(0,t)):i[r]=t}});var Sd=m(()=>{"use strict";var Sy=$e(),gy=ka(),vy=bd();Sy({target:"Object",stat:!0},{fromEntries:function(e){var t={};return gy(e,function(r,a){vy(t,r,a)},{AS_ENTRIES:!0}),t}})});var vd=m((Bw,gd)=>{"use strict";In();Sd();var yy=oa();gd.exports=yy.Object.fromEntries});var Td=m((Vw,yd)=>{"use strict";yd.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var xd=m(()=>{"use strict";In();var Ty=Td(),Iy=ne(),Ey=or(),xy=Ct(),Id=Lt(),Py=ce(),Ed=Py("toStringTag");for(Ra in Ty)xn=Iy[Ra],La=xn&&xn.prototype,La&&Ey(La)!==Ed&&xy(La,Ed,Ra),Id[Ra]=Id.Array;var xn,La,Ra});var wd=m((Fw,Pd)=>{"use strict";var wy=vd();xd();Pd.exports=wy});var Pn=m((qw,Ad)=>{"use strict";var Ay=wd();Ad.exports=Ay});var kd=m(()=>{"use strict"});var Hr=m((jw,Rd)=>{"use strict";var ky=er();Rd.exports=typeof process<"u"&&ky(process)=="process"});var $d=m((Gw,Ld)=>{"use strict";var Ry=$t();Ld.exports=function(i,e,t){return Ry.f(i,e,t)}});var Dd=m((Yw,Md)=>{"use strict";var Ly=rt(),$y=$d(),Cy=ce(),My=Ke(),Cd=Cy("species");Md.exports=function(i){var e=Ly(i);My&&e&&!e[Cd]&&$y(e,Cd,{configurable:!0,get:function(){return this}})}});var Bd=m((Ww,Od)=>{"use strict";var Dy=Cr(),Oy=TypeError;Od.exports=function(i,e){if(Dy(e,i))return i;throw Oy("Incorrect invocation")}});var An=m((Qw,Vd)=>{"use strict";var By=me(),Vy=ee(),wn=la(),_y=By(Function.toString);Vy(wn.inspectSource)||(wn.inspectSource=function(i){return _y(i)});Vd.exports=wn.inspectSource});var Hd=m((zw,Ud)=>{"use strict";var Ny=me(),Fy=Ae(),_d=ee(),qy=or(),Uy=rt(),Hy=An(),Nd=function(){},jy=[],Fd=Uy("Reflect","construct"),kn=/^\s*(?:class|function)\b/,Gy=Ny(kn.exec),Yy=!kn.exec(Nd),jr=function(e){if(!_d(e))return!1;try{return Fd(Nd,jy,e),!0}catch{return!1}},qd=function(e){if(!_d(e))return!1;switch(qy(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Yy||!!Gy(kn,Hy(e))}catch{return!0}};qd.sham=!0;Ud.exports=!Fd||Fy(function(){var i;return jr(jr.call)||!jr(Object)||!jr(function(){i=!0})||i})?qd:jr});var Gd=m((Kw,jd)=>{"use strict";var Wy=Hd(),Qy=Dr(),zy=TypeError;jd.exports=function(i){if(Wy(i))return i;throw zy(Qy(i)+" is not a constructor")}});var Rn=m((Jw,Wd)=>{"use strict";var Yd=Fe(),Ky=Gd(),Jy=tr(),Xy=ce(),Zy=Xy("species");Wd.exports=function(i,e){var t=Yd(i).constructor,r;return t===void 0||Jy(r=Yd(t)[Zy])?e:Ky(r)}});var zd=m((Xw,Qd)=>{"use strict";var eT=me();Qd.exports=eT([].slice)});var Jd=m((Zw,Kd)=>{"use strict";var tT=TypeError;Kd.exports=function(i,e){if(i<e)throw tT("Not enough arguments");return i}});var Ln=m((eA,Xd)=>{"use strict";var rT=Mr();Xd.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(rT)});var Nn=m((tA,op)=>{"use strict";var ke=ne(),iT=Zs(),aT=Fr(),Zd=ee(),sT=He(),np=Ae(),ep=un(),nT=zd(),tp=sa(),oT=Jd(),uT=Ln(),lT=Hr(),Bn=ke.setImmediate,Vn=ke.clearImmediate,cT=ke.process,$n=ke.Dispatch,dT=ke.Function,rp=ke.MessageChannel,pT=ke.String,Cn=0,Gr={},ip="onreadystatechange",Yr,Dt,Mn,Dn;np(function(){Yr=ke.location});var _n=function(i){if(sT(Gr,i)){var e=Gr[i];delete Gr[i],e()}},On=function(i){return function(){_n(i)}},ap=function(i){_n(i.data)},sp=function(i){ke.postMessage(pT(i),Yr.protocol+"//"+Yr.host)};(!Bn||!Vn)&&(Bn=function(e){oT(arguments.length,1);var t=Zd(e)?e:dT(e),r=nT(arguments,1);return Gr[++Cn]=function(){iT(t,void 0,r)},Dt(Cn),Cn},Vn=function(e){delete Gr[e]},lT?Dt=function(i){cT.nextTick(On(i))}:$n&&$n.now?Dt=function(i){$n.now(On(i))}:rp&&!uT?(Mn=new rp,Dn=Mn.port2,Mn.port1.onmessage=ap,Dt=aT(Dn.postMessage,Dn)):ke.addEventListener&&Zd(ke.postMessage)&&!ke.importScripts&&Yr&&Yr.protocol!=="file:"&&!np(sp)?(Dt=sp,ke.addEventListener("message",ap,!1)):ip in tp("script")?Dt=function(i){ep.appendChild(tp("script"))[ip]=function(){ep.removeChild(this),_n(i)}}:Dt=function(i){setTimeout(On(i),0)});op.exports={set:Bn,clear:Vn}});var Fn=m((rA,lp)=>{"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}}};lp.exports=up});var dp=m((iA,cp)=>{"use strict";var hT=Mr();cp.exports=/ipad|iphone|ipod/i.test(hT)&&typeof Pebble<"u"});var hp=m((aA,pp)=>{"use strict";var fT=Mr();pp.exports=/web0s(?!.*chrome)/i.test(fT)});var Tp=m((sA,yp)=>{"use strict";var Ot=ne(),fp=Fr(),mT=tn().f,qn=Nn().set,bT=Fn(),ST=Ln(),gT=dp(),vT=hp(),Un=Hr(),mp=Ot.MutationObserver||Ot.WebKitMutationObserver,bp=Ot.document,Sp=Ot.process,$a=Ot.Promise,gp=mT(Ot,"queueMicrotask"),Gn=gp&&gp.value,ur,Hn,jn,Ca,vp;Gn||(Wr=new bT,Qr=function(){var i,e;for(Un&&(i=Sp.domain)&&i.exit();e=Wr.get();)try{e()}catch(t){throw Wr.head&&ur(),t}i&&i.enter()},!ST&&!Un&&!vT&&mp&&bp?(Hn=!0,jn=bp.createTextNode(""),new mp(Qr).observe(jn,{characterData:!0}),ur=function(){jn.data=Hn=!Hn}):!gT&&$a&&$a.resolve?(Ca=$a.resolve(void 0),Ca.constructor=$a,vp=fp(Ca.then,Ca),ur=function(){vp(Qr)}):Un?ur=function(){Sp.nextTick(Qr)}:(qn=fp(qn,Ot),ur=function(){qn(Qr)}),Gn=function(i){Wr.head||ur(),Wr.add(i)});var Wr,Qr;yp.exports=Gn});var Ep=m((nA,Ip)=>{"use strict";Ip.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch{}}});var Ma=m((oA,xp)=>{"use strict";xp.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Bt=m((uA,Pp)=>{"use strict";var yT=ne();Pp.exports=yT.Promise});var Yn=m((lA,wp)=>{"use strict";wp.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var kp=m((cA,Ap)=>{"use strict";var TT=Yn(),IT=Hr();Ap.exports=!TT&&!IT&&typeof window=="object"&&typeof document=="object"});var lr=m((dA,$p)=>{"use strict";var ET=ne(),zr=Bt(),xT=ee(),PT=rn(),wT=An(),AT=ce(),kT=kp(),RT=Yn(),LT=Ue(),Wn=Os(),Rp=zr&&zr.prototype,$T=AT("species"),Qn=!1,Lp=xT(ET.PromiseRejectionEvent),CT=PT("Promise",function(){var i=wT(zr),e=i!==String(zr);if(!e&&Wn===66||LT&&!(Rp.catch&&Rp.finally))return!0;if(!Wn||Wn<51||!/native code/.test(i)){var t=new zr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[$T]=r,Qn=t.then(function(){})instanceof r,!Qn)return!0}return!e&&(kT||RT)&&!Lp});$p.exports={CONSTRUCTOR:CT,REJECTION_EVENT:Lp,SUBCLASSING:Qn}});var cr=m((pA,Mp)=>{"use strict";var Cp=it(),MT=TypeError,DT=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw MT("Bad Promise constructor");e=r,t=a}),this.resolve=Cp(e),this.reject=Cp(t)};Mp.exports.f=function(i){return new DT(i)}});var Xp=m(()=>{"use strict";var OT=$e(),BT=Ue(),Va=Hr(),vt=ne(),fr=be(),Dp=nr(),Op=vn(),VT=Ea(),_T=Dd(),NT=it(),Ba=ee(),FT=ze(),qT=Bd(),UT=Rn(),Fp=Nn().set,Zn=Tp(),HT=Ep(),jT=Ma(),GT=Fn(),qp=Xs(),_a=Bt(),eo=lr(),Up=cr(),Na="Promise",Hp=eo.CONSTRUCTOR,YT=eo.REJECTION_EVENT,WT=eo.SUBCLASSING,zn=qp.getterFor(Na),QT=qp.set,dr=_a&&_a.prototype,Vt=_a,Da=dr,jp=vt.TypeError,Kn=vt.document,to=vt.process,Jn=Up.f,zT=Jn,KT=!!(Kn&&Kn.createEvent&&vt.dispatchEvent),Gp="unhandledrejection",JT="rejectionhandled",Bp=0,Yp=1,XT=2,ro=1,Wp=2,Oa,Vp,ZT,_p,Qp=function(i){var e;return FT(i)&&Ba(e=i.then)?e:!1},zp=function(i,e){var t=e.value,r=e.state==Yp,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===Wp&&tI(e),e.rejection=ro),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(jp("Promise-chain cycle")):(u=Qp(l))?fr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Kp=function(i,e){i.notified||(i.notified=!0,Zn(function(){for(var t=i.reactions,r;r=t.get();)zp(r,i);i.notified=!1,e&&!i.rejection&&eI(i)}))},Jp=function(i,e,t){var r,a;KT?(r=Kn.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),vt.dispatchEvent(r)):r={promise:e,reason:t},!YT&&(a=vt["on"+i])?a(r):i===Gp&&HT("Unhandled promise rejection",t)},eI=function(i){fr(Fp,vt,function(){var e=i.facade,t=i.value,r=Np(i),a;if(r&&(a=jT(function(){Va?to.emit("unhandledRejection",t,e):Jp(Gp,e,t)}),i.rejection=Va||Np(i)?Wp:ro,a.error))throw a.value})},Np=function(i){return i.rejection!==ro&&!i.parent},tI=function(i){fr(Fp,vt,function(){var e=i.facade;Va?to.emit("rejectionHandled",e):Jp(JT,e,i.value)})},pr=function(i,e,t){return function(r){i(e,r,t)}},hr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=XT,Kp(i,!0))},Xn=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw jp("Promise can't be resolved itself");var r=Qp(e);r?Zn(function(){var a={done:!1};try{fr(r,e,pr(Xn,a,i),pr(hr,a,i))}catch(s){hr(a,s,i)}}):(i.value=e,i.state=Yp,Kp(i,!1))}catch(a){hr({done:!1},a,i)}}};if(Hp&&(Vt=function(e){qT(this,Da),NT(e),fr(Oa,this);var t=zn(this);try{e(pr(Xn,t),pr(hr,t))}catch(r){hr(t,r)}},Da=Vt.prototype,Oa=function(e){QT(this,{type:Na,done:!1,notified:!1,parent:!1,reactions:new GT,rejection:!1,state:Bp,value:void 0})},Oa.prototype=Dp(Da,"then",function(e,t){var r=zn(this),a=Jn(UT(this,Vt));return r.parent=!0,a.ok=Ba(e)?e:!0,a.fail=Ba(t)&&t,a.domain=Va?to.domain:void 0,r.state==Bp?r.reactions.add(a):Zn(function(){zp(a,r)}),a.promise}),Vp=function(){var i=new Oa,e=zn(i);this.promise=i,this.resolve=pr(Xn,e),this.reject=pr(hr,e)},Up.f=Jn=function(i){return i===Vt||i===ZT?new Vp(i):zT(i)},!BT&&Ba(_a)&&dr!==Object.prototype)){_p=dr.then,WT||Dp(dr,"then",function(e,t){var r=this;return new Vt(function(a,s){fr(_p,r,a,s)}).then(e,t)},{unsafe:!0});try{delete dr.constructor}catch{}Op&&Op(dr,Da)}OT({global:!0,constructor:!0,wrap:!0,forced:Hp},{Promise:Vt});VT(Vt,Na,!1,!0);_T(Na)});var ih=m((mA,rh)=>{"use strict";var rI=ce(),eh=rI("iterator"),th=!1;try{Zp=0,io={next:function(){return{done:!!Zp++}},return:function(){th=!0}},io[eh]=function(){return this},Array.from(io,function(){throw 2})}catch{}var Zp,io;rh.exports=function(i,e){if(!e&&!th)return!1;var t=!1;try{var r={};r[eh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var ao=m((bA,ah)=>{"use strict";var iI=Bt(),aI=ih(),sI=lr().CONSTRUCTOR;ah.exports=sI||!aI(function(i){iI.all(i).then(void 0,function(){})})});var sh=m(()=>{"use strict";var nI=$e(),oI=be(),uI=it(),lI=cr(),cI=Ma(),dI=ka(),pI=ao();nI({target:"Promise",stat:!0,forced:pI},{all:function(e){var t=this,r=lI.f(t),a=r.resolve,s=r.reject,n=cI(function(){var o=uI(t.resolve),l=[],u=0,c=1;dI(e,function(d){var p=u++,f=!1;c++,oI(o,t,d).then(function(b){f||(f=!0,l[p]=b,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var oh=m(()=>{"use strict";var hI=$e(),fI=Ue(),mI=lr().CONSTRUCTOR,no=Bt(),bI=rt(),SI=ee(),gI=nr(),nh=no&&no.prototype;hI({target:"Promise",proto:!0,forced:mI,real:!0},{catch:function(i){return this.then(void 0,i)}});!fI&&SI(no)&&(so=bI("Promise").prototype.catch,nh.catch!==so&&gI(nh,"catch",so,{unsafe:!0}));var so});var uh=m(()=>{"use strict";var vI=$e(),yI=be(),TI=it(),II=cr(),EI=Ma(),xI=ka(),PI=ao();vI({target:"Promise",stat:!0,forced:PI},{race:function(e){var t=this,r=II.f(t),a=r.reject,s=EI(function(){var n=TI(t.resolve);xI(e,function(o){yI(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var lh=m(()=>{"use strict";var wI=$e(),AI=be(),kI=cr(),RI=lr().CONSTRUCTOR;wI({target:"Promise",stat:!0,forced:RI},{reject:function(e){var t=kI.f(this);return AI(t.reject,void 0,e),t.promise}})});var oo=m((PA,ch)=>{"use strict";var LI=Fe(),$I=ze(),CI=cr();ch.exports=function(i,e){if(LI(i),$I(e)&&e.constructor===i)return e;var t=CI.f(i),r=t.resolve;return r(e),t.promise}});var hh=m(()=>{"use strict";var MI=$e(),DI=rt(),dh=Ue(),OI=Bt(),ph=lr().CONSTRUCTOR,BI=oo(),VI=DI("Promise"),_I=dh&&!ph;MI({target:"Promise",stat:!0,forced:dh||ph},{resolve:function(e){return BI(_I&&this===VI?OI:this,e)}})});var fh=m(()=>{"use strict";Xp();sh();oh();uh();lh();hh()});var gh=m(()=>{"use strict";var NI=$e(),FI=Ue(),Fa=Bt(),qI=Ae(),bh=rt(),Sh=ee(),UI=Rn(),mh=oo(),HI=nr(),lo=Fa&&Fa.prototype,jI=!!Fa&&qI(function(){lo.finally.call({then:function(){}},function(){})});NI({target:"Promise",proto:!0,real:!0,forced:jI},{finally:function(i){var e=UI(this,bh("Promise")),t=Sh(i);return this.then(t?function(r){return mh(e,i()).then(function(){return r})}:i,t?function(r){return mh(e,i()).then(function(){throw r})}:i)}});!FI&&Sh(Fa)&&(uo=bh("Promise").prototype.finally,lo.finally!==uo&&HI(lo,"finally",uo,{unsafe:!0}));var uo});var qa=m((CA,vh)=>{"use strict";var GI=rt();vh.exports=GI});var Th=m((MA,yh)=>{"use strict";kd();fh();gh();var YI=qa();yh.exports=YI("Promise","finally")});var Eh=m((DA,Ih)=>{"use strict";var WI=Th();Ih.exports=WI});var Ua=m((OA,xh)=>{"use strict";var QI=Eh();xh.exports=QI});var Dh=m(()=>{"use strict";var rE=$e(),iE=Br(),aE=ga(),sE=Sa(),nE=ws();rE({target:"Array",proto:!0},{at:function(e){var t=iE(this),r=aE(t),a=sE(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});nE("at")});var Bh=m((Mk,Oh)=>{"use strict";Dh();var oE=qa();Oh.exports=oE("Array","at")});var _h=m((Dk,Vh)=>{"use strict";var uE=Bh();Vh.exports=uE});var Jr=m((Ok,Nh)=>{"use strict";var lE=_h();Nh.exports=lE});var gf=m(()=>{"use strict"});var vf=m(()=>{"use strict"});var Tf=m((xC,yf)=>{"use strict";var YE=ze(),WE=er(),QE=ce(),zE=QE("match");yf.exports=function(i){var e;return YE(i)&&((e=i[zE])!==void 0?!!e:WE(i)=="RegExp")}});var Ef=m((PC,If)=>{"use strict";var KE=or(),JE=String;If.exports=function(i){if(KE(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return JE(i)}});var Pf=m((wC,xf)=>{"use strict";var XE=Fe();xf.exports=function(){var i=XE(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var kf=m((AC,Af)=>{"use strict";var ZE=be(),ex=He(),tx=Cr(),rx=Pf(),wf=RegExp.prototype;Af.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in wf)&&!ex(i,"flags")&&tx(wf,i)?ZE(rx,i):e}});var Lf=m((kC,Rf)=>{"use strict";var Do=me(),ix=Br(),ax=Math.floor,Co=Do("".charAt),sx=Do("".replace),Mo=Do("".slice),nx=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,ox=/\$([$&'`]|\d{1,2})/g;Rf.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=ox;return a!==void 0&&(a=ix(a),l=nx),sx(s,l,function(u,c){var d;switch(Co(c,0)){case"$":return"$";case"&":return i;case"`":return Mo(e,0,t);case"'":return Mo(e,n);case"<":d=a[Mo(c,1,-1)];break;default:var p=+c;if(p===0)return u;if(p>o){var f=ax(p/10);return f===0?u:f<=o?r[f-1]===void 0?Co(c,1):r[f-1]+Co(c,1):u}d=r[p-1]}return d===void 0?"":d})}});var Of=m(()=>{"use strict";var ux=$e(),lx=be(),Oo=me(),$f=ia(),cx=ee(),dx=tr(),px=Tf(),Er=Ef(),hx=Or(),fx=kf(),mx=Lf(),bx=ce(),Sx=Ue(),gx=bx("replace"),vx=TypeError,Df=Oo("".indexOf),yx=Oo("".replace),Cf=Oo("".slice),Tx=Math.max,Mf=function(i,e,t){return t>i.length?-1:e===""?t:Df(i,e,t)};ux({target:"String",proto:!0},{replaceAll:function(e,t){var r=$f(this),a,s,n,o,l,u,c,d,p,f=0,b=0,S="";if(!dx(e)){if(a=px(e),a&&(s=Er($f(fx(e))),!~Df(s,"g")))throw vx("`.replaceAll` does not allow non-global regexes");if(n=hx(e,gx),n)return lx(n,e,r,t);if(Sx&&a)return yx(Er(r),e,t)}for(o=Er(r),l=Er(e),u=cx(t),u||(t=Er(t)),c=l.length,d=Tx(1,c),f=Mf(o,l,0);f!==-1;)p=u?Er(t(l,f,o)):mx(l,o,f,[],void 0,t),S+=Cf(o,b,f)+p,b=f+c,f=Mf(o,l,f+d);return b<o.length&&(S+=Cf(o,b)),S}})});var Vf=m(($C,Bf)=>{"use strict";gf();vf();Of();var Ix=qa();Bf.exports=Ix("String","replaceAll")});var Nf=m((CC,_f)=>{"use strict";var Ex=Vf();_f.exports=Ex});var qf=m((MC,Ff)=>{"use strict";var xx=Nf();Ff.exports=xx});var Nx={};Dm(Nx,{ChromecastState:()=>Lr,HttpConnectionType:()=>ea,Observable:()=>et.Observable,PlaybackState:()=>pe,Player:()=>Wi,SDK_VERSION:()=>_x,Subject:()=>et.Subject,Subscription:()=>et.Subscription,Surface:()=>ta,VERSION:()=>Es,ValueSubject:()=>et.ValueSubject,VideoFormat:()=>tt,VideoQuality:()=>et.VideoQuality});module.exports=Om(Nx);var Es="2.0.106-beta.1";var pe=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(pe||{}),tt=(B=>(B.MPEG="MPEG",B.DASH="DASH",B.DASH_SEP="DASH_SEP",B.DASH_SEP_VK="DASH_SEP",B.DASH_WEBM="DASH_WEBM",B.DASH_WEBM_AV1="DASH_WEBM_AV1",B.DASH_STREAMS="DASH_STREAMS",B.DASH_WEBM_VK="DASH_WEBM",B.DASH_ONDEMAND="DASH_ONDEMAND",B.DASH_ONDEMAND_VK="DASH_ONDEMAND",B.DASH_LIVE="DASH_LIVE",B.DASH_LIVE_CMAF="DASH_LIVE_CMAF",B.DASH_LIVE_WEBM="DASH_LIVE_WEBM",B.HLS="HLS",B.HLS_ONDEMAND="HLS_ONDEMAND",B.HLS_JS="HLS",B.HLS_LIVE="HLS_LIVE",B.HLS_LIVE_CMAF="HLS_LIVE_CMAF",B.WEB_RTC_LIVE="WEB_RTC_LIVE",B))(tt||{});var Lr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Lr||{}),ea=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ea||{});var ta=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ta||{});var N=require("@vkontakte/videoplayer-shared");var Jo=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 ra=class{constructor(e){this.connection$=new N.ValueSubject(void 0);this.castState$=new N.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new N.Subject;this.realCastState$=new N.ValueSubject("NOT_AVAILABLE");this.subscription=new N.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,N.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Jo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:N.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,N.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,N.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,N.assertNever)(a.sessionState)}})).add((0,N.merge)((0,N.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,N.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,N.map)(a=>a.castState)),(0,N.observableFrom)([r.getCastState()])).pipe((0,N.filterChanged)(),(0,N.map)(Bm),(0,N.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,N.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();(0,N.assertNonNullable)(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;((0,N.isNullable)(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?(0,N.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:N.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Bm=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,N.assertNever)(i)}};var lm=Ne(Pn(),1);var kh=Ne(Ua(),1);var co=require("@vkontakte/videoplayer-shared");var de=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,co.assertNever)(t)}return i},po=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:(0,co.assertNever)(e)}};var P=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};var Je=require("@vkontakte/videoplayer-shared"),q=class{constructor(e){this.transitionStarted$=new Je.Subject;this.transitionEnded$=new Je.Subject;this.transitionUpdated$=new Je.Subject;this.forceChanged$=new Je.Subject;this.stateChangeStarted$=(0,Je.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Je.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,Je.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Ph=require("@vkontakte/videoplayer-shared"),wh=i=>{switch(i){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Ph.assertNever)(i)}};var L=require("@vkontakte/videoplayer-shared");var zI=5,KI=5,JI=500,Ah=7e3,Kr=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.Subscription;this.videoState=new q("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}default:(0,L.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(wh(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new L.Subscription;this.subscription.add(e),this.subscription.add((0,L.merge)(this.videoState.stateChangeStarted$.pipe((0,L.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,L.map)(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new L.Subject;e.add(a.pipe((0,L.debounce)(JI)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>zI)&&a.next(o),s=o})),e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<KI&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,L.assertNever)(n)}}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=(0,L.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,L.observableFrom)(["init"])).pipe((0,L.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];(0,L.assertNonNullable)(u);let c=(0,L.getHighestQuality)(Object.keys(u));(0,L.assertNonNullable)(c);let d=u[c];(0,L.assertNonNullable)(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];(0,L.assertNonNullable)(u),r=u.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let u=t[e];(0,L.assertNonNullable)(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];(0,L.assertNonNullable)(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];(0,L.assertNonNullable)(u),r=de(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.ErrorCategory.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,L.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:l}=this.params.meta;return(0,L.isNonNullable)(o)&&(n.metadata.title=o),(0,L.isNonNullable)(l)&&(n.metadata.subtitle=l),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add((0,L.timeout)(Ah).subscribe(()=>s(`timeout(${Ah})`)))});(0,kh.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var bo=require("@vkontakte/videoplayer-shared");var Rh=require("@vkontakte/videoplayer-shared"),Lh=i=>{try{i.pause(),i.playbackRate=0,(0,Rh.clearVideoElement)(i),i.remove()}catch(e){console.error(e)}};var Ha=require("@vkontakte/videoplayer-shared"),ho=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},fo=window.WeakMap?new WeakMap:new ho,mo=window.WeakMap?new WeakMap:new Map,XI=(i,e=20)=>{let t=0;return(0,Ha.fromEvent)(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},Se=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?(0,bo.clearVideoElement)(t):(t=document.createElement("video"),i.appendChild(t)),fo.set(t,r);let a=new Ha.Subscription;return a.add(XI(t,e)),mo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ge=i=>{mo.get(i)?.unsubscribe(),mo.delete(i);let t=fo.get(i);fo.delete(i),t?(0,bo.clearVideoElement)(i):Lh(i)};var $=require("@vkontakte/videoplayer-shared");var yt=require("@vkontakte/videoplayer-shared"),ja=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=(0,yt.isNullable)(a),u=new yt.Subscription;return a&&u.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),l&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),l&&i.setState(c.to)},s)),u},Xe=(i,e,t)=>ja(e,()=>i.loop,r=>{(0,yt.isNonNullable)(r)&&(i.loop=r)},{onError:t}),ve=(i,e,t,r)=>ja(e,()=>({muted:i.muted,volume:i.volume}),a=>{(0,yt.isNonNullable)(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),Ce=(i,e,t,r)=>ja(e,()=>i.playbackRate,a=>{(0,yt.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),Tt=ja;var ZI=i=>["__",i.language,i.label].join("|"),eE=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},So=class i{constructor(){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:$.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Tt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,$.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Tt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,$.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Tt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:a})),this.subscription.add(Tt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,$.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,$.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,$.filterChanged)()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add((0,$.fromEvent)(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;(0,$.isNonNullable)(t.align)&&(a.align=t.align),(0,$.isNonNullable)(t.position)&&(a.position=t.position),(0,$.isNonNullable)(t.size)&&(a.size=t.size),(0,$.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:ZI(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!eE(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,$.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,$.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Me=So;var nt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var $h=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},go=i=>{let e=$h(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Ch=i=>{let e=$h(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var k=require("@vkontakte/videoplayer-shared");var tE=3,Mh=(i,e,t=tE)=>{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 ye=i=>{let e=y=>(0,k.fromEvent)(i,y).pipe((0,k.mapTo)(void 0)),r=(0,k.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>(0,k.fromEvent)(i,y))).pipe((0,k.map)(y=>y.type==="ended"?i.readyState<2:i.readyState<3),(0,k.filterChanged)()),a=(0,k.merge)((0,k.fromEvent)(i,"progress"),(0,k.fromEvent)(i,"timeupdate")).pipe((0,k.map)(()=>Mh(i.buffered,i.currentTime))),n=(0,k.getCurrentBrowser)().browser===k.CurrentClientBrowser.Safari?(0,k.combine)({play:e("play").pipe((0,k.once)()),playing:e("playing")}).pipe((0,k.mapTo)(void 0)):e("playing"),o=(0,k.fromEvent)(i,"volumechange").pipe((0,k.map)(()=>({muted:i.muted,volume:i.volume}))),l=(0,k.fromEvent)(i,"ratechange").pipe((0,k.map)(()=>i.playbackRate)),u=(0,k.fromEvent)(i,"error").pipe((0,k.filter)(()=>!!(i.error||i.played.length)),(0,k.map)(()=>{let y=i.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:k.ErrorCategory.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:i.error??void 0}})),c=(0,k.fromEvent)(i,"timeupdate").pipe((0,k.map)(()=>i.currentTime)),d=new k.Subject,p=.3,f;c.subscribe(y=>{i.loop&&(0,k.isNonNullable)(f)&&(0,k.isNonNullable)(y)&&f>=i.duration-p&&y<=p&&d.next(f),f=y});let b=e("pause").pipe((0,k.filter)(()=>!i.error&&f!==i.duration)),S=(0,k.fromEvent)(i,"enterpictureinpicture"),T=(0,k.fromEvent)(i,"leavepictureinpicture"),I=new k.ValueSubject(Ch(i));S.subscribe(()=>I.next(!0)),T.subscribe(()=>I.next(!1));let C=new k.ValueSubject(go(i));return(0,k.fromEvent)(i,"fullscreenchange").pipe((0,k.map)(()=>go(i))).subscribe(C),{playing$:n,pause$:b,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,k.fromEvent)(i,"durationchange").pipe((0,k.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:I,inFullscreen$:C}};var ot=require("@vkontakte/videoplayer-shared"),It=i=>{switch(i){case"mobile":return ot.VideoQuality.Q_144P;case"lowest":return ot.VideoQuality.Q_240P;case"low":return ot.VideoQuality.Q_360P;case"sd":case"medium":return ot.VideoQuality.Q_480P;case"hd":case"high":return ot.VideoQuality.Q_720P;case"fullhd":case"full":return ot.VideoQuality.Q_1080P;case"quadhd":case"quad":return ot.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ot.VideoQuality.Q_2160P}};var yo=Ne(Jr(),1),H=require("@vkontakte/videoplayer-shared");var vo=!1,ut={},Fh=i=>{vo=i},qh=()=>{ut={}},Uh=i=>{i(ut)},Xr=(i,e)=>{vo&&(ut.meta=ut.meta??{},ut.meta[i]=e)},he=class{constructor(e){this.name=e}next(e){if(!vo)return;ut.series=ut.series??{};let t=ut.series[this.name]??[];t.push([Date.now(),e]),ut.series[this.name]=t}};var cE=new he("best_bitrate"),dE=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Ga=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,H.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},pE='Assertion "ABR Tracks is empty array" failed',hE=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{(0,H.assertNotEmptyArray)(i,pE);let p=r.usePixelRatio?window.devicePixelRatio??1:1,f=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},b=f&&(0,H.videoSizeToQuality)(f),S=r.considerPlaybackRate&&(0,H.isNonNullable)(o)?o:1,T=i.filter(A=>!(0,H.isInvariantQuality)(A.quality)).sort((A,W)=>(0,H.isHigher)(A.quality,W.quality)?-1:1),I=(0,yo.default)(T,-1)?.quality,C=(0,yo.default)(T,0)?.quality,B=(0,H.isNullable)(a)||(0,H.isNonNullable)(a.min)&&(0,H.isNonNullable)(a.max)&&(0,H.isLower)(a.max,a.min)||(0,H.isNonNullable)(a.min)&&C&&(0,H.isHigher)(a.min,C)||(0,H.isNonNullable)(a.max)&&I&&(0,H.isLower)(a.max,I),y=S*dE(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),x={},w=T.filter(A=>(b?(0,H.isLower)(A.quality,b):!0)?((0,H.isNonNullable)(t)&&isFinite(t)&&(0,H.isNonNullable)(A.bitrate)?t-s>=A.bitrate*y:!0)?r.lazyQualitySwitch&&(0,H.isNonNullable)(r.minBufferToSwitchUp)&&l&&!(0,H.isInvariantQuality)(l.quality)&&(n??0)<r.minBufferToSwitchUp&&(0,H.isHigher)(A.quality,l.quality)?(x[A.quality]="Buffer",!1):!!c&&(0,H.isHigherOrEqual)(A.quality,c)?(x[A.quality]="DroppedFramesLimit",!1):B||((0,H.isNullable)(a.max)||(0,H.isLowerOrEqual)(A.quality,a.max))&&((0,H.isNullable)(a.min)||(0,H.isHigherOrEqual)(A.quality,a.min))?!0:(x[A.quality]="FitsQualityLimits",!1):(x[A.quality]="FitsThroughput",!1):(x[A.quality]="FitsContainer",!1))[0];w&&w.bitrate&&cE.next(w.bitrate);let _=w??T[Math.ceil((T.length-1)/2)]??i[0];_.quality!==u?.last?.quality&&d({message:`
|
|
6
|
+
"use strict";var bs=Object.create;var Vi=Object.defineProperty;var Ss=Object.getOwnPropertyDescriptor;var gs=Object.getOwnPropertyNames;var vs=Object.getPrototypeOf,ys=Object.prototype.hasOwnProperty;var Ts=(n,e)=>{for(var t in e)Vi(n,t,{get:e[t],enumerable:!0})},qr=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gs(e))!ys.call(n,r)&&r!==t&&Vi(n,r,{get:()=>e[r],enumerable:!(i=Ss(e,r))||i.enumerable});return n};var Is=(n,e,t)=>(t=n!=null?bs(vs(n)):{},qr(e||!n||!n.__esModule?Vi(t,"default",{value:n,enumerable:!0}):t,n)),Es=n=>qr(Vi({},"__esModule",{value:!0}),n);var An={};Ts(An,{ChromecastState:()=>Vt,HttpConnectionType:()=>Bi,Observable:()=>Oe.Observable,PlaybackState:()=>de,Player:()=>Li,SDK_VERSION:()=>Pn,Subject:()=>Oe.Subject,Subscription:()=>Oe.Subscription,Surface:()=>Oi,VERSION:()=>Sr,ValueSubject:()=>Oe.ValueSubject,VideoFormat:()=>_e,VideoQuality:()=>Oe.VideoQuality});module.exports=Es(An);var Sr="2.0.106-dev.1a114cd2.0";var de=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(de||{}),_e=(C=>(C.MPEG="MPEG",C.DASH="DASH",C.DASH_SEP="DASH_SEP",C.DASH_SEP_VK="DASH_SEP",C.DASH_WEBM="DASH_WEBM",C.DASH_WEBM_AV1="DASH_WEBM_AV1",C.DASH_STREAMS="DASH_STREAMS",C.DASH_WEBM_VK="DASH_WEBM",C.DASH_ONDEMAND="DASH_ONDEMAND",C.DASH_ONDEMAND_VK="DASH_ONDEMAND",C.DASH_LIVE="DASH_LIVE",C.DASH_LIVE_CMAF="DASH_LIVE_CMAF",C.DASH_LIVE_WEBM="DASH_LIVE_WEBM",C.HLS="HLS",C.HLS_ONDEMAND="HLS_ONDEMAND",C.HLS_JS="HLS",C.HLS_LIVE="HLS_LIVE",C.HLS_LIVE_CMAF="HLS_LIVE_CMAF",C.WEB_RTC_LIVE="WEB_RTC_LIVE",C))(_e||{});var Vt=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Vt||{}),Bi=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Bi||{});var Oi=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Oi||{});var O=require("@vkontakte/videoplayer-shared");var zr=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 _i=class{constructor(e){this.connection$=new O.ValueSubject(void 0);this.castState$=new O.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new O.Subject;this.realCastState$=new O.ValueSubject("NOT_AVAILABLE");this.subscription=new O.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,O.isNonNullable)(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},r||zr("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:O.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,O.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,O.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,O.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,O.fromEvent)(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(0,O.assertNever)(r.sessionState)}})).add((0,O.merge)((0,O.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,O.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,O.map)(r=>r.castState)),(0,O.observableFrom)([i.getCastState()])).pipe((0,O.filterChanged)(),(0,O.map)(xs),(0,O.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=(0,O.isNonNullable)(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();(0,O.assertNonNullable)(o);let u=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;((0,O.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,O.isNonNullable)(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:O.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},xs=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(0,O.assertNever)(n)}};var gr=require("@vkontakte/videoplayer-shared");var oe=(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:(0,gr.assertNever)(t)}return n},vr=(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:(0,gr.assertNever)(e)}};var E=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};var Ce=require("@vkontakte/videoplayer-shared"),N=class{constructor(e){this.transitionStarted$=new Ce.Subject;this.transitionEnded$=new Ce.Subject;this.transitionUpdated$=new Ce.Subject;this.forceChanged$=new Ce.Subject;this.stateChangeStarted$=(0,Ce.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Ce.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,Ce.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Kr=require("@vkontakte/videoplayer-shared"),Jr=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Kr.assertNever)(n)}};var w=require("@vkontakte/videoplayer-shared");var ks=5,Ps=5,As=500,Xr=7e3,Bt=class{constructor(e){this.subscription=new w.Subscription;this.loadMediaTimeoutSubscription=new w.Subscription;this.videoState=new N("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:(0,w.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,w.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,w.assertNever)(e)}break}default:(0,w.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Jr(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 w.Subscription;this.subscription.add(e),this.subscription.add((0,w.merge)(this.videoState.stateChangeStarted$.pipe((0,w.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,w.map)(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 w.Subject;e.add(r.pipe((0,w.debounce)(As)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,w.fromEvent)(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)>ks)&&r.next(o),a=o})),e.add((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,w.fromEvent)(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(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Ps&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,w.assertNever)(s)}}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,w.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,w.observableFrom)(["init"])).pipe((0,w.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];(0,w.assertNonNullable)(d);let c=(0,w.getHighestQuality)(Object.keys(d));(0,w.assertNonNullable)(c);let l=d[c];(0,w.assertNonNullable)(l),i=l,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];(0,w.assertNonNullable)(d),i=d.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":case"DASH_STREAMS":{let d=t[e];(0,w.assertNonNullable)(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];(0,w.assertNonNullable)(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];(0,w.assertNonNullable)(d),i=oe(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:w.ErrorCategory.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,w.assertNever)(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:u}=this.params.meta;return(0,w.isNonNullable)(o)&&(s.metadata.title=o),(0,w.isNonNullable)(u)&&(s.metadata.subtitle=u),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((0,w.timeout)(Xr).subscribe(()=>a(`timeout(${Xr})`)))});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:w.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Er=require("@vkontakte/videoplayer-shared");var Zr=require("@vkontakte/videoplayer-shared"),ea=n=>{try{n.pause(),n.playbackRate=0,(0,Zr.clearVideoElement)(n),n.remove()}catch(e){console.error(e)}};var Ni=require("@vkontakte/videoplayer-shared"),yr=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)}},Tr=window.WeakMap?new WeakMap:new yr,Ir=window.WeakMap?new WeakMap:new Map,ws=(n,e=20)=>{let t=0;return(0,Ni.fromEvent)(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ce=(n,{audioVideoSyncRate:e})=>{let t=n.querySelector("video"),i=!!t;t?(0,Er.clearVideoElement)(t):(t=document.createElement("video"),n.appendChild(t)),Tr.set(t,i);let r=new Ni.Subscription;return r.add(ws(t,e)),Ir.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},pe=n=>{Ir.get(n)?.unsubscribe(),Ir.delete(n);let t=Tr.get(n);Tr.delete(n),t?(0,Er.clearVideoElement)(n):ea(n)};var L=require("@vkontakte/videoplayer-shared");var Je=require("@vkontakte/videoplayer-shared"),Fi=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=(0,Je.isNullable)(r),d=new Je.Subscription;return r&&d.add(r.subscribe(c=>{let l=n.getState();i(c,l)&&n.setState(c)},a)),i(o,s)||(t(s),u&&n.setState(s)),d.add(n.stateChangeStarted$.subscribe(c=>{t(c.to),u&&n.setState(c.to)},a)),d},Ve=(n,e,t)=>Fi(e,()=>n.loop,i=>{(0,Je.isNonNullable)(i)&&(n.loop=i)},{onError:t}),he=(n,e,t,i)=>Fi(e,()=>({muted:n.muted,volume:n.volume}),r=>{(0,Je.isNonNullable)(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}),Ee=(n,e,t,i)=>Fi(e,()=>n.playbackRate,r=>{(0,Je.isNonNullable)(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Xe=Fi;var Ls=n=>["__",n.language,n.label].join("|"),$s=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},xr=class n{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.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(Xe(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{(0,L.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,s)=>(0,L.isNonNullable)(a)&&(0,L.isNonNullable)(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe((0,L.map)(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(Xe(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{(0,L.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,s)=>(0,L.isNonNullable)(a)&&(0,L.isNonNullable)(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe((0,L.map)(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(Xe(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(Xe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,L.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,L.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,L.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let 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((0,L.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,L.isNonNullable)(t.align)&&(r.align=t.align),(0,L.isNonNullable)(t.position)&&(r.position=t.position),(0,L.isNonNullable)(t.size)&&(r.size=t.size),(0,L.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(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:Ls(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){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!$s(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,L.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,L.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},xe=xr;var Fe=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 ta=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},kr=n=>{let e=ta(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},ia=n=>{let e=ta(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};var P=require("@vkontakte/videoplayer-shared");var Ms=3,ra=(n,e,t=Ms)=>{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 u=a-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=a+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var me=n=>{let e=g=>(0,P.fromEvent)(n,g).pipe((0,P.mapTo)(void 0)),i=(0,P.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>(0,P.fromEvent)(n,g))).pipe((0,P.map)(g=>g.type==="ended"?n.readyState<2:n.readyState<3),(0,P.filterChanged)()),r=(0,P.merge)((0,P.fromEvent)(n,"progress"),(0,P.fromEvent)(n,"timeupdate")).pipe((0,P.map)(()=>ra(n.buffered,n.currentTime))),s=(0,P.getCurrentBrowser)().browser===P.CurrentClientBrowser.Safari?(0,P.combine)({play:e("play").pipe((0,P.once)()),playing:e("playing")}).pipe((0,P.mapTo)(void 0)):e("playing"),o=(0,P.fromEvent)(n,"volumechange").pipe((0,P.map)(()=>({muted:n.muted,volume:n.volume}))),u=(0,P.fromEvent)(n,"ratechange").pipe((0,P.map)(()=>n.playbackRate)),d=(0,P.fromEvent)(n,"error").pipe((0,P.filter)(()=>!!(n.error||n.played.length)),(0,P.map)(()=>{let g=n.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:P.ErrorCategory.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:n.error??void 0}})),c=(0,P.fromEvent)(n,"timeupdate").pipe((0,P.map)(()=>n.currentTime)),l=new P.Subject,h=.3,m;c.subscribe(g=>{n.loop&&(0,P.isNonNullable)(m)&&(0,P.isNonNullable)(g)&&m>=n.duration-h&&g<=h&&l.next(m),m=g});let f=e("pause").pipe((0,P.filter)(()=>!n.error&&m!==n.duration)),v=(0,P.fromEvent)(n,"enterpictureinpicture"),T=(0,P.fromEvent)(n,"leavepictureinpicture"),$=new P.ValueSubject(ia(n));v.subscribe(()=>$.next(!0)),T.subscribe(()=>$.next(!1));let Q=new P.ValueSubject(kr(n));return(0,P.fromEvent)(n,"fullscreenchange").pipe((0,P.map)(()=>kr(n))).subscribe(Q),{playing$:s,pause$:f,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,P.fromEvent)(n,"durationchange").pipe((0,P.map)(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:$,inFullscreen$:Q}};var Ue=require("@vkontakte/videoplayer-shared"),Ze=n=>{switch(n){case"mobile":return Ue.VideoQuality.Q_144P;case"lowest":return Ue.VideoQuality.Q_240P;case"low":return Ue.VideoQuality.Q_360P;case"sd":case"medium":return Ue.VideoQuality.Q_480P;case"hd":case"high":return Ue.VideoQuality.Q_720P;case"fullhd":case"full":return Ue.VideoQuality.Q_1080P;case"quadhd":case"quad":return Ue.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Ue.VideoQuality.Q_2160P}};var U=require("@vkontakte/videoplayer-shared");var Pr=!1,He={},aa=n=>{Pr=n},sa=()=>{He={}},na=n=>{n(He)},Ot=(n,e)=>{Pr&&(He.meta=He.meta??{},He.meta[n]=e)},ue=class{constructor(e){this.name=e}next(e){if(!Pr)return;He.series=He.series??{};let t=He.series[this.name]??[];t.push([Date.now(),e]),He.series[this.name]=t}};var Rs=new ue("best_bitrate"),Ds=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t,Ui=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,U.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Cs='Assertion "ABR Tracks is empty array" failed',Vs=(n,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:c,abrLogger:l})=>{(0,U.assertNotEmptyArray)(n,Cs);let h=i.usePixelRatio?window.devicePixelRatio??1:1,m=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*i.containerSizeFactor,height:e.height*h*i.containerSizeFactor},f=m&&(0,U.videoSizeToQuality)(m),v=i.considerPlaybackRate&&(0,U.isNonNullable)(o)?o:1,T=n.filter(k=>!(0,U.isInvariantQuality)(k.quality)).sort((k,j)=>(0,U.isHigher)(k.quality,j.quality)?-1:1),$=T.at(-1)?.quality,Q=T.at(0)?.quality,C=(0,U.isNullable)(r)||(0,U.isNonNullable)(r.min)&&(0,U.isNonNullable)(r.max)&&(0,U.isLower)(r.max,r.min)||(0,U.isNonNullable)(r.min)&&Q&&(0,U.isHigher)(r.min,Q)||(0,U.isNonNullable)(r.max)&&$&&(0,U.isLower)(r.max,$),g=v*Ds(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),I={},x=T.filter(k=>(f?(0,U.isLower)(k.quality,f):!0)?((0,U.isNonNullable)(t)&&isFinite(t)&&(0,U.isNonNullable)(k.bitrate)?t-a>=k.bitrate*g:!0)?i.lazyQualitySwitch&&(0,U.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,U.isInvariantQuality)(u.quality)&&(s??0)<i.minBufferToSwitchUp&&(0,U.isHigher)(k.quality,u.quality)?(I[k.quality]="Buffer",!1):!!c&&(0,U.isHigherOrEqual)(k.quality,c)?(I[k.quality]="DroppedFramesLimit",!1):C||((0,U.isNullable)(r.max)||(0,U.isLowerOrEqual)(k.quality,r.max))&&((0,U.isNullable)(r.min)||(0,U.isHigherOrEqual)(k.quality,r.min))?!0:(I[k.quality]="FitsQualityLimits",!1):(I[k.quality]="FitsThroughput",!1):(I[k.quality]="FitsContainer",!1))[0];x&&x.bitrate&&Rs.next(x.bitrate);let B=x??T[Math.ceil((T.length-1)/2)]??n[0];B.quality!==d?.last?.quality&&l({message:`
|
|
7
7
|
[available tracks]
|
|
8
|
-
${
|
|
8
|
+
${n.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
10
10
|
|
|
11
11
|
[tuning]
|
|
12
|
-
${Object.entries(
|
|
12
|
+
${Object.entries(i??{}).map(([k,j])=>`${k}: ${j}`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
16
|
+
containerQualityLimit: ${f},
|
|
17
17
|
throughput: ${t},
|
|
18
|
-
reserve: ${
|
|
18
|
+
reserve: ${a},
|
|
19
19
|
playbackRate: ${o},
|
|
20
|
-
playbackRateFactor: ${
|
|
21
|
-
forwardBufferHealth: ${
|
|
22
|
-
bitrateFactor: ${
|
|
23
|
-
minBufferToSwitchUp: ${
|
|
20
|
+
playbackRateFactor: ${v},
|
|
21
|
+
forwardBufferHealth: ${s},
|
|
22
|
+
bitrateFactor: ${g},
|
|
23
|
+
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
24
24
|
droppedVideoMaxQualityLimit: ${c},
|
|
25
|
-
limitsAreInvalid: ${
|
|
26
|
-
maxQualityLimit: ${
|
|
27
|
-
minQualityLimit: ${
|
|
25
|
+
limitsAreInvalid: ${C},
|
|
26
|
+
maxQualityLimit: ${r?.max},
|
|
27
|
+
minQualityLimit: ${r?.min},
|
|
28
28
|
|
|
29
29
|
[limited tracks]
|
|
30
|
-
${Object.entries(
|
|
30
|
+
${Object.entries(I).map(([k,j])=>`${k}: ${j}`).join(`
|
|
31
31
|
`)||"All tracks are available"}
|
|
32
32
|
|
|
33
|
-
[best track] ${
|
|
34
|
-
[selected track] ${
|
|
35
|
-
`});let
|
|
36
|
-
[last selected] ${
|
|
37
|
-
`}),A}return u?.recordSwitch(_),_},Et=hE;var oe=i=>new URL(i).hostname;var O=require("@vkontakte/videoplayer-shared");var Hh=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},Te=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Hh(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Hh(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};var Re=require("@vkontakte/videoplayer-shared");var Ze=require("@vkontakte/videoplayer-shared");function ue(){return(0,Ze.now)()}function To(i){return ue()-i}function Io(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,l=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return l&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function jh(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function mr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,p=!1,f="arraybuffer",b=7e3,S=2e3,T=()=>{if(l)return;(0,Ze.assertNonNullable)(c);let Q=To(c),se;if(Q<S){se=S-Q,setTimeout(T,se);return}S*=2,S>b&&(S=b),n&&n.abort(),n=new a,j()},I=Q=>(s=Q,W),C=Q=>(d=Q,W),B=()=>(f="json",W),y=()=>{if(!l){if(--u>=0){T(),r&&r();return}l=!0,d&&d(),t&&t()}},x=Q=>(p=Q,W),j=()=>{c=ue(),n=new a,n.open("get",i);let Q=0,se,Be=0,Pe=()=>((0,Ze.assertNonNullable)(c),Math.max(c,Math.max(se||0,Be||0)));if(s&&n.addEventListener("progress",R=>{let D=ue();s.updateChunk&&R.loaded>Q&&(s.updateChunk(Pe(),R.loaded-Q),Q=R.loaded,se=D)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(l)return;(0,Ze.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&s){let D=n.response.byteLength-Q;D&&s.updateChunk&&s.updateChunk(Pe(),D)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let R=()=>{(0,Ze.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Be=ue(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=f,n.send(),W},W={withBitrateReporting:I,withParallel:x,withJSONResponse:B,withRetryCount:Q=>(u=Q,W),withRetryInterval:(Q,se)=>((0,Ze.isNonNullable)(Q)&&(S=Q),(0,Ze.isNonNullable)(se)&&(b=se),W),withTimeout:Q=>(o=Q,W),withFinally:C,send:j,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return W}var Zr=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 ei=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ue(),a=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=l=>{e._complete=1,e._responseData=l,e._downloadTime=ue()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=mr(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ue()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ue();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Ya=1e4,Eo=3;var mE=6e4,bE=10,SE=1,gE=500,ti=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 Zr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Io(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=Io(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Re.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{jh(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ei(Eo,Ya,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,c=!1,d=()=>{let y=s&&(!c||c===this.rep);return y||t("Not running!"),y},p=(y,x,j)=>{l&&l.abort(),l=mr(this.urlResolver.resolve(y,!1),x,j,()=>this._retryCallback()).withTimeout(Ya).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Eo).withFinally(()=>{l=null}).send()},f=(y,x,j)=>{(0,Re.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),x,j,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=y=>{let x=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${x}=>${y}`),r.playbackRate=y)},S=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),T()},T=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}let j=ue()-1e4,w=0;for(let Y=0;Y<this.bufferStates.length;Y++){let A=this.bufferStates[Y];y=Math.min(y,A.buf),A.ts<j&&w++}this.bufferStates.splice(0,w),t(`update playback rate; minBuffer=${y} drop=${w} jitter=${this.sourceJitter}`);let _=y-SE;this.sourceJitter>=0?_-=this.sourceJitter/2:this.sourceJitter-=1,_>3?b(1.15):_>1?b(1.1):_>.3?b(1.05):b(1)}},I=y=>{let x,j=()=>x&&x.start?x.start.length:0,w=R=>x.start[R]/1e3,_=R=>x.dur[R]/1e3,Y=R=>x.fragIndex+R,A=(R,D)=>({chunkIdx:Y(R),startTS:w(R),dur:_(R),discontinuity:D}),W=()=>{let R=0;if(x&&x.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ie=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,le=D;this.sourceJitter>1&&(le+=this.sourceJitter-1);let we=x.dur.length-1;for(;we>=0&&(le-=x.dur[we],!(le<=0));--we);R=Math.min(we,x.dur.length-1-ie),R=Math.max(R,0)}return A(R,!0)},Q=R=>{let D=j();if(!(D<=0)){if((0,Re.isNonNullable)(R)){for(let ie=0;ie<D;ie++)if(w(ie)>R)return A(ie)}return W()}},se=R=>{let D=j(),ie=R?R.chunkIdx+1:0,le=ie-x.fragIndex;if(!(D<=0)){if(!R||le<0||le-D>bE)return t(`Resync: offset=${le} bChunks=${D} chunk=`+JSON.stringify(R)),W();if(!(le>=D))return A(ie-x.fragIndex,!1)}},Be=(R,D,ie)=>{u&&u.abort(),u=mr(this.urlResolver.resolve(R,!0,this.lowLatency),D,ie,()=>this._retryCallback()).withTimeout(Ya).withRetryCount(Eo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(R,D)=>{Be(y,ie=>{if(!d())return;x=ie;let le=!!x.lowLatency;le!==this.lowLatency&&S(le);let we=0;for(let We=0;We<x.dur.length;++We)we+=x.dur[We];we>0&&((0,Re.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(we/x.dur.length)),a({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,R(Q(D))},()=>this._handleNetworkError())},nextChunk:se}},C=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),(0,Re.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:x,logger:j}=this.params,w=I(e.jidxUrl),_,Y,A,W,Q=0,se,Be,Pe,R=()=>{se&&(clearTimeout(se),se=void 0);let z=Math.max(gE,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=Q+z,fe=ue(),Ve=Math.min(1e4,ae-fe);Q=fe;let bt=()=>{u||d()&&w.seek(()=>{d()&&(Q=ue(),D(),R())})};Ve>0?se=window.setTimeout(()=>{this.paused?R():bt()},Ve):bt()},D=()=>{let z;for(;z=w.nextChunk(W);)W=z,zt(z);let ae=w.nextChunk(A);if(ae){if(A&&ae.discontinuity){j("Detected discontinuity; restarting playback"),this.paused?R():(C(),this._initPlayerWith(e));return}We(ae)}else R()},ie=(z,ae)=>{if(!d()||!this.sourceBuffer)return;let fe,Ve,bt,Kt=St=>{window.setTimeout(()=>{d()&&ie(z,ae)},St)};if(this.sourceBuffer.updating)j("Source buffer is updating; delaying appendBuffer"),Kt(100);else{let St=ue(),Jt=x.currentTime;!this.paused&&x.buffered.length>1&&Be===Jt&&St-Pe>500&&(j("Stall suspected; trying to fix"),this._fixupStall()),Be!==Jt&&(Be=Jt,Pe=St);let Ar=this._getBufferSizeSec();if(Ar>30)j(`Buffered ${Ar} seconds; delaying appendBuffer`),Kt(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:St,buf:Ar}),T(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(Qi){if(Qi.name==="QuotaExceededError")j("QuotaExceededError; delaying appendBuffer"),bt=this.sourceBuffer.buffered.length,bt!==0&&(fe=this.sourceBuffer.buffered.start(0),Ve=Jt,Ve-fe>4&&this.sourceBuffer.remove(fe,Ve-3)),Kt(1e3);else throw Qi}}},le=()=>{Y&&_&&(j([`Appending chunk, sz=${Y.byteLength}:`,JSON.stringify(A)]),ie(Y,function(){Y=null,D()}))},we=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),We=z=>{d()&&f(we(z),(ae,fe)=>{if(d()){if(fe/=1e3,Y=ae,A=z,n=z.startTS,fe){let Ve=Math.min(10,z.dur/fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ve:Ve}le()}},()=>this._handleNetworkError())},zt=z=>{d()&&((0,Re.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(we(z),!1)))},Pt=z=>{d()&&(e.cachedHeader=z,ie(z,()=>{_=!0,le()}))};s=!0,w.seek(z=>{if(d()){if(Q=ue(),!z){R();return}W=z,!(0,Re.isNullable)(y)||z.startTS>y?We(z):(A=z,D())}},y),e.cachedHeader?Pt(e.cachedHeader):p(e.headerUrl,Pt,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,Re.isNonNullable)(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Re.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Re.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,f,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(f=this._getBufferSizeSec(),b=d/this.bitrate,f>10&&b>.8||f>15&&b>.5||f>20&&b>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(p,f)=>{let b=ue();if(this.chunkRateEstimator.addInterval(p,b,f)){let T=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:b-p,speed:T}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),n=-1/0,o,l=!0,u=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&To(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,p)=>{let f=s.updateChunk(d,p);return f&&u(),f},notifySwitch:d=>{let p=ue();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=mr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ya).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;Te(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))},mE))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var te=require("@vkontakte/videoplayer-shared"),xo=class{constructor(){this.onDroopedVideoFramesLimit$=new te.Subject;this.subscription=new te.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new te.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,te.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,te.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,te.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,te.interval)(this.droppedFramesChecker.checkTime).pipe((0,te.filter)(()=>this.playing),(0,te.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,te.debounce)(this.droppedFramesChecker.checkTime)),r=(0,te.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>(0,te.isLower)(r,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Wa=xo;var Qa=require("@vkontakte/videoplayer-shared"),Gh=require("@vkontakte/videoplayer-shared");var ri=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var vE=(i,e)=>new Qa.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||ri()))},{...r,...e});a.observe(i);let s=(0,Gh.fromEvent)(document,"visibilitychange").pipe((0,Qa.map)(n=>!document.hidden||ri())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),De=vE;var yE=["paused","playing","ready"],TE=["paused","playing","ready"],ii=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new q("stopped");this.representations$=new O.ValueSubject([]);this.textTracksManager=new Me;this.droppedFramesManager=new Wa;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new nt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:O.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=It(a.name)??(0,O.videoSizeToQuality)(a.video),o=a.bitrate/1e3,l={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:l};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,O.isNonNullable)(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(TE.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&yE.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(de(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let 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(de(this.params.source.url,l))}return;default:return(0,O.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ye(this.video);this.subscription.add(this.representations$.pipe((0,O.map)(a=>a.map(({track:s})=>s)),(0,O.filter)(a=>!!a.length),(0,O.once)()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:a}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,O.filterChanged)(),(0,O.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Xe(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ce(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.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(De(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,O.videoQualityToHeight)(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,O.assertNever)(a.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ge(this.video)}createLiveDashPlayer(){let e=new ti({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&(0,O.isNonNullable)(t)?t:Et(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let u=e.find(({track:c})=>c.id===s)?.representation;(0,O.assertNonNullable)(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;(0,O.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(de(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Yh=ii;var lt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var M=require("@vkontakte/videoplayer-shared");var za=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},br=class extends za{constructor(){super(),this.listeners||za.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},ai=class{constructor(){Object.defineProperty(this,"signal",{value:new br,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(ai.prototype[Symbol.toStringTag]="AbortController",br.prototype[Symbol.toStringTag]="AbortSignal");function Ka(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Po(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Ka({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(u,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let c=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((f,b)=>{c.addEventListener("abort",()=>b(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(l,u)])}return n(l,u)},Request:s}}var si=Ka({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Wh=si?Po({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ct=si?Wh.fetch:window.fetch,KR=si?Wh.Request:window.Request,dt=si?ai:window.AbortController,JR=si?br:window.AbortSignal;var Kh=Ne(Jr(),1);var pt=()=>window.ManagedMediaSource||window.MediaSource,Ja=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Qh=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),zh=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var xe=require("@vkontakte/videoplayer-shared"),Jh=(0,xe.isAndroid)(),Za=document.createElement("video"),xE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',PE='video/mp4; codecs="hev1.1.6.L93.B0"',Xh='video/webm; codecs="vp09.00.10.08"',Zh='video/webm; codecs="av01.0.00M.08"',wE='audio/mp4; codecs="mp4a.40.2"',AE='audio/webm; codecs="opus"',_t={mms:Ja(),mse:Qh(),hls:!!(Za.canPlayType?.("application/x-mpegurl")||Za.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Ie={mp4:!!Za.canPlayType?.("video/mp4"),webm:!!Za.canPlayType?.("video/webm"),cmaf:!0},Ee={h264:!!pt()?.isTypeSupported?.(xE),h265:!!pt()?.isTypeSupported?.(PE),vp9:!!pt()?.isTypeSupported?.(Xh),av1:!!pt()?.isTypeSupported?.(Zh),aac:!!pt()?.isTypeSupported?.(wE),opus:!!pt()?.isTypeSupported?.(AE)},Sr=(Ee.h264||Ee.h265)&&Ee.aac,Nt,kE=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Zh}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Xh}})]);Nt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{kE()}catch(i){console.error(i)}var gr=_t.hls&&Ie.mp4,ef=()=>Object.keys(Ee).filter(i=>Ee[i]),tf=(i,e=!1,t=!1)=>{let r=_t.mse||_t.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Ie.mp4&&Sr;case"DASH_WEBM":return r&&Ie.webm&&Ee.vp9&&Ee.opus;case"DASH_WEBM_AV1":return r&&Ie.webm&&Ee.av1&&Ee.opus;case"DASH_STREAMS":return r&&(Ie.mp4&&Sr||Ie.webm&&(Ee.vp9||Ee.av1)&&(Ee.opus||Ee.aac));case"DASH_LIVE":return _t.mse&&Ie.mp4&&Sr;case"DASH_LIVE_CMAF":return r&&Ie.mp4&&Sr&&Ie.cmaf;case"DASH_ONDEMAND":return r&&Ie.mp4&&Sr;case"HLS":case"HLS_ONDEMAND":return gr||e&&_t.mse&&Ie.mp4&&Sr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return gr;case"MPEG":return Ie.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return _t.webrtc&&_t.ws&&Ee.h264&&(Ie.mp4||Ie.webm);default:return(0,xe.assertNever)(a)}})},Xa=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Nt?Nt[t].smooth?[t,e]:Nt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Nt?Nt[t].powerEfficient?[t,e]:Nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,xe.assertNever)(i)}return[e,t]},rf=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Xa(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Jh)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...Xa(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Xa(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Xa(i),...a,"HLS","HLS_ONDEMAND"];default:(0,xe.assertNever)(e)}return gr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},af=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o,l=(0,xe.getCurrentBrowser)().device===xe.CurrentClientDevice.Mac&&(0,xe.getCurrentBrowser)().browser===xe.CurrentClientBrowser.Safari;if(Jh)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,xe.assertNever)(i)}else gr&&!l?o=n:l?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},wo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],sf=i=>{if(i.size!==0){if(i.size===1)return i.values().next().value.split(".").at(0);for(let e of i){let t=(0,Kh.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};var vr=require("@vkontakte/videoplayer-shared"),nf=i=>{if(!i)return{id:"EmptyResponse",category:vr.ErrorCategory.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:vr.ErrorCategory.NETWORK,message:`UV Error ${i}`};let e=i.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:vr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:vr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:vr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var ni=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};var of=()=>window.matchMedia("(dynamic-range: high)").matches,Ao=i=>{let e=i.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=r;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=r[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var g=require("@vkontakte/videoplayer-shared");var Pr=Ne(Jr(),1);var RE=(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)},LE=i=>window.clearTimeout(i),uf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ko=uf?RE:window.requestIdleCallback,cL=uf?LE:window.cancelIdleCallback;var Kf=Ne(Ua(),1);var Oe=require("@vkontakte/videoplayer-shared"),$E=16,lf=!1;try{lf=(0,Oe.getCurrentBrowser)().browser===Oe.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=$E}catch(i){console.error(i)}var Ro=class{constructor(e){this.bufferFull$=new Oe.Subject;this.error$=new Oe.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Oe.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;lf&&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:Oe.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Oe.assertNever)(t)}}},cf=Ro;var Lo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var E=require("@vkontakte/videoplayer-shared");var K=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var yr=class extends K{};var oi=class extends K{};var ui=class extends K{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 li=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ci=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var di=class extends K{constructor(t,r){super(t,r);this.data=this.content}};var re=class extends K{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Ft=class extends re{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,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:l,SAPType:u,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var pi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fi=class extends re{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 mi=class extends re{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var bi=class extends re{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Si=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends re{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 vi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends re{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var Ii=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ei=class extends re{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 xi=class extends re{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 Pi=class extends re{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ME={ftyp:ui,moov:li,moof:ci,mdat:di,sidx:Ft,trak:pi,mdia:Si,mfhd:Ti,tkhd:gi,traf:Ii,tfhd:Ei,tfdt:xi,trun:Pi,minf:vi,sv3d:hi,st3d:fi,prhd:mi,proj:yi,equi:bi,uuid:oi,unknown:yr},qt=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=ME[e];return r?new r(t,new i):new yr(t,new i)}};var Tr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var OE=new TextDecoder("ascii"),BE=i=>OE.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",VE=i=>{let e=new Ft(i,new qt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},_E=(i,e)=>{let r=new qt().parse(i),a=new Tr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],l=n[n.length-1],u=o.source.byteOffset,d=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(i.buffer,u,d)},NE=(i,e)=>{let r=new qt().parse(i),s=new Tr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),l=s[s.length-1].children.find(d=>d.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((d,p)=>d+p,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},FE=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 qt().parse(i),a=new Tr(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let l=a.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},df={validateData:BE,parseInit:FE,getIndexRange:()=>{},parseSegments:VE,parseFeedableSegmentChunk:_E,getSegmentEndTime:NE};var ht=require("@vkontakte/videoplayer-shared");var hf=require("@vkontakte/videoplayer-shared");var pf={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},ff=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=wi(i,t),a=r in pf,s=a?pf[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let l=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,c=wi(l),d=u*2**((o-1)*8)+c,p=t+o,f;return p+d>i.byteLength?f=new DataView(i.buffer,i.byteOffset+p):f=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:f,valueSize:d}},wi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ge=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return wi(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:(0,hf.assertNever)(e)}},Ut=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=ff(r);if(!e(a))return;a.type==="master"&&Ut(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},mf=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=ff(i);return Ut(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Ge(o,n):s===17026?t=Ge(o,n):s===17029&&(r=Ge(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var bf=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],qE=[231,22612,22743,167,171,163,160,175],UE=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Ut(i,({tag:p,type:f,value:b,valueSize:S})=>{if(p===21419){let T=Ge(b,f);u=wi(T)}else p!==21420&&(u=void 0);return p===408125543?(e=b.byteOffset,t=b.byteOffset+S):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ge(b,f):p===17545?a=Ge(b,f):p===21420&&u===475249515?l=Ge(b,f):p===374648427?Ut(b,({tag:T,type:I,value:C})=>T===30321?(c=Ge(C,I)===1,!1):!0):s&&n&&bf.includes(p)&&(o=!0),!o}),(0,ht.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,ht.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,ht.assertNonNullable)(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:l,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},HE=i=>{if((0,ht.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},jE=(i,e)=>{let t=!1,r=!1,a=o=>(0,ht.isNonNullable)(o.time)&&(0,ht.isNonNullable)(o.position),s=[],n;return Ut(i,({tag:o,type:l,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ge(u,l));break;case 183:break;case 241:n&&(n.position=Ge(u,l));break;default:t&&bf.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:c}=o,d=s[l+1];return{status:"none",time:{from:u,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},GE=i=>{let e=0,t=!1;try{Ut(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):qE.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},Sf={validateData:mf,parseInit:UE,getIndexRange:HE,parseSegments:jE,parseFeedableSegmentChunk:GE};var Ir=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Sf;case"mp4":return df}}throw new ReferenceError(`Unsupported mime type ${i}`)};var Bo=Ne(qf(),1);var xr=require("@vkontakte/videoplayer-shared");var Uf=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Hf=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},Ht=(i,e)=>{let t=i;t=(0,Bo.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,Bo.default)(t,n,(o,l)=>(0,xr.isNullable)(s)?o:(0,xr.isNullable)(l)?s:s.padStart(parseInt(l,10),"0"))}return t},Gf=(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",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),T=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=Hf(f);else if(b){let y=Hf(b);(0,xr.isNonNullable)(y)&&(p=y)}else T&&(p=parseInt(T,10));let I=0,C=s.getAttribute("profiles")?.split(",")??[];for(let y of l){let x=y.getAttribute("id")??"id"+(I++).toString(10),j=y.getAttribute("mimeType")??"",w=y.getAttribute("codecs")??"",_=y.getAttribute("contentType")??j?.split("/")[0],Y=y.getAttribute("profiles")?.split(",")??[],A=y.getAttribute("lang")??void 0,W=y.querySelector("Label")?.textContent?.trim()??void 0,Q=y.querySelectorAll("Representation"),se=y.querySelector("SegmentTemplate"),Be=y.querySelector("Role")?.getAttribute("value")??void 0,Pe=_,R={id:x,language:A,isDefault:Be==="main",label:W,codecs:w,hdr:Pe==="video"&&Ao(w),mime:j,representations:[]};for(let D of Q){let ie=D.getAttribute("lang")??void 0,le=D.getAttribute("label")??void 0,we=D.querySelector("BaseURL")?.textContent?.trim()??"",We=new URL(we||o,e).toString(),zt=D.getAttribute("mimeType")??j,Pt=D.getAttribute("codecs")??w??"",z;if(_==="text"){let ae=D.getAttribute("id")||"",fe=ae.includes("_auto");z={id:ae,isAuto:fe,kind:"text",url:We}}else{let ae=D.getAttribute("contentType")??zt?.split("/")[0]??_,fe=y.getAttribute("profiles")?.split(",")??[],Ve=parseInt(D.getAttribute("width")??"",10),bt=parseInt(D.getAttribute("height")??"",10),Kt=parseInt(D.getAttribute("bandwidth")??"",10)/1e3,St=D.getAttribute("frameRate")??"",Jt=D.getAttribute("quality")??void 0,Ar=St?Uf(St):void 0,Qi=D.getAttribute("id")??"id"+(I++).toString(10),Tm=ae==="video"?`${bt}p`:ae==="audio"?`${Kt}Kbps`:Pt,Im=`${Qi}@${Tm}`,Em=[...C,...Y,...fe],bs,xm=D.querySelector("SegmentBase"),wt=D.querySelector("SegmentTemplate")??se;if(xm){let At=D.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[kt,gs]=At.split("-").map(Xt=>parseInt(Xt,10)),gt={from:kt,to:gs},kr=D.querySelector("SegmentBase")?.getAttribute("indexRange"),[vs,zi]=kr?kr.split("-").map(Xt=>parseInt(Xt,10)):[],Rr=kr?{from:vs,to:zi}:void 0;bs={type:"byteRange",url:We,initRange:gt,indexRange:Rr}}else if(wt){let At={representationId:D.getAttribute("id")??void 0,bandwidth:D.getAttribute("bandwidth")??void 0},kt=parseInt(wt.getAttribute("timescale")??"",10),gs=wt.getAttribute("initialization")??"",gt=wt.getAttribute("media"),kr=parseInt(wt.getAttribute("startNumber")??"",10)??1,vs=Ht(gs,At);if(!gt)throw new ReferenceError("No media attribute in SegmentTemplate");let zi=wt.querySelectorAll("SegmentTimeline S")??[],Rr=[],Xt=0,ys="",Ts=0;if(zi.length){let Ki=kr,_e=0;for(let Zt of zi){let Qe=parseInt(Zt.getAttribute("d")??"",10),Rt=parseInt(Zt.getAttribute("r")??"",10)||0,Ji=parseInt(Zt.getAttribute("t")??"",10);_e=Number.isFinite(Ji)?Ji:_e;let Is=Qe/kt*1e3,wm=_e/kt*1e3;for(let Xi=0;Xi<Rt+1;Xi++){let Am=Ht(gt,{...At,segmentNumber:Ki.toString(10),segmentTime:(_e+Xi*Qe).toString(10)}),zo=(wm??0)+Xi*Is,km=zo+Is;Ki++,Rr.push({time:{from:zo,to:km},url:Am})}_e+=(Rt+1)*Qe,Xt+=(Rt+1)*Is}Ts=_e/kt*1e3,ys=Ht(gt,{...At,segmentNumber:Ki.toString(10),segmentTime:_e.toString(10)})}else if((0,xr.isNonNullable)(p)){let _e=parseInt(wt.getAttribute("duration")??"",10)/kt*1e3,Zt=Math.ceil(p/_e),Qe=0;for(let Rt=1;Rt<Zt;Rt++){let Ji=Ht(gt,{...At,segmentNumber:Rt.toString(10),segmentTime:Qe.toString(10)});Rr.push({time:{from:Qe,to:Qe+_e},url:Ji}),Qe+=_e}Ts=Qe,ys=Ht(gt,{...At,segmentNumber:Zt.toString(10),segmentTime:Qe.toString(10)})}let Pm={time:{from:Ts,to:1/0},url:ys};bs={type:"template",baseUrl:We,segmentTemplateUrl:gt,initUrl:vs,totalSegmentsDurationMs:Xt,segments:Rr,nextSegmentBeyondManifest:Pm,timescale:kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ae||!zt)continue;let Ss={video:"video",audio:"audio",text:"text"}[ae];if(!Ss)continue;Pe||=Ss,z={id:Im,kind:Ss,segmentReference:bs,profiles:Em,duration:p,bitrate:Kt,mime:zt,codecs:Pt,width:Ve,height:bt,fps:Ar,quality:Jt}}R.language||=ie,R.label||=le,R.mime||=zt,R.codecs||=Pt,R.hdr||=Pe==="video"&&Ao(Pt),R.representations.push(z)}Pe&&a[Pe].push(R)}return{dynamic:u,liveAvailabilityStartTime:d,duration:p,streams:a}};var Ai=Ne(Jr(),1);var Yf=require("@vkontakte/videoplayer-shared"),Wf=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?It(s):void 0)??(0,Yf.videoSizeToQuality)({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Qf=({id:i,bitrate:e})=>({id:i,bitrate:e}),es=(i,e,t)=>{let r=e.indexOf(i);return(0,Ai.default)(t,Math.round(t.length*r/e.length))??(0,Ai.default)(t,-1)},zf=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),_o=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Ai.default)(r.split("."),0),isDefault:a}),No=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Ai.default)(a.split("."),0)}),ts=i=>"url"in i,jt=i=>i.type==="template",ki=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Ri=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:l=!1,manifest:u}){this.currentSegmentLength$=new E.ValueSubject(0);this.onLastSegment$=new E.ValueSubject(!1);this.fullyBuffered$=new E.ValueSubject(!1);this.playingRepresentation$=new E.ValueSubject(void 0);this.playingRepresentationInit$=new E.ValueSubject(void 0);this.error$=new E.Subject;this.gaps=[];this.subscription=new E.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new dt;this.destroyAbortController=new dt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,E.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,E.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new cf(this.sourceBuffer),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,l=this.mediaSource.readyState;l!=="open"&&(o={id:`SegmentEjection_source_${l}`,category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:E.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let l=Math.min(this.bufferLimit,Lo(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=l,this.tuning.useNewPruneBufferStrategy){let u=lt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,u<c)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,E.assertNonNullable)(r,"No init buffer for starting representation"),(0,E.assertNonNullable)(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,E.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,E.assertNonNullable)(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,E.isNullable)(s)||(0,E.isNullable)(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,E.assertNonNullable)(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,E.isNonNullable)(n)&&(this.isLive||(a.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,E.abortable)(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(l=>l.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let u=t.find(p=>p.id===l);u&&this.representations.set(l,u);let c=this.representations.get(l);if(!c||!jt(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);(0,E.assertNonNullable)(a);let s=this.segments.get(r);(0,E.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,E.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=l,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.initData=new Map(r.map(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 dt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,E.isNullable)(e)||(0,E.isNullable)(this.downloadingRepresentationId)||(0,E.isNullable)(this.playingRepresentationId)||(0,E.isNullable)(this.sourceBuffer)||!(0,E.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,E.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=lt(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Lo(this.sourceBuffer.buffered)>=this.bufferLimit){let u=lt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);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 c=(0,Pr.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&<(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Pr.default)(r,-1);l&&l.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===l))}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;(0,E.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(r=>r.representations)??[];for(let r of t){if(!r||!jt(r.segmentReference))return;let a=r.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Pr.default)(s,-1)?.time.to??0,o=a?.findIndex(l=>Math.floor(n)>=Math.floor(l.time.from)&&Math.floor(n)<=Math.floor(l.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,l)}else{let l=a.slice(o+1);this.segments.set(r.id,[...s,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,E.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let r=t.segmentReference;if(!jt(r))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Ht(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:p,to:f}},b)=>{let S=p<=r&&f>=r,T=p>r||S||b===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&p<=r+I||f<=r+I;return(d==="none"||d==="partially_ejected"&&T&&C&&this.sourceBuffer&&!ni(this.sourceBuffer.buffered,r))&&T&&C});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,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=u||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")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(0,E.abortable)(o,async function*(){let c=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:l,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,f=Ir(t.mime);a.segment.time.to=f.getSegmentEndTime(d,p)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),ki(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let l of e)l.status="downloading",this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,E.abortable)(n,async function*(){let l=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),(0,E.fromEvent)(window,"online").pipe((0,E.once)()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(l){this.abortActiveSegments(e),ki(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(jt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Pr.default)(e,0).byte.from,to:(0,Pr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,l)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!jt(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,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}: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),c=Ir(n.mime).parseFeedableSegmentChunk(u,this.isLive);c?.byteLength&&(l.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let l=o.segmentReference.type,u=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=l==="byteRange",f=p?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let S=p?d.byte.from-r:0,T=p?d.byte.to-r:e.byteLength,I=S<a,C=T<=a;if(d.status==="downloading"&&I&&C){d.status="downloaded";let B=new DataView(e.buffer,e.byteOffset+S,f);this.sourceBufferTaskQueue.append(B,s).then(y=>y&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&I&&(c.loadedBytes=Math.min(f,a-S),c.loadedBytes>c.feedingBytes)){let B=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===f?B:Ir(o.mime).parseFeedableSegmentChunk(B);y?.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(x=>{if(s.aborted)n();else if(x)c.fedBytes+=y.byteLength,c.fedBytes===f&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<f)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let l of this.activeSegments){let{segment:u}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let c=u.byte.from-r,d=u.byte.to-r,p=d-c+1,f=c<a,b=d<=a;if(f){if(u.status==="downloading"&&b){u.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(l.loadedBytes=Math.min(p,a-c),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===p?S:Ir(o.mime).parseFeedableSegmentChunk(S);T?.byteLength&&(u.status="partially_fed",l.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,s)&&!s.aborted?(l.fedBytes+=T.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):n())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ts(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=ko(()=>(0,Kf.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,E.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ir(e.mime),a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:c}=o,d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&jt(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:E.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,E.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=l=>{l.sort((c,d)=>c.from-d.from);let u=[l[0]];for(let c=1;c<l.length;c++){let{from:d,to:p}=l[c],f=u[u.length-1];f.to>=d?f.to=Math.max(f.to,p):u.push(l[c])}return u},o=l=>{if(s>=t)return a;a.push(l.time),a=n(a);let u=ts(l)?l.size??0:l.byte.to-l.byte.from;s+=u};for(let l of this.segments.values())for(let u of l){let c=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&u.status==="fed"&&o(u)}for(let l=0;l<this.sourceBuffer.buffered.length;l++){let u=this.sourceBuffer.buffered.start(l)*1e3,c=this.sourceBuffer.buffered.end(l)*1e3,d=0;for(let p of this.segments.values())for(let f of p)f.status==="none"&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:u,to:c},url:"",status:"none"};o(p)}}if(a.length&&r){let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let c of u)c.time.from>=e+l&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,c)=>u||c,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,E.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,l=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let c=ts(u)?u.size??0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&l(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&l(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let f of p)if(f.status==="none"&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(d)){s=c,n=d;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 c of this.segments.values())for(let d of c)d.time.from>e+u&&d.status==="fed"&&l(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let 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=ko(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:E.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,E.isNullable)(this.sourceBuffer)||(0,E.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),l=e.some(c=>c.from-t<=n&&c.to+t>=o),u=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);l||(u.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Li=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Jf=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};var X=require("@vkontakte/videoplayer-shared");var rs=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.abortAllController=new dt;this.subscription=new X.Subscription;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Li(t));let r=yield ct(t,{signal:this.abortAllController.signal}).catch($i);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=(0,X.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:l=!1}={}){let u=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(u,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),u=_.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(u=Li(u));let d=this.abortAllController.signal,p;if(n){let _=new dt;if(p=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{_.abort()}catch(Y){$i(Y)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(Y){$i(Y)}d=_.signal}let f=(0,X.now)(),b=yield ct(u,{priority:s,headers:c,signal:d}).catch($i),S=(0,X.now)();if(!b)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-f),!b.ok||!b.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!a&&!o)return p?.unsubscribe(),b.arrayBuffer();let[T,I]=b.body.tee(),C=T.getReader();o&&this.throughputEstimator?.trackStream(I,l);let B=0,y=new Uint8Array(0),x=!1,j=_=>{p?.unsubscribe(),x=!0,$i(_)},w=(0,X.abortable)(d,async function*({done:_,value:Y}){if(B===0&&this.lastRequestFirstBytes$.next((0,X.now)()-f),d.aborted){p?.unsubscribe();return}if(!_&&Y){let A=new Uint8Array(y.length+Y.length);A.set(y),A.set(Y,y.length),y=A,B+=Y.byteLength,a?.(new DataView(y.buffer),B),yield C?.read().then(w,j)}}.bind(this));return yield C?.read().then(w,j),p?.unsubscribe(),x?null:y.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,l=!1,u,c;e.indexRange&&(u=e.indexRange.from,c=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let f=t.parseInit(p),b=e.indexRange??t.getIndexRange(f);if(!b)throw new ReferenceError("No way to load representation index");let S;if(l)S=new DataView(d,b.from-n,b.to-b.from+1);else{let I=yield this.fetch(e.url,{range:b,priority:r,measureThroughput:!1});if(!I)return null;S=new DataView(I)}let T=t.parseSegments(S,f,b);return{init:f,dataView:new DataView(d),segments:T}}.bind(this));this.fetchTemplateRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=Jf(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:(0,X.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},$i=i=>{if(!ki(i))throw i};var Gt=(i,e,t)=>t*e+(1-t)*i,Fo=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Xf=(i,e,t,r)=>{let a=0,s=t,n=Fo(i,e),o=e<r?e:r;for(let l=0;l<o;l++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};var Ci=require("@vkontakte/videoplayer-shared"),xt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ci.ValueSubject(e.initial),this.debounced$=new Ci.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new he(`raw_${t}`),this.smoothedSeries$=new he(`smoothed_${t}`),this.reportedSeries$=new he(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,Ci.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var is=class extends xt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Gt(this.slow,t,this.params.emaAlphaSlow),this.fast=Gt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var as=class extends xt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=Fo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Gt(this.emaSmoothed,t,this.params.emaAlpha);let a=Xf(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var ss=class extends xt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Gt(this.smoothed,t,this.params.emaAlpha):t}};var Yt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new is({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new as({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ss({initial:e,label:"liveEdgeDelay",...t})}};var qo=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var em=["timeupdate","progress","play","seeked","stalled","waiting"];var ns=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new g.Subscription;this.representationSubscription=new g.Subscription;this.state$=new q("none");this.currentVideoRepresentation$=new g.ValueSubject(void 0);this.currentVideoRepresentationInit$=new g.ValueSubject(void 0);this.currentAudioRepresentation$=new g.ValueSubject(void 0);this.currentVideoSegmentLength$=new g.ValueSubject(0);this.currentAudioSegmentLength$=new g.ValueSubject(0);this.error$=new g.Subject;this.lastConnectionType$=new g.ValueSubject(void 0);this.lastConnectionReused$=new g.ValueSubject(void 0);this.lastRequestFirstBytes$=new g.ValueSubject(void 0);this.isLive$=new g.ValueSubject(!1);this.liveDuration$=new g.ValueSubject(0);this.liveAvailabilityStartTime$=new g.ValueSubject(void 0);this.bufferLength$=new g.ValueSubject(0);this.liveLoadBufferLength$=new g.ValueSubject(0);this.livePositionFromPlayer$=new g.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new g.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new g.Subject;this.gapWatchdogActive=!1;this.destroyController=new dt;this.initManifest=(0,g.abortable)(this.destroyController.signal,async function*(e,t,r){this.element=e,this.manifestUrlString=de(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:g.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,g.abortable)(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:g.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=Gf(e??"",this.manifestUrlString)}catch(s){let n=nf(e)??{id:"ManifestParsing",category:g.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:s};this.error$.next(n)}if(!t)return null;let r=(s,n,o)=>!!(this.element?.canPlayType?.(n)&&pt()?.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:c,codecs:d})=>r(s,c,d)),l=new Set(o.map(({codecs:c})=>c)),u=sf(l);if(u&&(a[s]=o.filter(({codecs:c})=>c.startsWith(u))),s==="video"){let c=of(),d=this.tuning.preferHDR,p=a.video.some(b=>b.hdr),f=a.video.some(b=>!b.hdr);c&&d&&p?a.video=a.video.filter(b=>b.hdr):f&&(a.video=a.video.filter(b=>!b.hdr))}}return{...t,streams:a}}.bind(this));this.initRepresentations=(0,g.abortable)(this.destroyController.signal,async function*(e,t,r){(0,g.assertNonNullable)(this.manifest),(0,g.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=d=>{this.representationSubscription.add((0,g.fromEvent)(d,"error").pipe((0,g.filter)(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:g.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?zh():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ja())if(r){let d=document.createElement("source");a(d),d.type="application/x-mpegurl",d.src=r.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,p)=>[...d,...p.representations],[]);if(this.videoBufferManager=new Ri("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,g.isNonNullable)(t)){let d=this.manifest.streams.audio.reduce((p,f)=>[...p,...f.representations],[]);this.audioBufferManager=new Ri("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,g.interval)(1e3).subscribe(d=>{if(this.element?.paused){let p=po(this.manifestUrlString,2);this.manifestUrlString=de(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add((0,g.merge)(...em.filter(d=>d!=="waiting").map(d=>(0,g.fromEvent)(this.element,d))).pipe((0,g.map)(d=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),(0,g.filterChanged)(),(0,g.filter)(d=>!!d),(0,g.tap)(d=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,g.filterChanged)()).subscribe(p=>qo(this.element,1))),this.representationSubscription.add((0,g.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,g.filter)(({bufferLength:p,isActiveLowLatency:f})=>f&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add((0,g.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=p-b,C=1;Math.abs(I)>S&&(C=1+Math.sign(I)*T),qo(this.element,C)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let f=0;if(p){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add((0,g.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,g.throttle)(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:f})=>{if((0,g.assertNonNullable)(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,S=po(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),C=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,B=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,y=isFinite(p)?p:f,x=this.isActiveLowLatency$.getValue(),j=T<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(x&&j);let w="none";if(x?w="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&j?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&y<I?w="live_forward_buffering":y<I+B&&(w="live_with_target_offset"),isFinite(p)&&(d=p>d?p:d),w==="live_forward_buffering"||w==="live_with_target_offset"){let _=d-(I+C),Y=this.normolizeLiveOffset(Math.trunc(S+_/b)),A=Math.abs(Y-S),W;!p||A<=this.tuning.dashCmafLive.offsetCalculationError?W=S:Y>0&&A>this.tuning.dashCmafLive.offsetCalculationError?W=Y:W=0,this.manifestUrlString=de(this.manifestUrlString,W,2)}w!=="none"&&w!=="active_low_latency"&&(d=0,this.updateLive())}))}let l=(0,g.merge)(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe((0,g.map)(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),u=(0,g.merge)(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe((0,g.map)(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue())));this.representationSubscription.add((0,g.merge)(this.forceEnded$,(0,g.combine)({allBuffersFull:l,someBufferEnded:u}).pipe((0,g.filter)(({allBuffersFull:d,someBufferEnded:p})=>d&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:g.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add((0,g.merge)(...this.bufferManagers.map(d=>d.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(d=>this.source?.addEventListener("sourceopen",d)));let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(d=>d.representations).flatMap(d=>d.duration??0)];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&(0,g.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,g.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:g.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new rs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Yt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){(0,g.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=de(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio))}initBuffer(){(0,g.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,g.merge)(...em.map(e=>(0,g.fromEvent)(this.element,e)),(0,g.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:g.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,g.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,g.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ni(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`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let t=this.element.currentTime*1e3;this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)}}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,g.interval)(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:g.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,r)}seek(e,t){(0,g.assertNonNullable)(this.element),(0,g.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),ni(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$.getValue()&&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 os=class{constructor(e,t){this.fov=e,this.orientation=t}};var us=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var tm=`attribute vec2 a_vertex;
|
|
33
|
+
[best track] ${x?.quality}
|
|
34
|
+
[selected track] ${B?.quality}
|
|
35
|
+
`});let W=B&&d&&d.history[B.id]&&(0,U.now)()-d.history[B.id]<=i.trackCooldown&&(!d.last||B.id!==d.last.id);if(B?.id&&d&&!W&&d.recordSelection(B),W&&d?.last){let k=d.last;return d?.recordSwitch(k),l({message:`
|
|
36
|
+
[last selected] ${k?.quality}
|
|
37
|
+
`}),k}return d?.recordSwitch(B),B},et=Vs;var ae=n=>new URL(n).hostname;var D=require("@vkontakte/videoplayer-shared");var oa=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"))},fe=async n=>{let e=n.muted;try{await n.play()}catch(t){if(!oa(t))return!1;if(e)return console.warn(t),!1;n.muted=!0;try{await n.play()}catch(i){return oa(i)&&(n.muted=!1,console.warn(i)),!1}}return!0};var Te=require("@vkontakte/videoplayer-shared");var Be=require("@vkontakte/videoplayer-shared");function se(){return(0,Be.now)()}function Ar(n){return se()-n}function wr(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,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),o&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function da(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function Et(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,d=0,c,l,h=!1,m="arraybuffer",f=7e3,v=2e3,T=()=>{if(u)return;(0,Be.assertNonNullable)(c);let Y=Ar(c),re;if(Y<v){re=v-Y,setTimeout(T,re);return}v*=2,v>f&&(v=f),s&&s.abort(),s=new r,H()},$=Y=>(a=Y,j),Q=Y=>(l=Y,j),C=()=>(m="json",j),g=()=>{if(!u){if(--d>=0){T(),i&&i();return}u=!0,l&&l(),t&&t()}},I=Y=>(h=Y,j),H=()=>{c=se(),s=new r,s.open("get",n);let Y=0,re,Ae=0,ve=()=>((0,Be.assertNonNullable)(c),Math.max(c,Math.max(re||0,Ae||0)));if(a&&s.addEventListener("progress",A=>{let R=se();a.updateChunk&&A.loaded>Y&&(a.updateChunk(ve(),A.loaded-Y),Y=A.loaded,re=R)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>g())),s.addEventListener("load",()=>{if(u)return;(0,Be.assertNonNullable)(s);let A=s.status;if(A>=200&&A<300){if(s.response.byteLength&&a){let R=s.response.byteLength-Y;R&&a.updateChunk&&a.updateChunk(ve(),R)}s.responseType==="json"&&!Object.values(s.response).length?g():(l&&l(),e(s.response))}else g()}),s.addEventListener("error",()=>{g()}),h){let A=()=>{(0,Be.assertNonNullable)(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Ae=se(),s.removeEventListener("readystatechange",A))};s.addEventListener("readystatechange",A)}return s.responseType=m,s.send(),j},j={withBitrateReporting:$,withParallel:I,withJSONResponse:C,withRetryCount:Y=>(d=Y,j),withRetryInterval:(Y,re)=>((0,Be.isNonNullable)(Y)&&(v=Y),(0,Be.isNonNullable)(re)&&(f=re),j),withTimeout:Y=>(o=Y,j),withFinally:Q,send:H,abort:()=>{s&&(s.abort(),s=void 0),u=!0,l&&l()}};return j}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 u=a.bytes*s/o;r+=u,a.start=t,a.bytes-=u}}}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 Nt=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=se(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=se()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Et(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=se()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=se();if(Object.keys(this.activeRequests).length>=e)return!1;let 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 Hi=1e4,Lr=3;var Os=6e4,_s=10,Ns=1,Fs=500,Ft=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=wr(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=wr(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||(0,Te.isNonNullable)(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=()=>{da(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 Nt(Lr,Hi,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,u=null,d=null,c=!1,l=()=>{let g=a&&(!c||c===this.rep);return g||t("Not running!"),g},h=(g,I,H)=>{u&&u.abort(),u=Et(this.urlResolver.resolve(g,!1),I,H,()=>this._retryCallback()).withTimeout(Hi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Lr).withFinally(()=>{u=null}).send()},m=(g,I,H)=>{(0,Te.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),I,H,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=g=>{let I=i.playbackRate;i.playbackRate!==g&&(t(`Playback rate switch: ${I}=>${g}`),i.playbackRate=g)},v=g=>{this.lowLatency=g,t(`lowLatency changed to ${g}`),T()},T=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let g=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let H=se()-1e4,x=0;for(let W=0;W<this.bufferStates.length;W++){let k=this.bufferStates[W];g=Math.min(g,k.buf),k.ts<H&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${g} drop=${x} jitter=${this.sourceJitter}`);let B=g-Ns;this.sourceJitter>=0?B-=this.sourceJitter/2:this.sourceJitter-=1,B>3?f(1.15):B>1?f(1.1):B>.3?f(1.05):f(1)}},$=g=>{let I,H=()=>I&&I.start?I.start.length:0,x=A=>I.start[A]/1e3,B=A=>I.dur[A]/1e3,W=A=>I.fragIndex+A,k=(A,R)=>({chunkIdx:W(A),startTS:x(A),dur:B(A),discontinuity:R}),j=()=>{let A=0;if(I&&I.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,te=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ne=R;this.sourceJitter>1&&(ne+=this.sourceJitter-1);let ye=I.dur.length-1;for(;ye>=0&&(ne-=I.dur[ye],!(ne<=0));--ye);A=Math.min(ye,I.dur.length-1-te),A=Math.max(A,0)}return k(A,!0)},Y=A=>{let R=H();if(!(R<=0)){if((0,Te.isNonNullable)(A)){for(let te=0;te<R;te++)if(x(te)>A)return k(te)}return j()}},re=A=>{let R=H(),te=A?A.chunkIdx+1:0,ne=te-I.fragIndex;if(!(R<=0)){if(!A||ne<0||ne-R>_s)return t(`Resync: offset=${ne} bChunks=${R} chunk=`+JSON.stringify(A)),j();if(!(ne>=R))return k(te-I.fragIndex,!1)}},Ae=(A,R,te)=>{d&&d.abort(),d=Et(this.urlResolver.resolve(A,!0,this.lowLatency),R,te,()=>this._retryCallback()).withTimeout(Hi).withRetryCount(Lr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(A,R)=>{Ae(g,te=>{if(!l())return;I=te;let ne=!!I.lowLatency;ne!==this.lowLatency&&v(ne);let ye=0;for(let Re=0;Re<I.dur.length;++Re)ye+=I.dur[Re];ye>0&&((0,Te.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ye/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,A(Y(R))},()=>this._handleNetworkError())},nextChunk:re}},Q=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),(0,Te.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:g=>{let{videoElement:I,logger:H}=this.params,x=$(e.jidxUrl),B,W,k,j,Y=0,re,Ae,ve,A=()=>{re&&(clearTimeout(re),re=void 0);let q=Math.max(Fs,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=Y+q,le=se(),we=Math.min(1e4,ie-le);Y=le;let qe=()=>{d||l()&&x.seek(()=>{l()&&(Y=se(),R(),A())})};we>0?re=window.setTimeout(()=>{this.paused?A():qe()},we):qe()},R=()=>{let q;for(;q=x.nextChunk(j);)j=q,gt(q);let ie=x.nextChunk(k);if(ie){if(k&&ie.discontinuity){H("Detected discontinuity; restarting playback"),this.paused?A():(Q(),this._initPlayerWith(e));return}Re(ie)}else A()},te=(q,ie)=>{if(!l()||!this.sourceBuffer)return;let le,we,qe,vt=ze=>{window.setTimeout(()=>{l()&&te(q,ie)},ze)};if(this.sourceBuffer.updating)H("Source buffer is updating; delaying appendBuffer"),vt(100);else{let ze=se(),yt=I.currentTime;!this.paused&&I.buffered.length>1&&Ae===yt&&ze-ve>500&&(H("Stall suspected; trying to fix"),this._fixupStall()),Ae!==yt&&(Ae=yt,ve=ze);let Rt=this._getBufferSizeSec();if(Rt>30)H(`Buffered ${Rt} seconds; delaying appendBuffer`),vt(2e3);else try{this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(this.bufferStates.push({ts:ze,buf:Rt}),T(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch($i){if($i.name==="QuotaExceededError")H("QuotaExceededError; delaying appendBuffer"),qe=this.sourceBuffer.buffered.length,qe!==0&&(le=this.sourceBuffer.buffered.start(0),we=yt,we-le>4&&this.sourceBuffer.remove(le,we-3)),vt(1e3);else throw $i}}},ne=()=>{W&&B&&(H([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(k)]),te(W,function(){W=null,R()}))},ye=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),Re=q=>{l()&&m(ye(q),(ie,le)=>{if(l()){if(le/=1e3,W=ie,k=q,s=q.startTS,le){let we=Math.min(10,q.dur/le);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}ne()}},()=>this._handleNetworkError())},gt=q=>{l()&&((0,Te.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ye(q),!1)))},it=q=>{l()&&(e.cachedHeader=q,te(q,()=>{B=!0,ne()}))};a=!0,x.seek(q=>{if(l()){if(Y=se(),!q){A();return}j=q,!(0,Te.isNullable)(g)||q.startTS>g?Re(q):(k=q,R())}},g),e.cachedHeader?it(e.cachedHeader):h(e.headerUrl,it,()=>this._handleNetworkError())},stop:Q,getTimestampSec:()=>s},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,Te.isNonNullable)(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,(0,Te.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Te.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let h,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(m=this._getBufferSizeSec(),f=l/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}h=this._selectQuality(l),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${l}`)},a=(()=>({updateChunk:(h,m)=>{let f=se();if(this.chunkRateEstimator.addInterval(h,f,m)){let T=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:f-h,speed:T}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))(),s=-1/0,o,u=!0,d=()=>{let l=a.get();if(l&&o&&this.autoQuality){if(u&&l>o&&Ar(s)<3e4)return;i(l)}u=this.autoQuality};return{updateChunk:(l,h)=>{let m=a.updateChunk(l,h);return m&&d(),m},notifySwitch:l=>{let h=se();l<o&&(s=h),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=Et(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Hi).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;fe(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((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.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))},Os))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Z=require("@vkontakte/videoplayer-shared"),$r=class{constructor(){this.onDroopedVideoFramesLimit$=new Z.Subject;this.subscription=new Z.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new Z.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,Z.isInvariantQuality)(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&&(0,Z.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,Z.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,Z.interval)(this.droppedFramesChecker.checkTime).pipe((0,Z.filter)(()=>this.playing),(0,Z.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,Z.debounce)(this.droppedFramesChecker.checkTime)),i=(0,Z.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>(0,Z.isLower)(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}},Gi=$r;var Qi=require("@vkontakte/videoplayer-shared"),ua=require("@vkontakte/videoplayer-shared");var Ut=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Us=(n,e)=>new Qi.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||Ut()))},{...i,...e});r.observe(n);let a=(0,ua.fromEvent)(document,"visibilitychange").pipe((0,Qi.map)(s=>!document.hidden||Ut())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),ke=Us;var Hs=["paused","playing","ready"],Gs=["paused","playing","ready"],Ht=class{constructor(e){this.subscription=new D.Subscription;this.videoState=new N("stopped");this.representations$=new D.ValueSubject([]);this.textTracksManager=new xe;this.droppedFramesManager=new Gi;this.maxSeekBackTime$=new D.ValueSubject(1/0);this.zeroTime$=new D.ValueSubject(void 0);this.liveOffset=new Fe;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:D.ErrorCategory.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=Ze(r.name)??(0,D.videoSizeToQuality)(r.video),o=r.bitrate/1e3,u={...r.video};if(!s)continue;let d={id:a,quality:s,bitrate:o,size:u};i.push({track:d,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),(0,D.isNonNullable)(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),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(Gs.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&Hs.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(oe(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(oe(this.params.source.url,u))}return;default:return(0,D.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:D.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};(0,D.merge)(this.videoState.stateChangeStarted$.pipe((0,D.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,D.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ce(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ae(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=me(this.video);this.subscription.add(this.representations$.pipe((0,D.map)(r=>r.map(({track:a})=>a)),(0,D.filter)(r=>!!r.length),(0,D.once)()).subscribe(r=>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:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,D.filterChanged)(),(0,D.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,D.combine)({zeroTime:this.zeroTime$.pipe((0,D.filter)(D.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ve(this.video,this.params.desiredState.isLooped,t)).add(he(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ee(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(ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&(0,D.videoQualityToHeight)(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(0,D.assertNever)(r.to)}},t)).add((0,D.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,D.observableFrom)(["init"])).pipe((0,D.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),pe(this.video)}createLiveDashPlayer(){let e=new Ft({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&&(0,D.isNonNullable)(t)?t:et(e.map(({track:d})=>d),{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,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==o){let d=e.find(({track:c})=>c.id===a)?.representation;(0,D.assertNonNullable)(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;(0,D.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(oe(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var la=Ht;var Ge=(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)};var M=require("@vkontakte/videoplayer-shared");var Qe=()=>window.ManagedMediaSource||window.MediaSource,Wi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),ca=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),pa=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ge=require("@vkontakte/videoplayer-shared"),ha=(0,ge.isAndroid)(),Yi=document.createElement("video"),js='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ys='video/mp4; codecs="hev1.1.6.L93.B0"',ma='video/webm; codecs="vp09.00.10.08"',fa='video/webm; codecs="av01.0.00M.08"',qs='audio/mp4; codecs="mp4a.40.2"',zs='audio/webm; codecs="opus"',ot={mms:Wi(),mse:ca(),hls:!!(Yi.canPlayType?.("application/x-mpegurl")||Yi.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},be={mp4:!!Yi.canPlayType?.("video/mp4"),webm:!!Yi.canPlayType?.("video/webm"),cmaf:!0},Se={h264:!!Qe()?.isTypeSupported?.(js),h265:!!Qe()?.isTypeSupported?.(Ys),vp9:!!Qe()?.isTypeSupported?.(ma),av1:!!Qe()?.isTypeSupported?.(fa),aac:!!Qe()?.isTypeSupported?.(qs),opus:!!Qe()?.isTypeSupported?.(zs)},xt=(Se.h264||Se.h265)&&Se.aac,dt,Ks=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:fa}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:ma}})]);dt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Ks()}catch(n){console.error(n)}var kt=ot.hls&&be.mp4,ba=()=>Object.keys(Se).filter(n=>Se[n]),Sa=(n,e=!1,t=!1)=>{let i=ot.mse||ot.mms&&t;return n.filter(r=>{switch(r){case"DASH_SEP":return i&&be.mp4&&xt;case"DASH_WEBM":return i&&be.webm&&Se.vp9&&Se.opus;case"DASH_WEBM_AV1":return i&&be.webm&&Se.av1&&Se.opus;case"DASH_STREAMS":return i&&(be.mp4&&xt||be.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return ot.mse&&be.mp4&&xt;case"DASH_LIVE_CMAF":return i&&be.mp4&&xt&&be.cmaf;case"DASH_ONDEMAND":return i&&be.mp4&&xt;case"HLS":case"HLS_ONDEMAND":return kt||e&&ot.mse&&be.mp4&&xt;case"HLS_LIVE":case"HLS_LIVE_CMAF":return kt;case"MPEG":return be.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ot.webrtc&&ot.ws&&Se.h264&&(be.mp4||be.webm);default:return(0,ge.assertNever)(r)}})},ji=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 dt?dt[t].smooth?[t,e]:dt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return dt?dt[t].powerEfficient?[t,e]:dt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ge.assertNever)(n)}return[e,t]},ga=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...ji(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ha)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...ji(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ji(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ji(n),...r,"HLS","HLS_ONDEMAND"];default:(0,ge.assertNever)(e)}return kt?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},va=({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,u=(0,ge.getCurrentBrowser)().device===ge.CurrentClientDevice.Mac&&(0,ge.getCurrentBrowser)().browser===ge.CurrentClientBrowser.Safari;if(ha)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:(0,ge.assertNever)(n)}else kt&&!u?o=s:u?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"]},Mr=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ya=n=>{if(n.size!==0){if(n.size===1)return n.values().next().value.split(".").at(0);for(let e of n){let t=e.split(".").at(0);if(t==="opus"||t==="vp09"||t==="av01")return t}return n.values().next().value.split(".").at(0)}};var Pt=require("@vkontakte/videoplayer-shared"),Ta=n=>{if(!n)return{id:"EmptyResponse",category:Pt.ErrorCategory.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:Pt.ErrorCategory.NETWORK,message:`UV Error ${n}`};let e=n.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Pt.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(n,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Pt.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Pt.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Gt=(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};var Ia=()=>window.matchMedia("(dynamic-range: high)").matches,Rr=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,s]=i;return!!(s&&parseInt(s,10)>8)}case"vp09":{let[r,a,s]=i;return!!(r&&parseInt(r,10)>=2&&s&&parseInt(s,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,s]=r.toUpperCase(),o=a+s;return["6E","7A","F4"].includes(o)}}return!1};var b=require("@vkontakte/videoplayer-shared");var Pe=require("@vkontakte/videoplayer-shared"),Js=16,Ea=!1;try{Ea=(0,Pe.getCurrentBrowser)().browser===Pe.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=Js}catch(n){console.error(n)}var Dr=class{constructor(e){this.bufferFull$=new Pe.Subject;this.error$=new Pe.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Pe.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let 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;Ea&&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:Pe.ErrorCategory.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:(0,Pe.assertNever)(t)}}},xa=Dr;var Cr=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};var y=require("@vkontakte/videoplayer-shared");var z=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 At=class extends z{};var Qt=class extends z{};var Wt=class extends z{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 jt=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yt=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qt=class extends z{constructor(t,i){super(t,i);this.data=this.content}};var ee=class extends z{constructor(t,i){super(t,i);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ut=class extends ee{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,u=this.readUint32();a=this.readUint32();let d=a>>>28,c=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:o,subsegmentDuration:u,SAPType:d,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var zt=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Kt=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Jt=class extends ee{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 Xt=class extends ee{constructor(t,i){super(t,i);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Zt=class extends ee{constructor(t,i){super(t,i);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ei=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ti=class extends ee{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 ii=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ri=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ai=class extends ee{constructor(t,i){super(t,i);this.sequenceNumber=this.readUint32()}};var si=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ni=class extends ee{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 oi=class extends ee{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 di=class extends ee{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 Zs={ftyp:Wt,moov:jt,moof:Yt,mdat:qt,sidx:ut,trak:zt,mdia:ei,mfhd:ai,tkhd:ti,traf:si,tfhd:ni,tfdt:oi,trun:di,minf:ii,sv3d:Kt,st3d:Jt,prhd:Xt,proj:ri,equi:Zt,uuid:Qt,unknown:At},lt=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=Zs[e];return i?new i(t,new n):new At(t,new n)}};var wt=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 tn=new TextDecoder("ascii"),rn=n=>tn.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",an=n=>{let e=new ut(n,new lt),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})},sn=(n,e)=>{let i=new lt().parse(n),r=new wt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],d=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,d,l)},nn=(n,e)=>{let i=new lt().parse(n),a=new wt(i).findAll("traf"),s=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),u=a[a.length-1].children.find(l=>l.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((l,h)=>l+h,0):d=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},on=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 lt().parse(n),r=new wt(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 u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},ka={validateData:rn,parseInit:on,getIndexRange:()=>{},parseSegments:an,parseFeedableSegmentChunk:sn,getSegmentEndTime:nn};var We=require("@vkontakte/videoplayer-shared");var Aa=require("@vkontakte/videoplayer-shared");var Pa={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"}},wa=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=ui(n,t),r=i in Pa,a=r?Pa[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 u=new DataView(n.buffer,n.byteOffset+t+1,o-1),d=s&255>>o,c=ui(u),l=d*2**((o-1)*8)+c,h=t+o,m;return h+l>n.byteLength?m=new DataView(n.buffer,n.byteOffset+h):m=new DataView(n.buffer,n.byteOffset+h,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+l,value:m,valueSize:l}},ui=(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},$e=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return ui(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:(0,Aa.assertNever)(e)}},ct=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=wa(i);if(!e(r))return;r.type==="master"&&ct(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},La=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=wa(n);return ct(r.value,({tag:a,type:s,value:o})=>(a===17143?e=$e(o,s):a===17026?t=$e(o,s):a===17029&&(i=$e(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var $a=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],dn=[231,22612,22743,167,171,163,160,175],un=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,d,c=!1,l=0;return ct(n,({tag:h,type:m,value:f,valueSize:v})=>{if(h===21419){let T=$e(f,m);d=ui(T)}else h!==21420&&(d=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+v):h===357149030?a=!0:h===290298740?s=!0:h===2807729?i=$e(f,m):h===17545?r=$e(f,m):h===21420&&d===475249515?u=$e(f,m):h===374648427?ct(f,({tag:T,type:$,value:Q})=>T===30321?(c=$e(Q,$)===1,!1):!0):a&&s&&$a.includes(h)&&(o=!0),!o}),(0,We.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,We.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,We.assertNonNullable)(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:u,is3dVideo:c,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ln=n=>{if((0,We.isNullable)(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},cn=(n,e)=>{let t=!1,i=!1,r=o=>(0,We.isNonNullable)(o.time)&&(0,We.isNonNullable)(o.position),a=[],s;return ct(n,({tag:o,type:u,value:d})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=$e(d,u));break;case 183:break;case 241:s&&(s.position=$e(d,u));break;default:t&&$a.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:d,position:c}=o,l=a[u+1];return{status:"none",time:{from:d,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},pn=n=>{let e=0,t=!1;try{ct(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):dn.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},Ma={validateData:La,parseInit:un,getIndexRange:ln,parseSegments:cn,parseFeedableSegmentChunk:pn};var Lt=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ma;case"mp4":return ka}}throw new ReferenceError(`Unsupported mime type ${n}`)};var $t=require("@vkontakte/videoplayer-shared");var Ra=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var Da=n=>{if(!n.startsWith("P"))return;let e=(s,o)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(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},pt=(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,u)=>(0,$t.isNullable)(a)?o:(0,$t.isNullable)(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Va=(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()??"",u=s.children,d=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),l=c?new Date(c).getTime():void 0,h,m=a.getAttribute("mediaPresentationDuration"),f=s.getAttribute("duration"),T=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)h=Da(m);else if(f){let g=Da(f);(0,$t.isNonNullable)(g)&&(h=g)}else T&&(h=parseInt(T,10));let $=0,Q=a.getAttribute("profiles")?.split(",")??[];for(let g of u){let I=g.getAttribute("id")??"id"+($++).toString(10),H=g.getAttribute("mimeType")??"",x=g.getAttribute("codecs")??"",B=g.getAttribute("contentType")??H?.split("/")[0],W=g.getAttribute("profiles")?.split(",")??[],k=g.getAttribute("lang")??void 0,j=g.querySelector("Label")?.textContent?.trim()??void 0,Y=g.querySelectorAll("Representation"),re=g.querySelector("SegmentTemplate"),Ae=g.querySelector("Role")?.getAttribute("value")??void 0,ve=B,A={id:I,language:k,isDefault:Ae==="main",label:j,codecs:x,hdr:ve==="video"&&Rr(x),mime:H,representations:[]};for(let R of Y){let te=R.getAttribute("lang")??void 0,ne=R.getAttribute("label")??void 0,ye=R.querySelector("BaseURL")?.textContent?.trim()??"",Re=new URL(ye||o,e).toString(),gt=R.getAttribute("mimeType")??H,it=R.getAttribute("codecs")??x??"",q;if(B==="text"){let ie=R.getAttribute("id")||"",le=ie.includes("_auto");q={id:ie,isAuto:le,kind:"text",url:Re}}else{let ie=R.getAttribute("contentType")??gt?.split("/")[0]??B,le=g.getAttribute("profiles")?.split(",")??[],we=parseInt(R.getAttribute("width")??"",10),qe=parseInt(R.getAttribute("height")??"",10),vt=parseInt(R.getAttribute("bandwidth")??"",10)/1e3,ze=R.getAttribute("frameRate")??"",yt=R.getAttribute("quality")??void 0,Rt=ze?Ra(ze):void 0,$i=R.getAttribute("id")??"id"+($++).toString(10),ds=ie==="video"?`${qe}p`:ie==="audio"?`${vt}Kbps`:it,us=`${$i}@${ds}`,ls=[...Q,...W,...le],lr,cs=R.querySelector("SegmentBase"),rt=R.querySelector("SegmentTemplate")??re;if(cs){let at=R.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[st,pr]=at.split("-").map(Tt=>parseInt(Tt,10)),Ke={from:st,to:pr},Dt=R.querySelector("SegmentBase")?.getAttribute("indexRange"),[hr,Mi]=Dt?Dt.split("-").map(Tt=>parseInt(Tt,10)):[],Ct=Dt?{from:hr,to:Mi}:void 0;lr={type:"byteRange",url:Re,initRange:Ke,indexRange:Ct}}else if(rt){let at={representationId:R.getAttribute("id")??void 0,bandwidth:R.getAttribute("bandwidth")??void 0},st=parseInt(rt.getAttribute("timescale")??"",10),pr=rt.getAttribute("initialization")??"",Ke=rt.getAttribute("media"),Dt=parseInt(rt.getAttribute("startNumber")??"",10)??1,hr=pt(pr,at);if(!Ke)throw new ReferenceError("No media attribute in SegmentTemplate");let Mi=rt.querySelectorAll("SegmentTimeline S")??[],Ct=[],Tt=0,mr="",fr=0;if(Mi.length){let Ri=Dt,Le=0;for(let It of Mi){let De=parseInt(It.getAttribute("d")??"",10),nt=parseInt(It.getAttribute("r")??"",10)||0,Di=parseInt(It.getAttribute("t")??"",10);Le=Number.isFinite(Di)?Di:Le;let br=De/st*1e3,hs=Le/st*1e3;for(let Ci=0;Ci<nt+1;Ci++){let ms=pt(Ke,{...at,segmentNumber:Ri.toString(10),segmentTime:(Le+Ci*De).toString(10)}),Yr=(hs??0)+Ci*br,fs=Yr+br;Ri++,Ct.push({time:{from:Yr,to:fs},url:ms})}Le+=(nt+1)*De,Tt+=(nt+1)*br}fr=Le/st*1e3,mr=pt(Ke,{...at,segmentNumber:Ri.toString(10),segmentTime:Le.toString(10)})}else if((0,$t.isNonNullable)(h)){let Le=parseInt(rt.getAttribute("duration")??"",10)/st*1e3,It=Math.ceil(h/Le),De=0;for(let nt=1;nt<It;nt++){let Di=pt(Ke,{...at,segmentNumber:nt.toString(10),segmentTime:De.toString(10)});Ct.push({time:{from:De,to:De+Le},url:Di}),De+=Le}fr=De,mr=pt(Ke,{...at,segmentNumber:It.toString(10),segmentTime:De.toString(10)})}let ps={time:{from:fr,to:1/0},url:mr};lr={type:"template",baseUrl:Re,segmentTemplateUrl:Ke,initUrl:hr,totalSegmentsDurationMs:Tt,segments:Ct,nextSegmentBeyondManifest:ps,timescale:st}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ie||!gt)continue;let cr={video:"video",audio:"audio",text:"text"}[ie];if(!cr)continue;ve||=cr,q={id:us,kind:cr,segmentReference:lr,profiles:ls,duration:h,bitrate:vt,mime:gt,codecs:it,width:we,height:qe,fps:Rt,quality:yt}}A.language||=te,A.label||=ne,A.mime||=gt,A.codecs||=it,A.hdr||=ve==="video"&&Rr(it),A.representations.push(q)}ve&&r[ve].push(A)}return{dynamic:d,liveAvailabilityStartTime:l,duration:h,streams:r}};var Ba=require("@vkontakte/videoplayer-shared"),Oa=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a})=>{let s=(a?Ze(a):void 0)??(0,Ba.videoSizeToQuality)({width:e,height:t});return s&&{id:n,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},_a=({id:n,bitrate:e})=>({id:n,bitrate:e}),qi=(n,e,t)=>{let i=e.indexOf(n);return t.at(Math.round(t.length*i/e.length))??t.at(-1)},Na=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Or=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),_r=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),zi=n=>"url"in n,ht=n=>n.type==="template",li=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var ci=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:d}){this.currentSegmentLength$=new y.ValueSubject(0);this.onLastSegment$=new y.ValueSubject(!1);this.fullyBuffered$=new y.ValueSubject(!1);this.playingRepresentation$=new y.ValueSubject(void 0);this.playingRepresentationInit$=new y.ValueSubject(void 0);this.error$=new y.Subject;this.gaps=[];this.subscription=new y.Subscription;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=(0,y.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,y.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new xa(this.sourceBuffer),this.subscription.add((0,y.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:y.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),o??={id:"SegmentEjection",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s},this.error$.next(o)})),this.subscription.add((0,y.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:y.ErrorCategory.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 u=Math.min(this.bufferLimit,Cr(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let d=Ge(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,s*2,d<c)}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);(0,y.assertNonNullable)(i,"No init buffer for starting representation"),(0,y.assertNonNullable)(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=(0,y.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,y.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,y.isNullable)(a)||(0,y.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,y.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let s=this.getCurrentPosition();(0,y.isNonNullable)(s)&&(this.isLive||(r.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(s,1/0,!0)),this.maintain(s)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,y.abortable)(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let d=t.find(h=>h.id===u);d&&this.representations.set(u,d);let c=this.representations.get(u);if(!c||!ht(c.segmentReference))return;let l=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,y.assertNonNullable)(r);let a=this.segments.get(i);(0,y.assertNonNullable)(a,"No segments for starting representation");let s=this.initData.get(i);if((0,y.assertNonNullable)(s,"No init buffer for starting representation"),!(s 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(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=o,this.isLive=!!d?.dynamic,this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.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((0,y.isNullable)(e)||(0,y.isNullable)(this.downloadingRepresentationId)||(0,y.isNullable)(this.playingRepresentationId)||(0,y.isNullable)(this.sourceBuffer)||!(0,y.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,y.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next((r?.time.to??0)-(r?.time.from??0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Ge(this.sourceBuffer.buffered,e),l=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+100&&(a=l)}if(isFinite(this.bufferLimit)&&Cr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ge(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{let c=o.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&Ge(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=i.at(-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}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;(0,y.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,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?.streams[this.kind].flatMap(r=>r.representations).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){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!ht(i.segmentReference))return;let r=i.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),a=this.segments.get(i.id)??[],s=a.at(-1)?.time.to??0,o=r?.findIndex(u=>Math.floor(s)>=Math.floor(u.time.from)&&Math.floor(s)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,u)}else{let u=r.slice(o+1);this.segments.set(i.id,[...a,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,y.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let i=t.segmentReference;if(!ht(i))return;let r=this.segments.get(t.id)??[],a=r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to),!!!r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*i.timescale/1e3).toString(10),u=pt(i.segmentTemplateUrl,{segmentTime:o});r.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(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:l,time:{from:h,to:m}},f)=>{let v=h<=i&&m>=i,T=h>i||v||f===0&&i===0,$=Math.min(this.forwardBufferTarget,this.bufferLimit),Q=this.preloadOnly&&h<=i+$||m<=i+$;return(l==="none"||l==="partially_ejected"&&T&&Q&&this.sourceBuffer&&!Gt(this.sourceBuffer.buffered,i))&&T&&Q});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=r;l<a.length&&(s<=d||o<=c);l++){let h=a[l];if(s+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}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:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,y.abortable)(o,async function*(){let c=(0,y.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!c)return;let l=new DataView(c);if(!isFinite(r.segment.time.to)){let h=t.segmentReference.timescale,m=Lt(t.mime);r.segment.time.to=m.getSegmentEndTime(l,h)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(l,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),li(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await(0,y.abortable)(s,async function*(){let u=(0,y.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),(0,y.fromEvent)(window,"online").pipe((0,y.once)()).subscribe(()=>{d(),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(u){this.abortActiveSegments(e),li(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(ht(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,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ht(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=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,c)=>{if(!a.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:d,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:u,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)return;let s=this.representations.get(t);if(s)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Lt(s.mime).parseFeedableSegmentChunk(d,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,d=e.byteLength;for(let c of this.activeSegments){let{segment:l}=c,h=u==="byteRange",m=h?l.byte.to-l.byte.from+1:d;if(c.representationId!==t||!(!h||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(a.aborted){s();continue}let v=h?l.byte.from-i:0,T=h?l.byte.to-i:e.byteLength,$=v<r,Q=T<=r;if(l.status==="downloading"&&$&&Q){l.status="downloaded";let C=new DataView(e.buffer,e.byteOffset+v,m);this.sourceBufferTaskQueue.append(C,a).then(g=>g&&!a.aborted?this.onSegmentFullyAppended(c,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&$&&(c.loadedBytes=Math.min(m,r-v),c.loadedBytes>c.feedingBytes)){let C=new DataView(e.buffer,e.byteOffset+v+c.feedingBytes,c.loadedBytes-c.feedingBytes),g=c.loadedBytes===m?C:Lt(o.mime).parseFeedableSegmentChunk(C);g?.byteLength&&(l.status="partially_fed",c.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,a).then(I=>{if(a.aborted)s();else if(I)c.fedBytes+=g.byteLength,c.fedBytes===m&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<m)return;s()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:d}=u;if(u.representationId!==t)continue;if(a.aborted){s();continue}let c=d.byte.from-i,l=d.byte.to-i,h=l-c+1,m=c<r,f=l<=r;if(m){if(d.status==="downloading"&&f){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-c),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),T=u.loadedBytes===h?v:Lt(o.mime).parseFeedableSegmentChunk(v);T?.byteLength&&(d.status="partially_fed",u.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,a)&&!a.aborted?(u.fedBytes+=T.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):s())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",zi(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.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let 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?(0,y.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,y.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Lt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:d,segments:c}=o,l=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,l);let h=c;this.isLive&&ht(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:y.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,y.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=u=>{u.sort((c,l)=>c.from-l.from);let d=[u[0]];for(let c=1;c<u.length;c++){let{from:l,to:h}=u[c],m=d[d.length-1];m.to>=l?m.to=Math.max(m.to,h):d.push(u[c])}return d},o=u=>{if(a>=t)return r;r.push(u.time),r=s(r);let d=zi(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){let c=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||l)&&d.status==="fed"&&o(d)}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,l=0;for(let h of this.segments.values())for(let m of h)m.status==="none"&&Math.round(m.time.from)<=Math.round(d)&&Math.round(m.time.to)>=Math.round(c)&&l++;if(l===this.segments.size){let h={time:{from:d,to:c},url:"",status:"none"};o(h)}}if(r.length&&i){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"&&o(c)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,c)=>d||c,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,y.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,o=!1,u=d=>{a=Math.min(a,d.time.from),s=Math.max(s,d.time.to);let c=zi(d)?d.size??0:d.byte.to-d.byte.from;r+=c};for(let d of this.segments.values())for(let c of d){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(a)&&isFinite(s),!o){r=0,a=1/0,s=-1/0;for(let d of this.segments.values())for(let c of d){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(a)&&isFinite(s),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){let c=this.sourceBuffer.buffered.start(d)*1e3,l=this.sourceBuffer.buffered.end(d)*1e3;for(let h of this.segments.values())for(let m of h)if(m.status==="none"&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.time.to)>=Math.round(l)){a=c,s=l;break}}if(o=isFinite(a)&&isFinite(s),!o&&i){r=0,a=1/0,s=-1/0;let d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>e+d&&l.status==="fed"&&u(l)}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:y.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,y.isNullable)(this.sourceBuffer)||(0,y.isNullable)(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),u=e.some(c=>c.from-t<=s&&c.to+t>=o),d=e.filter(c=>s>=c.from-t&&s<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(d.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var pi=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var Fa=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}};var J=require("@vkontakte/videoplayer-shared");var Ki=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new J.ValueSubject(void 0);this.lastConnectionReused$=new J.ValueSubject(void 0);this.lastRequestFirstBytes$=new J.ValueSubject(void 0);this.abortAllController=new AbortController;this.subscription=new J.Subscription;this.fetchManifest=(0,J.abortable)(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=pi(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(hi);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));this.fetch=(0,J.abortable)(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:u=!1}={}){let d=e,c=new Headers;if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let B=new URL(d,location.href);B.searchParams.append("bytes",`${i.from}-${i.to}`),d=B.toString();break}default:(0,J.assertNever)(t)}this.requestQuic&&(d=pi(d));let l=this.abortAllController.signal,h;if(s){let B=new AbortController;if(h=(0,J.merge)((0,J.fromEvent)(this.abortAllController.signal,"abort"),(0,J.fromEvent)(s,"abort")).subscribe(()=>{try{B.abort()}catch(W){hi(W)}}),this.abortAllController.signal.aborted||s.aborted)try{B.abort()}catch(W){hi(W)}l=B.signal}let m=(0,J.now)(),f=yield fetch(d,{priority:a,headers:c,signal:l}).catch(hi),v=(0,J.now)();if(!f)return h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-m),!f.ok||!f.body)return h?.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));if(this.onHeadersReceived(f.headers),!r&&!o)return h?.unsubscribe(),f.arrayBuffer();let[T,$]=f.body.tee(),Q=T.getReader();o&&this.throughputEstimator?.trackStream($,u);let C=0,g=new Uint8Array(0),I=!1,H=B=>{h?.unsubscribe(),I=!0,hi(B)},x=(0,J.abortable)(l,async function*({done:B,value:W}){if(C===0&&this.lastRequestFirstBytes$.next((0,J.now)()-m),l.aborted){h?.unsubscribe();return}if(!B&&W){let k=new Uint8Array(g.length+W.length);k.set(g),k.set(W,g.length),g=k,C+=W.byteLength,r?.(new DataView(g.buffer),C),yield Q?.read().then(x,H)}}.bind(this));return yield Q?.read().then(x,H),h?.unsubscribe(),I?null:g.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,J.abortable)(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,u=!1,d,c;e.indexRange&&(d=e.indexRange.from,c=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),o=Math.max(c,a))),s=Math.min(s,0);let l=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!l)return null;let h=new DataView(l,r-s,a-s+1);if(!t.validateData(h))throw new Error("Invalid media file");let m=t.parseInit(h),f=e.indexRange??t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let v;if(u)v=new DataView(l,f.from-s,f.to-f.from+1);else{let $=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!$)return null;v=new DataView($)}let T=t.parseSegments(v,m,f);return{init:m,dataView:new DataView(l),segments:T}}.bind(this));this.fetchTemplateRepresentation=(0,J.abortable)(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}=Fa(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:(0,J.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},hi=n=>{if(!li(n))throw n};var mt=(n,e,t)=>t*e+(1-t)*n,Nr=(n,e)=>n.reduce((t,i)=>t+i,0)/e,Ua=(n,e,t,i)=>{let r=0,a=t,s=Nr(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};var mi=require("@vkontakte/videoplayer-shared"),tt=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 mi.ValueSubject(e.initial),this.debounced$=new mi.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ue(`raw_${t}`),this.smoothedSeries$=new ue(`smoothed_${t}`),this.reportedSeries$=new ue(`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)&&((0,mi.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Ji=class extends tt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=mt(this.slow,t,this.params.emaAlphaSlow),this.fast=mt(this.fast,t,this.params.emaAlphaFast);let i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast)}};var Xi=class extends tt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let i=Nr(this.pastMeasures,this.takenMeasures);this.emaSmoothed=mt(this.emaSmoothed,t,this.params.emaAlpha);let r=Ua(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:i}};var Zi=class extends tt{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?mt(this.smoothed,t,this.params.emaAlpha):t}};var ft=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ji({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Xi({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 Zi({initial:e,label:"liveEdgeDelay",...t})}};var Fr=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};var Ga=["timeupdate","progress","play","seeked","stalled","waiting"];var er=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new b.Subscription;this.representationSubscription=new b.Subscription;this.state$=new N("none");this.currentVideoRepresentation$=new b.ValueSubject(void 0);this.currentVideoRepresentationInit$=new b.ValueSubject(void 0);this.currentAudioRepresentation$=new b.ValueSubject(void 0);this.currentVideoSegmentLength$=new b.ValueSubject(0);this.currentAudioSegmentLength$=new b.ValueSubject(0);this.error$=new b.Subject;this.lastConnectionType$=new b.ValueSubject(void 0);this.lastConnectionReused$=new b.ValueSubject(void 0);this.lastRequestFirstBytes$=new b.ValueSubject(void 0);this.isLive$=new b.ValueSubject(!1);this.liveDuration$=new b.ValueSubject(0);this.liveAvailabilityStartTime$=new b.ValueSubject(void 0);this.bufferLength$=new b.ValueSubject(0);this.liveLoadBufferLength$=new b.ValueSubject(0);this.livePositionFromPlayer$=new b.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new b.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new b.Subject;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=(0,b.abortable)(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=oe(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:b.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,b.abortable)(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:b.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=Va(e??"",this.manifestUrlString)}catch(a){let s=Ta(e)??{id:"ManifestParsing",category:b.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(s)}if(!t)return null;let i=(a,s,o)=>!!(this.element?.canPlayType?.(s)&&Qe()?.isTypeSupported?.(`${s}; codecs="${o}"`)||a==="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 r={text:t.streams.text,video:[],audio:[]};for(let a of["video","audio"]){let o=t.streams[a].filter(({mime:c,codecs:l})=>i(a,c,l)),u=new Set(o.map(({codecs:c})=>c)),d=ya(u);if(d&&(r[a]=o.filter(({codecs:c})=>c.startsWith(d))),a==="video"){let c=Ia(),l=this.tuning.preferHDR,h=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);c&&l&&h?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}return{...t,streams:r}}.bind(this));this.initRepresentations=(0,b.abortable)(this.destroyController.signal,async function*(e,t,i){(0,b.assertNonNullable)(this.manifest),(0,b.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add((0,b.fromEvent)(l,"error").pipe((0,b.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:b.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?pa():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 l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((l,h)=>[...l,...h.representations],[]);if(this.videoBufferManager=new ci("video",this.source,o,s),this.bufferManagers=[this.videoBufferManager],(0,b.isNonNullable)(t)){let l=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new ci("audio",this.source,l,s),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,b.interval)(1e3).subscribe(l=>{if(this.element?.paused){let h=vr(this.manifestUrlString,2);this.manifestUrlString=oe(this.manifestUrlString,h+1e3,2)}})),this.representationSubscription.add((0,b.merge)(...Ga.filter(l=>l!=="waiting").map(l=>(0,b.fromEvent)(this.element,l))).pipe((0,b.map)(l=>this.element?Ge(this.element.buffered,this.element.currentTime*1e3):0),(0,b.filterChanged)(),(0,b.filter)(l=>!!l),(0,b.tap)(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,b.filterChanged)()).subscribe(h=>Fr(this.element,1))),this.representationSubscription.add((0,b.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,b.filter)(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add((0,b.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:m})=>{if(!m)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,$=h-f,Q=1;Math.abs($)>v&&(Q=1+Math.sign($)*T),Fr(this.element,Q)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let l=0;this.representationSubscription.add((0,b.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,b.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if((0,b.assertNonNullable)(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,v=vr(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,$=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),Q=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,C=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,g=isFinite(h)?h:m,I=this.isActiveLowLatency$.getValue(),H=T<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(I&&H);let x="none";if(I?x="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&H?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),x="active_low_latency"):v!==0&&g<$?x="live_forward_buffering":g<$+C&&(x="live_with_target_offset"),isFinite(h)&&(l=h>l?h:l),x==="live_forward_buffering"||x==="live_with_target_offset"){let B=l-($+Q),W=this.normolizeLiveOffset(Math.trunc(v+B/f)),k=Math.abs(W-v),j;!h||k<=this.tuning.dashCmafLive.offsetCalculationError?j=v:W>0&&k>this.tuning.dashCmafLive.offsetCalculationError?j=W:j=0,this.manifestUrlString=oe(this.manifestUrlString,j,2)}x!=="none"&&x!=="active_low_latency"&&(l=0,this.updateLive())}))}let u=(0,b.merge)(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe((0,b.map)(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),d=(0,b.merge)(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe((0,b.map)(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add((0,b.merge)(this.forceEnded$,(0,b.combine)({allBuffersFull:u,someBufferEnded:d}).pipe((0,b.filter)(({allBuffersFull:l,someBufferEnded:h})=>l&&h))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:b.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add((0,b.merge)(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(l=>this.source?.addEventListener("sourceopen",l)));let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>l.duration??0)];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&(0,b.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,b.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:b.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ki({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=ft.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){(0,b.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=oe(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio))}initBuffer(){(0,b.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,b.merge)(...Ga.map(e=>(0,b.fromEvent)(this.element,e)),(0,b.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:b.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,b.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,b.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Gt(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`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let t=this.element.currentTime*1e3;this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)}}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,b.interval)(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:b.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){(0,b.assertNonNullable)(this.element),(0,b.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Gt(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)}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$.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 tr=class{constructor(e,t){this.fov=e,this.orientation=t}};var ir=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 Qa=`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
|
|
48
|
+
`;var Wa=`#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 ls=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new os(this.params.fov,this.params.orientation),this.cameraRotationManager=new us(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(tm,this.gl.VERTEX_SHADER),r=this.createShader(rm,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,c=t+a,d=e-r,p=t+a;return[s,n,o,l,u,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Wt=class{constructor(e){this.subscription=new M.Subscription;this.videoState=new q("stopped");this.elementSize$=new M.ValueSubject(void 0);this.textTracksManager=new Me;this.droppedFramesManager=new Wa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ga;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.pause()):r?.to==="playing"&&P(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"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,M.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ls(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ns({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ye(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:M.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,l)=>this.subscription.add(o.subscribe(l,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,M.filter)(u=>!!u.length),(0,M.once)()).subscribe(u=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:u})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,M.filter)(M.isNonNullable),(0,M.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,M.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Xe(this.video,t.isLooped,a)),this.subscription.add(ve(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,M.observeElementSize)(this.video),this.elementSize$),s(De(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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 c=this.player.getStreams();if((0,M.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of c.audio){p.push(_o(f));let b=[];for(let S of f.representations){let T=Qf(S);b.push(T),this.audioTracksMap.set(T,{stream:f,representation:S})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(No(p));let f=[];for(let b of p.representations){let S=Wf(b);S&&(f.push(S),this.videoTracksMap.set(S,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let f of p.representations){let b=zf(p,f);this.textTracksMap.set(b,{stream:p,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:M.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add((0,M.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,M.fromEvent)(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,f]=d,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),u==="manifest_ready")this.player.initRepresentations(p.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),f){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,S).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,M.filterChanged)()).subscribe(u=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===u);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(No(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,M.filterChanged)()).subscribe(u=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===u);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(_o(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,M.map)(({to:u})=>u==="ready"),(0,M.filterChanged)());this.subscription.add((0,M.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,M.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,M.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,M.observableFrom)(["init"])).pipe((0,M.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:w})=>w===a),o=t.currentVideoTrack$.getValue(),l=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let u=[...this.videoStreamsMap.keys()].find(({id:w})=>w===l.id),c=u&&this.videoStreamsMap.get(u);if(!c)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:w})=>w===b?.id),T=0;if(S){if(n&&!r){let w=es(n,c,this.audioStreamsMap.get(S)??[]);T=Math.max(T,w?.bitrate??-1/0)}if(o){let w=es(o,c,this.audioStreamsMap.get(S)??[]);T=Math.max(T,w?.bitrate??-1/0)}}let I=Et(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:f,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:C}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(I=c.filter(w=>!(0,M.isInvariantQuality)(w.quality)).sort((w,_)=>(_.bitrate??0)-(w.bitrate??0)).filter(w=>(0,M.isLowerOrEqual)(w.quality,I.quality)&&(0,M.isLowerOrEqual)(w.quality,C))[0]??I);let B=r?I??n:n??I,y=S&&es(B,c,this.audioStreamsMap.get(S)??[]),x=this.videoTracksMap.get(B)?.representation,j=y&&this.audioTracksMap.get(y)?.representation;if(x&&j)return[x,j];if(x&&!j&&this.audioTracksMap.size===0)return[x,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:M.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ge(this.video)}};var Di=class extends Wt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Qt=require("@vkontakte/videoplayer-shared");var Oi=class extends Wt{constructor(e){super(e),this.liveOffset=new nt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,Qt.combine)({interval:(0,Qt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(a-1);s<=0&&e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add((0,Qt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Qt.map)(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var im=Ne(Ua(),1);var U=require("@vkontakte/videoplayer-shared"),Ye={};var wr=(i,e)=>new U.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Bi=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new q("initializing");this.textTracksManager=new Me;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,U.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,U.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,U.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,U.assertNever)(e)}break;default:(0,U.assertNever)(t)}};this.video=Se(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),ge(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:U.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,im.default)(import("hls.js").then(a=>{e||(Ye.Hls=a.default,Ye.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,U.assertNonNullable)(Ye.Hls,"hls.js not loaded"),this.hls=new Ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,U.assertNonNullable)(Ye.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:U.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=ye(this.video),s=(u,c)=>this.subscription.add(u.subscribe(c,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(Xe(this.video,e.isLooped,r)),this.subscription.add(ve(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ce(this.video,e.playbackRate,a.playbackRateState$,r)),s(De(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,U.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(wr(this.hls,Ye.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:U.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(wr(this.hls,Ye.Events.MANIFEST_PARSED).pipe((0,U.map)(({levels:u})=>u.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:f,height:b}=d,S=It(d.attrs.QUALITY??"")??(0,U.videoSizeToQuality)({width:f,height:b});if(!S)return c;let T=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,I={id:p.toString(),quality:S,bitrate:d.bitrate/1e3,size:{width:f,height:b},fps:T};return this.trackLevels.set(p,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(wr(this.hls,Ye.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let p=d.name,f=d.attrs.URI||"",b=d.lang,S="internal";c.push({id:p,url:f,language:b,type:S})}e.internalTextTracks.startTransitionTo(c)}}),s(wr(this.hls,Ye.Events.LEVEL_LOADING).pipe((0,U.map)(({url:u})=>oe(u))),t.hostname$),s(wr(this.hls,Ye.Events.FRAG_CHANGED),u=>{let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(Tt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=wr(this.hls,Ye.Events.LEVEL_SWITCHED).pipe((0,U.map)(({level:u})=>n(this.hls.levels[u])));o.pipe((0,U.filter)(U.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Tt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if((0,U.isNullable)(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,f=this.hls.levels[p];!f||c.bitrate>f.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=(0,U.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Te(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),P(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"),P(this.params.desiredState.playbackState,"stopped",!0)}};var am="X-Playback-Duration",Uo=async i=>{let e=await ct(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(am)?parseInt(e.headers.get(am),10):void 0};var F=require("@vkontakte/videoplayer-shared");var jo=Ne(Pn(),1);var cs=require("@vkontakte/videoplayer-shared");var $x=i=>{let e=null;if(i.QUALITY&&(e=It(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,cs.videoSizeToQuality)({width:t,height:r})}return e??null},Cx=(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,jo.default)(o[1].split(",").map(T=>T.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,d=$x(u),p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let f=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,b;if(u.RESOLUTION){let[T,I]=u.RESOLUTION.split("x").map(C=>parseInt(C,10));T&&I&&(b={width:T,height:I})}let S=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:S,bandwidth:p,size:b,fps:f})}if(l){let u=(0,jo.default)(l[1].split(",").map(f=>f.split("=")).map(([f,b])=>[f,b.replace(/^"|"$/g,"")])),c=u.URI?.replace(/playlist$/,"subtitles.vtt"),d=u.LANGUAGE,p=u.NAME;c&&d&&a.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},Mx=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Ho=0,sm=async(i,e=i,t)=>{let a=await(await ct(i)).text();Ho+=1;try{let{qualityManifests:s,textTracks:n}=Cx(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Ho<=t.manifestRetryMaxCount)return await Mx((0,cs.getExponentialDelay)(Ho-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),sm(i,e,t)}return{qualityManifests:[],textTracks:[]}},ds=sm;var Vi=class{constructor(e){this.subscription=new F.Subscription;this.videoState=new q("stopped");this.textTracksManager=new Me;this.manifests$=new F.ValueSubject([]);this.liveOffset=new nt;this.manifestStartTime$=new F.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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 c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),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"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else a?.to==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,F.assertNever)(t)}};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:F.VideoQuality.INVARIANT,url:this.params.source.url},ds(de(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:F.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:F.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.maxSeekBackTime$=new F.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:F.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ye(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(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),s(De(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,F.filterChanged)(),(0,F.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&(0,F.isNonNullable)(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(f=>f.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(oe(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,F.combine)({startTime:this.manifestStartTime$.pipe((0,F.filter)(F.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe((0,F.map)(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,F.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,F.observableFrom)(["init"])).pipe((0,F.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){let e=this.selectManifest();if((0,F.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:l}=t?.to??r??{};for(let[u,c]of[[o,"mq"],[l,"lq"]]){let d=String(parseFloat(u||""));c&&u&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=de(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Uo(n).then(o=>{if(!(0,F.isNullable)(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,F.isNullable)(l)||!isFinite(l))try{ct(n).then(u=>u.text()).then(u=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(c){let d=new URL(c,n).toString();Uo(d).then(p=>{(0,F.isNullable)(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){Te(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:F.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};var G=require("@vkontakte/videoplayer-shared");var _i=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new q("stopped");this.textTracksManager=new Me;this.manifests$=new G.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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 c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,G.assertNever)(t)}};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:G.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ds(de(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:G.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:G.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ye(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$),s(this.videoState.stateChangeEnded$.pipe((0,G.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Xe(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&(0,G.isNonNullable)(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(f=>f.id===d);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(oe(p.url));let f=this.params.desiredState.playbackRate.getState(),b=this.params.output.element$.getValue()?.playbackRate;if(f!==b){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(f),S.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,G.map)(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!(0,G.isIOS)()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,G.merge)((0,G.fromEvent)(o,"addtrack"),(0,G.fromEvent)(o,"removetrack"),(0,G.fromEvent)(o,"change"),(0,G.observableFrom)(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=(0,G.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){let e=this.selectManifest();if((0,G.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,l]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));l&&o&&a.searchParams.set(l,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){Te(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var J=require("@vkontakte/videoplayer-shared");var Ni=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new q("stopped");this.trackUrls={};this.textTracksManager=new Me;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,J.assertNever)(e)}};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:J.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ye(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$),s(this.videoState.stateChangeEnded$.pipe((0,J.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Xe(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),s(De(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,J.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(l!==u){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(l),c.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,J.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,J.observableFrom)(["init"])).pipe((0,J.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ge(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,J.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,J.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Li(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){Te(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:J.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!(0,J.isInvariantQuality)(o.track.quality)&&(0,J.isLowerOrEqual)(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&(0,J.isHigherOrEqual)(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!(0,J.isInvariantQuality)(u.track.quality)&&(0,J.isHigher)(u.track.quality,e)),l=o.length;l&&(t=o[l-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=Et(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};var Z=require("@vkontakte/videoplayer-shared");var om=require("@vkontakte/videoplayer-shared"),nm=["stun:videostun.mycdn.me:80"],Dx=1e3,Ox=3,Go=()=>null,ps=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Go;this.externalStopCallback=Go;this.externalErrorCallback=Go;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:nm}]};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:om.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Dx)}normalizeOptions(e={}){let t={stunServerList:nm,maxRetryNumber:Ox,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Fi=class{constructor(e){this.videoState=new q("stopped");this.maxSeekBackTime$=new Z.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,Z.assertNever)(e)}};this.subscription=new Z.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Se(e.container,e.tuning),this.liveStreamClient=new ps(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Z.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,Z.merge)(this.videoState.stateChangeStarted$.pipe((0,Z.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Z.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ye(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(De(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(ve(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,Z.assertNever)(n.to)}},r)).add((0,Z.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Z.VideoQuality.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Z.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Te(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Z.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var qi=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var v=require("@vkontakte/videoplayer-shared");var ft=require("@vkontakte/videoplayer-shared"),um=i=>new ft.Observable(e=>{let t=new ft.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,ft.map)(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,ft.map)(({type:u})=>u!==void 0)),n=new ft.Subject,o=0,l="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),l=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Le=require("@vkontakte/videoplayer-shared");var Ui=null,hs=null;function Yo(){return Ui||(Ui=new(window.AudioContext||window.webkitAudioContext)),hs||(hs=new GainNode(Ui,{gain:1}),hs.connect(Ui.destination)),{audioCtx:Ui,gainNode:hs}}var fs=require("@vkontakte/videoplayer-shared");var Hi=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new Le.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe((0,Le.filter)(n=>!!n.type),(0,Le.once)()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){let{browser:t}=(0,fs.getCurrentBrowser)();t===fs.CurrentClientBrowser.Safari&&e!=="MPEG"||this.subscriptions.add((0,Le.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Le.filter)(({playbackState:r,video:a,volume:{muted:s,volume:n}})=>r==="playing"&&!!a&&!s&&!!n),(0,Le.once)()).subscribe(({video:r})=>this.initAudioContextOnce(r)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:a}=Yo(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${i.errorId} destroyed`);a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch(n){this.volumeMultiplierError$.next({id:i.errorId,category:Le.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:Le.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Yo();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var Bx={chunkDuration:5e3,maxParallelRequests:5},ji=class{constructor(e){this.current$=new v.ValueSubject({type:void 0});this.providerError$=new v.Subject;this.noAvailableProvidersError$=new v.Subject;this.volumeMultiplierError$=new v.Subject;this.providerOutput={position$:new v.ValueSubject(0),duration$:new v.ValueSubject(1/0),volume$:new v.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new v.ValueSubject([]),currentVideoStream$:new v.ValueSubject(void 0),availableVideoTracks$:new v.ValueSubject([]),currentVideoTrack$:new v.ValueSubject(void 0),availableAudioStreams$:new v.ValueSubject([]),currentAudioStream$:new v.ValueSubject(void 0),availableAudioTracks$:new v.ValueSubject([]),currentVideoSegmentLength$:new v.ValueSubject(0),currentAudioSegmentLength$:new v.ValueSubject(0),isAudioAvailable$:new v.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new v.ValueSubject(!1),autoVideoTrackLimits$:new v.ValueSubject(void 0),currentBuffer$:new v.ValueSubject(void 0),isBuffering$:new v.ValueSubject(!0),error$:new v.Subject,warning$:new v.Subject,willSeekEvent$:new v.Subject,seekedEvent$:new v.Subject,loopedEvent$:new v.Subject,endedEvent$:new v.Subject,firstBytesEvent$:new v.Subject,firstFrameEvent$:new v.Subject,canplay$:new v.Subject,isLive$:new v.ValueSubject(void 0),isLowLatency$:new v.ValueSubject(!1),canChangePlaybackSpeed$:new v.ValueSubject(!0),liveTime$:new v.ValueSubject(void 0),liveBufferTime$:new v.ValueSubject(void 0),availableTextTracks$:new v.ValueSubject([]),currentTextTrack$:new v.ValueSubject(void 0),hostname$:new v.ValueSubject(void 0),httpConnectionType$:new v.ValueSubject(void 0),httpConnectionReused$:new v.ValueSubject(void 0),inPiP$:new v.ValueSubject(!1),inFullscreen$:new v.ValueSubject(!1),element$:new v.ValueSubject(void 0),elementVisible$:new v.ValueSubject(!0),availableSources$:new v.ValueSubject(void 0),is3DVideo$:new v.ValueSubject(!1),playbackState$:new v.ValueSubject("")};this.subscription=new v.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=tf([...af(this.params.tuning),...rf(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,v.isNonNullable)(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new qi(s);let n=[...wo(!0),...wo(!1)];this.chromecastFormatsIterator=new qi(n.filter(o=>(0,v.isNonNullable)(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Hi(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((0,v.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.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(0,v.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,v.assertNonNullable)(o),new Di({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Oi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),gr||!this.params.tuning.useHlsJs?new _i({...n,source:o}):new Bi({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Vi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Ni({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Yh({...n,source:o,config:{...Bx,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Fi({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,v.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,v.assertNonNullable)(o),new Kr({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,v.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,v.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,v.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,lm.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,r=0;return e.add((0,v.merge)(this.providerOutput.error$,um({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,v.map)(a=>({id:`ProviderHangup:${a}`,category:v.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe((0,v.filter)(({to:s})=>s==="playing"),(0,v.once)()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=a.category===v.ErrorCategory.NETWORK,o=a.category===v.ErrorCategory.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}};var V=require("@vkontakte/videoplayer-shared");var Vx=5e3,cm="one_video_throughput",dm="one_video_rtt",Gi=window.navigator.connection,pm=()=>{let i=Gi?.downlink;if((0,V.isNonNullable)(i)&&i!==10)return i*1e3},hm=()=>{let i=Gi?.rtt;if((0,V.isNonNullable)(i)&&i!==3e3)return i},fm=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Wo=class i{constructor(e){this.subscription=new V.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(cm)||(e.useBrowserEstimation?pm():void 0)||Vx,r=i.load(dm)??(e.useBrowserEstimation?hm():void 0)??0;if(this.throughput$=new V.ValueSubject(t),this.rtt$=new V.ValueSubject(r),this.rttAdjustedThroughput$=new V.ValueSubject(fm(t,r,e.rttPenaltyRequestSize)),this.throughput=Yt.getSmoothedValue(t,-1,e),this.rtt=Yt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=pm();n&&this.throughput.next(n);let o=hm();(0,V.isNonNullable)(o)&&this.rtt.next(o)};Gi&&"onchange"in Gi&&this.subscription.add((0,V.fromEvent)(Gi,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{V.safeStorage.set(cm,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{V.safeStorage.set(dm,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,V.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,V.map)(({throughput:a,rtt:s})=>fm(a,s,e.rttPenaltyRequestSize)),(0,V.filter)(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,V.now)(),a=new V.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,V.fromEvent)(e,"progress").pipe((0,V.once)()).subscribe(s=>{t=s.loaded,r=(0,V.now)()}));break;case 1:case 0:a.add((0,V.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,V.now)()}));break}a.add((0,V.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,V.now)(),l=n-t,u=o-r;this.addRawSpeed(l,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=(0,V.now)(),n=0,o=(0,V.now)(),l=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,(0,V.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,V.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=(0,V.now)()}else n+=d.byteLength;o=(0,V.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,V.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,V.now)()-o,this.concurrentDownloads.size),n=0,o=(0,V.now)());await r?.read().then(u,l)}};this.concurrentDownloads.add(e),r?.read().then(u,l)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=V.safeStorage.get(e);if((0,V.isNonNullable)(t))return parseInt(t,10)??void 0}},mm=Wo;var Yi=require("@vkontakte/videoplayer-shared"),bm={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:Yi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Yi.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Sm=i=>({...(0,Yi.fillWithDefault)(i,bm),configName:[...i.configName??[],...bm.configName]});var h=require("@vkontakte/videoplayer-shared");var mt=require("@vkontakte/videoplayer-shared"),Qo=({seekState:i,position$:e})=>(0,mt.merge)(i.stateChangeEnded$.pipe((0,mt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,mt.filter)(mt.isNonNullable)),e.pipe((0,mt.filter)(()=>i.getState().state==="none")));var gm=require("@vkontakte/videoplayer-shared"),vm=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,gm.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var ms=require("@vkontakte/videoplayer-shared"),ym=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,ms.filter)(a=>a.length>0),(0,ms.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Wi=class{constructor(e={configName:[]}){this.subscription=new h.Subscription;this.logger=new h.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new h.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new q("stopped"),seekState:new q({state:"none"}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),videoStream:new q(void 0),audioStream:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};this.info={playbackState$:new h.ValueSubject("stopped"),position$:new h.ValueSubject(0),duration$:new h.ValueSubject(1/0),muted$:new h.ValueSubject(!1),volume$:new h.ValueSubject(1),availableVideoStreams$:new h.ValueSubject([]),currentVideoStream$:new h.ValueSubject(void 0),availableQualities$:new h.ValueSubject([]),availableQualitiesFps$:new h.ValueSubject({}),currentQuality$:new h.ValueSubject(void 0),isAutoQualityEnabled$:new h.ValueSubject(!0),autoQualityLimitingAvailable$:new h.ValueSubject(!1),autoQualityLimits$:new h.ValueSubject({}),availableAudioStreams$:new h.ValueSubject([]),currentAudioStream$:new h.ValueSubject(void 0),availableAudioTracks$:new h.ValueSubject([]),isAudioAvailable$:new h.ValueSubject(!0),currentPlaybackRate$:new h.ValueSubject(1),currentBuffer$:new h.ValueSubject({start:0,end:0}),isBuffering$:new h.ValueSubject(!0),isStalled$:new h.ValueSubject(!1),isEnded$:new h.ValueSubject(!1),isLooped$:new h.ValueSubject(!1),isLive$:new h.ValueSubject(void 0),canChangePlaybackSpeed$:new h.ValueSubject(void 0),atLiveEdge$:new h.ValueSubject(void 0),atLiveDurationEdge$:new h.ValueSubject(void 0),liveTime$:new h.ValueSubject(void 0),liveBufferTime$:new h.ValueSubject(void 0),currentFormat$:new h.ValueSubject(void 0),availableTextTracks$:new h.ValueSubject([]),currentTextTrack$:new h.ValueSubject(void 0),throughputEstimation$:new h.ValueSubject(void 0),rttEstimation$:new h.ValueSubject(void 0),videoBitrate$:new h.ValueSubject(void 0),hostname$:new h.ValueSubject(void 0),httpConnectionType$:new h.ValueSubject(void 0),httpConnectionReused$:new h.ValueSubject(void 0),surface$:new h.ValueSubject("none"),chromecastState$:new h.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new h.ValueSubject(void 0),intrinsicVideoSize$:new h.ValueSubject(void 0),availableSources$:new h.ValueSubject(void 0),is3DVideo$:new h.ValueSubject(!1),currentVideoSegmentLength$:new h.ValueSubject(0),currentAudioSegmentLength$:new h.ValueSubject(0)};this.events={inited$:new h.Subject,ready$:new h.Subject,started$:new h.Subject,playing$:new h.Subject,paused$:new h.Subject,stopped$:new h.Subject,willStart$:new h.Subject,willResume$:new h.Subject,willPause$:new h.Subject,willStop$:new h.Subject,willDestruct$:new h.Subject,watchCoverageRecord$:new h.Subject,watchCoverageLive$:new h.Subject,managedError$:new h.Subject,fatalError$:new h.Subject,ended$:new h.Subject,looped$:new h.Subject,seeked$:new h.Subject,willSeek$:new h.Subject,firstBytes$:new h.Subject,firstFrame$:new h.Subject,canplay$:new h.Subject,log$:new h.Subject};this.experimental={element$:new h.ValueSubject(void 0),tuningConfigName$:new h.ValueSubject([]),enableDebugTelemetry$:new h.ValueSubject(!1),dumpTelemetry:Uh};if(this.initLogs(),this.tuning=Sm(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ra({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new mm(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(d=>JSON.stringify(d,(p,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:h.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=vm(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ji({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&&!ri()?(0,h.fromEvent)(document,"visibilitychange").pipe((0,h.once)()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),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){(0,h.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,h.filter)(r=>r.length>0),(0,h.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){(0,h.assertNonNullable)(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 ym(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((0,h.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,h.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.filter)(({from:e})=>e==="stopped"),(0,h.once)()).subscribe(()=>{this.initedAt=(0,h.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:h.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,h.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,h.map)(n=>n.destination),(0,h.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,h.map)(n=>n.map(({quality:o})=>o).sort((o,l)=>(0,h.isInvariantQuality)(o)?1:(0,h.isInvariantQuality)(l)?-1:(0,h.isHigher)(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let l of n)l.fps&&(o[l.quality]=l.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.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((0,h.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe((0,h.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,h.combine)({hasLiveOffsetByPaused:(0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(n=>n.to),(0,h.filterChanged)(),(0,h.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,h.combine)({atLiveEdge:(0,h.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Qo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,h.map)(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,h.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,h.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,h.map)(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.muted),(0,h.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.volume),(0,h.filterChanged)()).subscribe(this.info.volume$)).add(Qo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,h.merge)(e.providerOutput.endedEvent$.pipe((0,h.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,h.mapTo)(!1))).pipe((0,h.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,h.map)(n=>({id:n?`No${n}`:"NoProviders",category:h.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,h.once)(),(0,h.map)(n=>n??(0,h.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new h.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new h.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.filter)(({to:n})=>n==="playing"),(0,h.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,h.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,h.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,h.filterChanged)());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add((0,h.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,h.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":l?u?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,h.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new h.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,h.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,h.filter)(r=>r.length>0),(0,h.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=Et(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,h.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,h.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;(0,h.assertNonNullable)(this.providerContainer),(0,h.assertNonNullable)(e),qh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Fh(t)),this.providerContainer.current$.subscribe(({type:t})=>Xr("provider",t)),e.duration$.subscribe(t=>Xr("duration",t)),e.availableVideoTracks$.pipe((0,h.filter)(t=>!!t.length),(0,h.once)()).subscribe(t=>Xr("tracks",t)),this.events.fatalError$.subscribe(new he("fatalError")),this.events.managedError$.subscribe(new he("managedError")),e.position$.subscribe(new he("position")),e.currentVideoTrack$.pipe((0,h.map)(t=>t?.quality)).subscribe(new he("quality")),this.info.currentBuffer$.subscribe(new he("buffer")),e.isBuffering$.subscribe(new he("isBuffering"))].forEach(t=>this.subscription.add(t)),Xr("codecs",ef())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:h.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,h.merge)((0,h.fromEvent)(document,"visibilitychange"),(0,h.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var et=require("@vkontakte/videoplayer-shared"),_x=`@vkontakte/videoplayer-core@${Es}`;
|
|
91
|
+
`;var rr=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 tr(this.params.fov,this.params.orientation),this.cameraRotationManager=new ir(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(Qa,this.gl.VERTEX_SHADER),i=this.createShader(Wa,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,u=t-r,d=e+i,c=t+r,l=e-i,h=t+r;return[a,s,o,u,d,c,l,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var bt=class{constructor(e){this.subscription=new M.Subscription;this.videoState=new N("stopped");this.elementSize$=new M.ValueSubject(void 0);this.textTracksManager=new xe;this.droppedFramesManager=new Gi;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ui;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"),E(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.pause()):i?.to==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return(0,M.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new rr(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=ce(e.container,e.tuning),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new er({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=me(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:M.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,M.filter)(d=>!!d.length),(0,M.once)()).subscribe(d=>{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:d})})),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((0,M.filter)(M.isNonNullable),(0,M.once)()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe((0,M.map)(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ve(this.video,t.isLooped,r)),this.subscription.add(he(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ee(this.video,t.playbackRate,i.playbackRateState$,r)),a((0,M.observeElementSize)(this.video),this.elementSize$),a(ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if((0,M.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of c.audio){h.push(Or(m));let f=[];for(let v of m.representations){let T=_a(v);f.push(T),this.audioTracksMap.set(T,{stream:m,representation:v})}this.audioStreamsMap.set(m,f)}this.params.output.availableAudioStreams$.next(h)}let l=[];for(let h of c.video){l.push(_r(h));let m=[];for(let f of h.representations){let v=Oa(f);v&&(m.push(v),this.videoTracksMap.set(v,{stream:h,representation:f}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(l);for(let h of c.text)for(let m of h.representations){let f=Na(h,m);this.textTracksMap.set(f,{stream:h,representation:m})}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 d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=d=>e.error$.next({id:"RepresentationSwitch",category:M.ErrorCategory.WTF,message:"Switching representations threw",thrown:d});this.subscription.add((0,M.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,M.fromEvent)(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(d)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoAudioRepresentations();if(!l)return;let[h,m]=l,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),d==="manifest_ready")this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(s),m){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,v).catch(s)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,M.filterChanged)()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[l,{stream:h}]=c,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(l),e.currentVideoStream$.next(_r(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,M.filterChanged)()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[l,{stream:h}]=c,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Or(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}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((0,M.map)(({to:d})=>d==="ready"),(0,M.filterChanged)());this.subscription.add((0,M.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add((0,M.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,M.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,M.observableFrom)(["init"])).pipe((0,M.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=e.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:x})=>x===r),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let d=[...this.videoStreamsMap.keys()].find(({id:x})=>x===u.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let l=Ge(this.video.buffered,this.video.currentTime*1e3),h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(l/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:x})=>x===f?.id),T=0;if(v){if(s&&!i){let x=qi(s,c,this.audioStreamsMap.get(v)??[]);T=Math.max(T,x?.bitrate??-1/0)}if(o){let x=qi(o,c,this.audioStreamsMap.get(v)??[]);T=Math.max(T,x?.bitrate??-1/0)}}let $=et(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:m,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:Q}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&i&&($=c.filter(x=>!(0,M.isInvariantQuality)(x.quality)).sort((x,B)=>(B.bitrate??0)-(x.bitrate??0)).filter(x=>(0,M.isLowerOrEqual)(x.quality,$.quality)&&(0,M.isLowerOrEqual)(x.quality,Q))[0]??$);let C=i?$??s:s??$,g=v&&qi(C,c,this.audioStreamsMap.get(v)??[]),I=this.videoTracksMap.get(C)?.representation,H=g&&this.audioTracksMap.get(g)?.representation;if(I&&H)return[I,H];if(I&&!H&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){fe(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:M.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),pe(this.video)}};var bi=class extends bt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var St=require("@vkontakte/videoplayer-shared");var Si=class extends bt{constructor(e){super(e),this.liveOffset=new Fe}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((0,St.combine)({interval:(0,St.interval)(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((0,St.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,St.map)(({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)})}};var F=require("@vkontakte/videoplayer-shared"),Me={};var Mt=(n,e)=>new F.Observable(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),gi=class{constructor(e){this.subscription=new F.Subscription;this.videoState=new N("initializing");this.textTracksManager=new xe;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:(0,F.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,F.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,F.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,F.assertNever)(e)}break;default:(0,F.assertNever)(t)}};this.video=ce(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(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),pe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:F.ErrorCategory.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||(Me.Hls=r.default,Me.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){(0,F.assertNonNullable)(Me.Hls,"hls.js not loaded"),this.hls=new Me.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,F.assertNonNullable)(Me.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:F.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=me(this.video),a=(d,c)=>this.subscription.add(d.subscribe(c,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(Ve(this.video,e.isLooped,i)),this.subscription.add(he(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ee(this.video,e.playbackRate,r.playbackRateState$,i)),a(ke(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe((0,F.map)(d=>d.to)),this.params.output.playbackState$),this.subscription.add(Mt(this.hls,Me.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:F.ErrorCategory.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(Mt(this.hls,Me.Events.MANIFEST_PARSED).pipe((0,F.map)(({levels:d})=>d.reduce((c,l)=>{let h=l.name||l.height.toString(10),{width:m,height:f}=l,v=Ze(l.attrs.QUALITY??"")??(0,F.videoSizeToQuality)({width:m,height:f});if(!v)return c;let T=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,$={id:h.toString(),quality:v,bitrate:l.bitrate/1e3,size:{width:m,height:f},fps:T};return this.trackLevels.set(h,{track:$,level:l}),c.push($),c},[]))),t.availableVideoTracks$),a(Mt(this.hls,Me.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let c=[];for(let l of d.subtitleTracks){let h=l.name,m=l.attrs.URI||"",f=l.lang,v="internal";c.push({id:h,url:m,language:f,type:v})}e.internalTextTracks.startTransitionTo(c)}}),a(Mt(this.hls,Me.Events.LEVEL_LOADING).pipe((0,F.map)(({url:d})=>ae(d))),t.hostname$),a(Mt(this.hls,Me.Events.FRAG_CHANGED),d=>{let{video:c,audio:l}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3)}),this.subscription.add(Xe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));let s=d=>Array.from(this.trackLevels.values()).find(({level:c})=>c===d)?.track,o=Mt(this.hls,Me.Events.LEVEL_SWITCHED).pipe((0,F.map)(({level:d})=>s(this.hls.levels[d])));o.pipe((0,F.filter)(F.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Xe(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{if((0,F.isNullable)(d))return;let c=this.trackLevels.get(d.id)?.level;if(!c)return;let l=this.hls.levels.indexOf(c),h=this.hls.currentLevel,m=this.hls.levels[h];!m||c.bitrate>m.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,F.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,F.observableFrom)(["init"])).pipe((0,F.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await fe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:F.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),E(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"),E(this.params.desiredState.playbackState,"stopped",!0)}};var ja="X-Playback-Duration",Ur=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(ja)?parseInt(e.headers.get(ja),10):void 0};var _=require("@vkontakte/videoplayer-shared");var ar=require("@vkontakte/videoplayer-shared");var vn=n=>{let e=null;if(n.QUALITY&&(e=Ze(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,ar.videoSizeToQuality)({width:t,height:i})}return e??null},yn=(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:(.+)/),u=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let d=Object.fromEntries(o[1].split(",").map(T=>T.split("="))),c=d.QUALITY??`stream-${d.BANDWIDTH}`,l=vn(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,f;if(d.RESOLUTION){let[T,$]=d.RESOLUTION.split("x").map(Q=>parseInt(Q,10));T&&$&&(f={width:T,height:$})}let v=new URL(t[++a],e).toString();l&&i.push({id:c,quality:l,url:v,bandwidth:h,size:f,fps:m})}if(u){let d=Object.fromEntries(u[1].split(",").map(m=>m.split("=")).map(([m,f])=>[m,f.replace(/^"|"$/g,"")])),c=d.URI?.replace(/playlist$/,"subtitles.vtt"),l=d.LANGUAGE,h=d.NAME;c&&l&&r.push({type:"internal",id:l,label:h,language:l,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Tn=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),Hr=0,Ya=async(n,e=n,t)=>{let r=await(await fetch(n)).text();Hr+=1;try{let{qualityManifests:a,textTracks:s}=yn(r,e);return{qualityManifests:a,textTracks:s}}catch{if(Hr<=t.manifestRetryMaxCount)return await Tn((0,ar.getExponentialDelay)(Hr-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ya(n,e,t)}return{qualityManifests:[],textTracks:[]}},sr=Ya;var vi=class{constructor(e){this.subscription=new _.Subscription;this.videoState=new N("stopped");this.textTracksManager=new xe;this.manifests$=new _.ValueSubject([]);this.liveOffset=new Fe;this.manifestStartTime$=new _.ValueSubject(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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?E(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):r?.to==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,_.assertNever)(t)}};this.params=e,this.video=ce(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_.VideoQuality.INVARIANT,url:this.params.source.url},sr(oe(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:_.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.maxSeekBackTime$=new _.ValueSubject(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(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:_.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=me(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,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(he(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ee(this.video,t.playbackRate,r.playbackRateState$,i)),a(ke(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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((0,_.filterChanged)(),(0,_.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(0,_.isNonNullable)(d.to)){let l=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let h=this.manifests$.getValue().find(m=>m.id===l);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ae(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,_.combine)({startTime:this.manifestStartTime$.pipe((0,_.filter)(_.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,_.map)(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:h})=>({id:u,quality:d,size:c,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let s=(0,_.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,_.observableFrom)(["init"])).pipe((0,_.debounce)(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),pe(this.video)}prepare(){let e=this.selectManifest();if((0,_.isNullable)(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:u}=t?.to??i??{};for(let[d,c]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(d||""));c&&d&&r.searchParams.set(c,l)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=oe(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),Ur(s).then(o=>{if(!(0,_.isNullable)(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,_.isNullable)(u)||!isFinite(u))try{fetch(s).then(d=>d.text()).then(d=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d)?.[1];if(c){let l=new URL(c,s).toString();Ur(l).then(h=>{(0,_.isNullable)(h)||this.maxSeekBackTime$.next(h)})}})}catch{}}})}playIfAllowed(){fe(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};var G=require("@vkontakte/videoplayer-shared");var yi=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new N("stopped");this.textTracksManager=new xe;this.manifests$=new G.ValueSubject([]);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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?E(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,G.assertNever)(t)}};this.params=e,this.video=ce(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:G.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),sr(oe(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:G.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),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(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:G.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=me(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));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((0,G.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ve(this.video,t.isLooped,i)),this.subscription.add(he(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ee(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(0,G.isNonNullable)(d.to)){let l=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let h=this.manifests$.getValue().find(m=>m.id===l);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ae(h.url));let m=this.params.desiredState.playbackRate.getState(),f=this.params.output.element$.getValue()?.playbackRate;if(m!==f){let v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(m),v.playbackRate=m)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,G.map)(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:h})=>({id:u,quality:d,size:c,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!(0,G.isIOS)()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,G.merge)((0,G.fromEvent)(o,"addtrack"),(0,G.fromEvent)(o,"removetrack"),(0,G.fromEvent)(o,"change"),(0,G.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=(0,G.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),pe(this.video)}prepare(){let e=this.selectManifest();if((0,G.isNullable)(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,u]of[[a,"mq"],[s,"lq"]]){let d=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){fe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var K=require("@vkontakte/videoplayer-shared");var Ti=class{constructor(e){this.subscription=new K.Subscription;this.videoState=new N("stopped");this.trackUrls={};this.textTracksManager=new xe;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let 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:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*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"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):i?.to==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return(0,K.assertNever)(e)}};this.params=e,this.video=ce(e.container,e.tuning),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:K.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=me(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,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((0,K.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ve(this.video,t.isLooped,i)),this.subscription.add(he(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ee(this.video,t.playbackRate,r.playbackRateState$,i)),a(ke(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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&&(0,K.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(u!==d){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=(0,K.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,K.observableFrom)(["init"])).pipe((0,K.debounce)(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),pe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,K.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,K.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=pi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ae(t))}playIfAllowed(){fe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:K.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let r=Object.values(this.trackUrls).find(o=>!(0,K.isInvariantQuality)(o.track.quality)&&(0,K.isLowerOrEqual)(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,s=this.trackUrls[a??"0"]?.track;if(r&&s&&(0,K.isHigherOrEqual)(s.quality,r.quality)&&(t=r),!t){let o=Object.values(this.trackUrls).filter(d=>!(0,K.isInvariantQuality)(d.track.quality)&&(0,K.isHigher)(d.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(i=t.quality)}else if(!e){let r=Object.values(this.trackUrls).map(a=>a.track);t=et(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})}};var X=require("@vkontakte/videoplayer-shared");var za=require("@vkontakte/videoplayer-shared"),qa=["stun:videostun.mycdn.me:80"],In=1e3,En=3,Gr=()=>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=Gr;this.externalStopCallback=Gr;this.externalErrorCallback=Gr;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:qa}]};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:za.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),In)}normalizeOptions(e={}){let t={stunServerList:qa,maxRetryNumber:En,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ii=class{constructor(e){this.videoState=new N("stopped");this.maxSeekBackTime$=new X.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):i?.to==="playing"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return(0,X.assertNever)(e)}};this.subscription=new X.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ce(e.container,e.tuning),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),pe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:X.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};(0,X.merge)(this.videoState.stateChangeStarted$.pipe((0,X.map)(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,X.map)(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=me(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(ke(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(he(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(0,X.assertNever)(s.to)}},i)).add((0,X.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ae(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:X.VideoQuality.INVARIANT}),this.video.srcObject=e,E(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:X.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){fe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ei=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var S=require("@vkontakte/videoplayer-shared");var je=require("@vkontakte/videoplayer-shared"),Ka=n=>new je.Observable(e=>{let t=new je.Subscription,i=n.desiredPlaybackState$.stateChangeStarted$.pipe((0,je.map)(({from:d,to:c})=>`${d}-${c}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe((0,je.map)(({type:d})=>d!==void 0)),s=new je.Subject,o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Ie=require("@vkontakte/videoplayer-shared");var xi=null,or=null;function Qr(){return xi||(xi=new(window.AudioContext||window.webkitAudioContext)),or||(or=new GainNode(xi,{gain:1}),or.connect(xi.destination)),{audioCtx:xi,gainNode:or}}var dr=require("@vkontakte/videoplayer-shared");var ki=class n{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new Ie.Subscription;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe((0,Ie.filter)(s=>!!s.type),(0,Ie.once)()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){let{browser:t}=(0,dr.getCurrentBrowser)();t===dr.CurrentClientBrowser.Safari&&e!=="MPEG"||this.subscriptions.add((0,Ie.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Ie.filter)(({playbackState:i,video:r,volume:{muted:a,volume:s}})=>i==="playing"&&!!r&&!a&&!!s),(0,Ie.once)()).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}=Qr(),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:Ie.ErrorCategory.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:s})}}).catch(s=>{this.volumeMultiplierError$.next({id:n.errorId,category:Ie.ErrorCategory.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=Qr();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var xn={chunkDuration:5e3,maxParallelRequests:5},Pi=class{constructor(e){this.current$=new S.ValueSubject({type:void 0});this.providerError$=new S.Subject;this.noAvailableProvidersError$=new S.Subject;this.volumeMultiplierError$=new S.Subject;this.providerOutput={position$:new S.ValueSubject(0),duration$:new S.ValueSubject(1/0),volume$:new S.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new S.ValueSubject([]),currentVideoStream$:new S.ValueSubject(void 0),availableVideoTracks$:new S.ValueSubject([]),currentVideoTrack$:new S.ValueSubject(void 0),availableAudioStreams$:new S.ValueSubject([]),currentAudioStream$:new S.ValueSubject(void 0),availableAudioTracks$:new S.ValueSubject([]),currentVideoSegmentLength$:new S.ValueSubject(0),currentAudioSegmentLength$:new S.ValueSubject(0),isAudioAvailable$:new S.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new S.ValueSubject(!1),autoVideoTrackLimits$:new S.ValueSubject(void 0),currentBuffer$:new S.ValueSubject(void 0),isBuffering$:new S.ValueSubject(!0),error$:new S.Subject,warning$:new S.Subject,willSeekEvent$:new S.Subject,seekedEvent$:new S.Subject,loopedEvent$:new S.Subject,endedEvent$:new S.Subject,firstBytesEvent$:new S.Subject,firstFrameEvent$:new S.Subject,canplay$:new S.Subject,isLive$:new S.ValueSubject(void 0),isLowLatency$:new S.ValueSubject(!1),canChangePlaybackSpeed$:new S.ValueSubject(!0),liveTime$:new S.ValueSubject(void 0),liveBufferTime$:new S.ValueSubject(void 0),availableTextTracks$:new S.ValueSubject([]),currentTextTrack$:new S.ValueSubject(void 0),hostname$:new S.ValueSubject(void 0),httpConnectionType$:new S.ValueSubject(void 0),httpConnectionReused$:new S.ValueSubject(void 0),inPiP$:new S.ValueSubject(!1),inFullscreen$:new S.ValueSubject(!1),element$:new S.ValueSubject(void 0),elementVisible$:new S.ValueSubject(!0),availableSources$:new S.ValueSubject(void 0),is3DVideo$:new S.ValueSubject(!1),playbackState$:new S.ValueSubject("")};this.subscription=new S.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Sa([...va(this.params.tuning),...ga(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,S.isNonNullable)(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 Ei(a);let s=[...Mr(!0),...Mr(!1)];this.chromecastFormatsIterator=new Ei(s.filter(o=>(0,S.isNonNullable)(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new ki(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((0,S.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:S.ErrorCategory.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(0,S.assertNever)(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":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,S.assertNonNullable)(o),new bi({...s,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Si({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),kt||!this.params.tuning.useHlsJs?new yi({...s,source:o}):new gi({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new vi({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ti({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new la({...s,source:o,config:{...xn,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ii({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,S.assertNever)(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(0,S.assertNonNullable)(o),new Bt({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(0,S.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,S.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,S.assertNever)(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 S.Subscription,t=!1,i=0;return e.add((0,S.merge)(this.providerOutput.error$,Ka({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,S.map)(r=>({id:`ProviderHangup:${r}`,category:S.ErrorCategory.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((0,S.filter)(({to:a})=>a==="playing"),(0,S.once)()).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===S.ErrorCategory.NETWORK,o=r.category===S.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(s&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}})),e}};var V=require("@vkontakte/videoplayer-shared");var kn=5e3,Ja="one_video_throughput",Xa="one_video_rtt",Ai=window.navigator.connection,Za=()=>{let n=Ai?.downlink;if((0,V.isNonNullable)(n)&&n!==10)return n*1e3},es=()=>{let n=Ai?.rtt;if((0,V.isNonNullable)(n)&&n!==3e3)return n},ts=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},Wr=class n{constructor(e){this.subscription=new V.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(Ja)||(e.useBrowserEstimation?Za():void 0)||kn,i=n.load(Xa)??(e.useBrowserEstimation?es():void 0)??0;if(this.throughput$=new V.ValueSubject(t),this.rtt$=new V.ValueSubject(i),this.rttAdjustedThroughput$=new V.ValueSubject(ts(t,i,e.rttPenaltyRequestSize)),this.throughput=ft.getSmoothedValue(t,-1,e),this.rtt=ft.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=Za();s&&this.throughput.next(s);let o=es();(0,V.isNonNullable)(o)&&this.rtt.next(o)};Ai&&"onchange"in Ai&&this.subscription.add((0,V.fromEvent)(Ai,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{V.safeStorage.set(Ja,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{V.safeStorage.set(Xa,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,V.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,V.map)(({throughput:r,rtt:a})=>ts(r,a,e.rttPenaltyRequestSize)),(0,V.filter)(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=(0,V.now)(),r=new V.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,V.fromEvent)(e,"progress").pipe((0,V.once)()).subscribe(a=>{t=a.loaded,i=(0,V.now)()}));break;case 1:case 0:r.add((0,V.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,V.now)()}));break}r.add((0,V.fromEvent)(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=(0,V.now)(),u=s-t,d=o-i;this.addRawSpeed(u,d,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=(0,V.now)(),s=0,o=(0,V.now)(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},d=async({done:c,value:l})=>{if(c)!t&&this.addRawSpeed(r,(0,V.now)()-a,1),this.concurrentDownloads.delete(e);else if(l){if(t){let h=(0,V.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-a;f&&this.addRawSpeed(s,f,1,t),s=l.byteLength,a=(0,V.now)()}else s+=l.byteLength;o=(0,V.now)()}else r+=l.byteLength,s+=l.byteLength,s>=this.tuningConfig.streamMinSampleSize&&(0,V.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,(0,V.now)()-o,this.concurrentDownloads.size),s=0,o=(0,V.now)());await i?.read().then(d,u)}};this.concurrentDownloads.add(e),i?.read().then(d,u)}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=V.safeStorage.get(e);if((0,V.isNonNullable)(t))return parseInt(t,10)??void 0}},is=Wr;var wi=require("@vkontakte/videoplayer-shared"),rs={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:wi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:wi.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},as=n=>({...(0,wi.fillWithDefault)(n,rs),configName:[...n.configName??[],...rs.configName]});var p=require("@vkontakte/videoplayer-shared");var Ye=require("@vkontakte/videoplayer-shared"),jr=({seekState:n,position$:e})=>(0,Ye.merge)(n.stateChangeEnded$.pipe((0,Ye.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,Ye.filter)(Ye.isNonNullable)),e.pipe((0,Ye.filter)(()=>n.getState().state==="none")));var ss=require("@vkontakte/videoplayer-shared"),ns=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return(0,ss.assertNonNullable)(e,`Wrong container or containerId {${n.container}}`),e};var ur=require("@vkontakte/videoplayer-shared"),os=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,ur.filter)(r=>r.length>0),(0,ur.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var Li=class{constructor(e={configName:[]}){this.subscription=new p.Subscription;this.logger=new p.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new p.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new N("stopped"),seekState:new N({state:"none"}),volume:new N({volume:1,muted:!1}),videoTrack:new N(void 0),videoStream:new N(void 0),audioStream:new N(void 0),autoVideoTrackSwitching:new N(!0),autoVideoTrackLimits:new N({}),isLooped:new N(!1),playbackRate:new N(1),externalTextTracks:new N([]),internalTextTracks:new N([]),currentTextTrack:new N(void 0),textTrackCuesSettings:new N({}),cameraOrientation:new N({x:0,y:0})};this.info={playbackState$:new p.ValueSubject("stopped"),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableVideoStreams$:new p.ValueSubject([]),currentVideoStream$:new p.ValueSubject(void 0),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),availableAudioStreams$:new p.ValueSubject([]),currentAudioStream$:new p.ValueSubject(void 0),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),currentPlaybackRate$:new p.ValueSubject(1),currentBuffer$:new p.ValueSubject({start:0,end:0}),isBuffering$:new p.ValueSubject(!0),isStalled$:new p.ValueSubject(!1),isEnded$:new p.ValueSubject(!1),isLooped$:new p.ValueSubject(!1),isLive$:new p.ValueSubject(void 0),canChangePlaybackSpeed$:new p.ValueSubject(void 0),atLiveEdge$:new p.ValueSubject(void 0),atLiveDurationEdge$:new p.ValueSubject(void 0),liveTime$:new p.ValueSubject(void 0),liveBufferTime$:new p.ValueSubject(void 0),currentFormat$:new p.ValueSubject(void 0),availableTextTracks$:new p.ValueSubject([]),currentTextTrack$:new p.ValueSubject(void 0),throughputEstimation$:new p.ValueSubject(void 0),rttEstimation$:new p.ValueSubject(void 0),videoBitrate$:new p.ValueSubject(void 0),hostname$:new p.ValueSubject(void 0),httpConnectionType$:new p.ValueSubject(void 0),httpConnectionReused$:new p.ValueSubject(void 0),surface$:new p.ValueSubject("none"),chromecastState$:new p.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new p.ValueSubject(void 0),intrinsicVideoSize$:new p.ValueSubject(void 0),availableSources$:new p.ValueSubject(void 0),is3DVideo$:new p.ValueSubject(!1),currentVideoSegmentLength$:new p.ValueSubject(0),currentAudioSegmentLength$:new p.ValueSubject(0)};this.events={inited$:new p.Subject,ready$:new p.Subject,started$:new p.Subject,playing$:new p.Subject,paused$:new p.Subject,stopped$:new p.Subject,willStart$:new p.Subject,willResume$:new p.Subject,willPause$:new p.Subject,willStop$:new p.Subject,willDestruct$:new p.Subject,watchCoverageRecord$:new p.Subject,watchCoverageLive$:new p.Subject,managedError$:new p.Subject,fatalError$:new p.Subject,ended$:new p.Subject,looped$:new p.Subject,seeked$:new p.Subject,willSeek$:new p.Subject,firstBytes$:new p.Subject,firstFrame$:new p.Subject,canplay$:new p.Subject,log$:new p.Subject};this.experimental={element$:new p.ValueSubject(void 0),tuningConfigName$:new p.ValueSubject([]),enableDebugTelemetry$:new p.ValueSubject(!1),dumpTelemetry:na};if(this.initLogs(),this.tuning=as(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new _i({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new is(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 u=s.map(l=>JSON.stringify(l,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),d=`Player.${String(i)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:p.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=ns(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Pi({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&&!Ut()?(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.once)()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let 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}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,p.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,p.filter)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){(0,p.assertNonNullable)(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 os(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((0,p.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,p.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width: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((0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.filter)(({from:e})=>e==="stopped"),(0,p.once)()).subscribe(()=>{this.initedAt=(0,p.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:p.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,p.map)(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,p.map)(s=>s.destination),(0,p.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,p.map)(s=>s.map(({quality:o})=>o).sort((o,u)=>(0,p.isInvariantQuality)(o)?1:(0,p.isInvariantQuality)(u)?-1:(0,p.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(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((0,p.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(s=>{this.desiredState.autoVideoTrackLimits.setState(s??{})})).add(e.providerOutput.currentBuffer$.pipe((0,p.map)(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((0,p.combine)({hasLiveOffsetByPaused:(0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(s=>s.to),(0,p.filterChanged)(),(0,p.map)(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((0,p.combine)({atLiveEdge:(0,p.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:jr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:s,position:o,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(o)<d/1e3}),(0,p.filterChanged)(),(0,p.tap)(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,p.map)(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add((0,p.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,p.map)(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,p.filterChanged)(),(0,p.tap)(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,p.map)(s=>s.muted),(0,p.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,p.map)(s=>s.volume),(0,p.filterChanged)()).subscribe(this.info.volume$)).add(jr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,p.merge)(e.providerOutput.endedEvent$.pipe((0,p.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,p.mapTo)(!1))).pipe((0,p.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,p.map)(s=>({id:s?`No${s}`:"NoProviders",category:p.ErrorCategory.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((0,p.once)(),(0,p.map)(s=>s??(0,p.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new p.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:s})=>s==="playing"),(0,p.once)()).subscribe(()=>i.next(!1)));let r=0,a=(0,p.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,p.map)(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),(0,p.filterChanged)());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((0,p.merge)(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((0,p.merge)(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(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),l;c==="CONNECTED"?l="second_screen":u?d?s?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,p.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new p.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,p.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t,i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=et(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,p.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,p.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;(0,p.assertNonNullable)(this.providerContainer),(0,p.assertNonNullable)(e),sa(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>aa(t)),this.providerContainer.current$.subscribe(({type:t})=>Ot("provider",t)),e.duration$.subscribe(t=>Ot("duration",t)),e.availableVideoTracks$.pipe((0,p.filter)(t=>!!t.length),(0,p.once)()).subscribe(t=>Ot("tracks",t)),this.events.fatalError$.subscribe(new ue("fatalError")),this.events.managedError$.subscribe(new ue("managedError")),e.position$.subscribe(new ue("position")),e.currentVideoTrack$.pipe((0,p.map)(t=>t?.quality)).subscribe(new ue("quality")),this.info.currentBuffer$.subscribe(new ue("buffer")),e.isBuffering$.subscribe(new ue("isBuffering"))].forEach(t=>this.subscription.add(t)),Ot("codecs",ba())}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:p.ErrorCategory.DOM,message:String(r)})})};this.subscription.add((0,p.merge)((0,p.fromEvent)(document,"visibilitychange"),(0,p.fromEvent)(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}};var Oe=require("@vkontakte/videoplayer-shared"),Pn=`@vkontakte/videoplayer-core@${Sr}`;
|